babylon.max.js 3.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. })();
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. Color3.prototype.getClassName = function () {
  62. return "Color3";
  63. };
  64. Color3.prototype.getHashCode = function () {
  65. var hash = this.r || 0;
  66. hash = (hash * 397) ^ (this.g || 0);
  67. hash = (hash * 397) ^ (this.b || 0);
  68. return hash;
  69. };
  70. // Operators
  71. Color3.prototype.toArray = function (array, index) {
  72. if (index === undefined) {
  73. index = 0;
  74. }
  75. array[index] = this.r;
  76. array[index + 1] = this.g;
  77. array[index + 2] = this.b;
  78. return this;
  79. };
  80. Color3.prototype.toColor4 = function (alpha) {
  81. if (alpha === void 0) { alpha = 1; }
  82. return new Color4(this.r, this.g, this.b, alpha);
  83. };
  84. Color3.prototype.asArray = function () {
  85. var result = [];
  86. this.toArray(result, 0);
  87. return result;
  88. };
  89. Color3.prototype.toLuminance = function () {
  90. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  91. };
  92. Color3.prototype.multiply = function (otherColor) {
  93. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  94. };
  95. Color3.prototype.multiplyToRef = function (otherColor, result) {
  96. result.r = this.r * otherColor.r;
  97. result.g = this.g * otherColor.g;
  98. result.b = this.b * otherColor.b;
  99. return this;
  100. };
  101. Color3.prototype.equals = function (otherColor) {
  102. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  103. };
  104. Color3.prototype.equalsFloats = function (r, g, b) {
  105. return this.r === r && this.g === g && this.b === b;
  106. };
  107. Color3.prototype.scale = function (scale) {
  108. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  109. };
  110. Color3.prototype.scaleToRef = function (scale, result) {
  111. result.r = this.r * scale;
  112. result.g = this.g * scale;
  113. result.b = this.b * scale;
  114. return this;
  115. };
  116. Color3.prototype.add = function (otherColor) {
  117. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  118. };
  119. Color3.prototype.addToRef = function (otherColor, result) {
  120. result.r = this.r + otherColor.r;
  121. result.g = this.g + otherColor.g;
  122. result.b = this.b + otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.subtract = function (otherColor) {
  126. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  127. };
  128. Color3.prototype.subtractToRef = function (otherColor, result) {
  129. result.r = this.r - otherColor.r;
  130. result.g = this.g - otherColor.g;
  131. result.b = this.b - otherColor.b;
  132. return this;
  133. };
  134. Color3.prototype.clone = function () {
  135. return new Color3(this.r, this.g, this.b);
  136. };
  137. Color3.prototype.copyFrom = function (source) {
  138. this.r = source.r;
  139. this.g = source.g;
  140. this.b = source.b;
  141. return this;
  142. };
  143. Color3.prototype.copyFromFloats = function (r, g, b) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. return this;
  148. };
  149. Color3.prototype.toHexString = function () {
  150. var intR = (this.r * 255) | 0;
  151. var intG = (this.g * 255) | 0;
  152. var intB = (this.b * 255) | 0;
  153. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  154. };
  155. Color3.prototype.toLinearSpace = function () {
  156. var convertedColor = new Color3();
  157. this.toLinearSpaceToRef(convertedColor);
  158. return convertedColor;
  159. };
  160. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  161. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  162. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  163. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  164. return this;
  165. };
  166. Color3.prototype.toGammaSpace = function () {
  167. var convertedColor = new Color3();
  168. this.toGammaSpaceToRef(convertedColor);
  169. return convertedColor;
  170. };
  171. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  172. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  173. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  174. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  175. return this;
  176. };
  177. // Statics
  178. Color3.FromHexString = function (hex) {
  179. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  180. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  181. return new Color3(0, 0, 0);
  182. }
  183. var r = parseInt(hex.substring(1, 3), 16);
  184. var g = parseInt(hex.substring(3, 5), 16);
  185. var b = parseInt(hex.substring(5, 7), 16);
  186. return Color3.FromInts(r, g, b);
  187. };
  188. Color3.FromArray = function (array, offset) {
  189. if (offset === void 0) { offset = 0; }
  190. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  191. };
  192. Color3.FromInts = function (r, g, b) {
  193. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  194. };
  195. Color3.Lerp = function (start, end, amount) {
  196. var r = start.r + ((end.r - start.r) * amount);
  197. var g = start.g + ((end.g - start.g) * amount);
  198. var b = start.b + ((end.b - start.b) * amount);
  199. return new Color3(r, g, b);
  200. };
  201. Color3.Red = function () { return new Color3(1, 0, 0); };
  202. Color3.Green = function () { return new Color3(0, 1, 0); };
  203. Color3.Blue = function () { return new Color3(0, 0, 1); };
  204. Color3.Black = function () { return new Color3(0, 0, 0); };
  205. Color3.White = function () { return new Color3(1, 1, 1); };
  206. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  207. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  208. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  209. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  210. return Color3;
  211. })();
  212. BABYLON.Color3 = Color3;
  213. var Color4 = (function () {
  214. function Color4(r, g, b, a) {
  215. this.r = r;
  216. this.g = g;
  217. this.b = b;
  218. this.a = a;
  219. }
  220. // Operators
  221. Color4.prototype.addInPlace = function (right) {
  222. this.r += right.r;
  223. this.g += right.g;
  224. this.b += right.b;
  225. this.a += right.a;
  226. return this;
  227. };
  228. Color4.prototype.asArray = function () {
  229. var result = [];
  230. this.toArray(result, 0);
  231. return result;
  232. };
  233. Color4.prototype.toArray = function (array, index) {
  234. if (index === undefined) {
  235. index = 0;
  236. }
  237. array[index] = this.r;
  238. array[index + 1] = this.g;
  239. array[index + 2] = this.b;
  240. array[index + 3] = this.a;
  241. return this;
  242. };
  243. Color4.prototype.add = function (right) {
  244. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  245. };
  246. Color4.prototype.subtract = function (right) {
  247. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  248. };
  249. Color4.prototype.subtractToRef = function (right, result) {
  250. result.r = this.r - right.r;
  251. result.g = this.g - right.g;
  252. result.b = this.b - right.b;
  253. result.a = this.a - right.a;
  254. return this;
  255. };
  256. Color4.prototype.scale = function (scale) {
  257. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  258. };
  259. Color4.prototype.scaleToRef = function (scale, result) {
  260. result.r = this.r * scale;
  261. result.g = this.g * scale;
  262. result.b = this.b * scale;
  263. result.a = this.a * scale;
  264. return this;
  265. };
  266. /**
  267. * Multipy an RGBA Color4 value by another and return a new Color4 object
  268. * @param color The Color4 (RGBA) value to multiply by
  269. * @returns A new Color4.
  270. */
  271. Color4.prototype.multiply = function (color) {
  272. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  273. };
  274. /**
  275. * Multipy an RGBA Color4 value by another and push the result in a reference value
  276. * @param color The Color4 (RGBA) value to multiply by
  277. * @param result The Color4 (RGBA) to fill the result in
  278. * @returns the result Color4.
  279. */
  280. Color4.prototype.multiplyToRef = function (color, result) {
  281. result.r = this.r * color.r;
  282. result.g = this.g * color.g;
  283. result.b = this.b * color.b;
  284. result.a = this.a * color.a;
  285. return result;
  286. };
  287. Color4.prototype.toString = function () {
  288. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  289. };
  290. Color4.prototype.getClassName = function () {
  291. return "Color4";
  292. };
  293. Color4.prototype.getHashCode = function () {
  294. var hash = this.r || 0;
  295. hash = (hash * 397) ^ (this.g || 0);
  296. hash = (hash * 397) ^ (this.b || 0);
  297. hash = (hash * 397) ^ (this.a || 0);
  298. return hash;
  299. };
  300. Color4.prototype.clone = function () {
  301. return new Color4(this.r, this.g, this.b, this.a);
  302. };
  303. Color4.prototype.copyFrom = function (source) {
  304. this.r = source.r;
  305. this.g = source.g;
  306. this.b = source.b;
  307. this.a = source.a;
  308. return this;
  309. };
  310. Color4.prototype.toHexString = function () {
  311. var intR = (this.r * 255) | 0;
  312. var intG = (this.g * 255) | 0;
  313. var intB = (this.b * 255) | 0;
  314. var intA = (this.a * 255) | 0;
  315. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  316. };
  317. // Statics
  318. Color4.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  320. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  321. return new Color4(0, 0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. var a = parseInt(hex.substring(7, 9), 16);
  327. return Color4.FromInts(r, g, b, a);
  328. };
  329. Color4.Lerp = function (left, right, amount) {
  330. var result = new Color4(0, 0, 0, 0);
  331. Color4.LerpToRef(left, right, amount, result);
  332. return result;
  333. };
  334. Color4.LerpToRef = function (left, right, amount, result) {
  335. result.r = left.r + (right.r - left.r) * amount;
  336. result.g = left.g + (right.g - left.g) * amount;
  337. result.b = left.b + (right.b - left.b) * amount;
  338. result.a = left.a + (right.a - left.a) * amount;
  339. };
  340. Color4.FromArray = function (array, offset) {
  341. if (offset === void 0) { offset = 0; }
  342. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  343. };
  344. Color4.FromInts = function (r, g, b, a) {
  345. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  346. };
  347. Color4.CheckColors4 = function (colors, count) {
  348. // Check if color3 was used
  349. if (colors.length === count * 3) {
  350. var colors4 = [];
  351. for (var index = 0; index < colors.length; index += 3) {
  352. var newIndex = (index / 3) * 4;
  353. colors4[newIndex] = colors[index];
  354. colors4[newIndex + 1] = colors[index + 1];
  355. colors4[newIndex + 2] = colors[index + 2];
  356. colors4[newIndex + 3] = 1.0;
  357. }
  358. return colors4;
  359. }
  360. return colors;
  361. };
  362. return Color4;
  363. })();
  364. BABYLON.Color4 = Color4;
  365. var Vector2 = (function () {
  366. function Vector2(x, y) {
  367. this.x = x;
  368. this.y = y;
  369. }
  370. Vector2.prototype.toString = function () {
  371. return "{X: " + this.x + " Y:" + this.y + "}";
  372. };
  373. Vector2.prototype.getClassName = function () {
  374. return "Vector2";
  375. };
  376. Vector2.prototype.getHashCode = function () {
  377. var hash = this.x || 0;
  378. hash = (hash * 397) ^ (this.y || 0);
  379. return hash;
  380. };
  381. // Operators
  382. Vector2.prototype.toArray = function (array, index) {
  383. if (index === void 0) { index = 0; }
  384. array[index] = this.x;
  385. array[index + 1] = this.y;
  386. return this;
  387. };
  388. Vector2.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. Vector2.prototype.copyFrom = function (source) {
  394. this.x = source.x;
  395. this.y = source.y;
  396. return this;
  397. };
  398. Vector2.prototype.copyFromFloats = function (x, y) {
  399. this.x = x;
  400. this.y = y;
  401. return this;
  402. };
  403. Vector2.prototype.add = function (otherVector) {
  404. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  405. };
  406. Vector2.prototype.addToRef = function (otherVector, result) {
  407. result.x = this.x + otherVector.x;
  408. result.y = this.y + otherVector.y;
  409. return this;
  410. };
  411. Vector2.prototype.addInPlace = function (otherVector) {
  412. this.x += otherVector.x;
  413. this.y += otherVector.y;
  414. return this;
  415. };
  416. Vector2.prototype.addVector3 = function (otherVector) {
  417. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  418. };
  419. Vector2.prototype.subtract = function (otherVector) {
  420. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  421. };
  422. Vector2.prototype.subtractToRef = function (otherVector, result) {
  423. result.x = this.x - otherVector.x;
  424. result.y = this.y - otherVector.y;
  425. return this;
  426. };
  427. Vector2.prototype.subtractInPlace = function (otherVector) {
  428. this.x -= otherVector.x;
  429. this.y -= otherVector.y;
  430. return this;
  431. };
  432. Vector2.prototype.multiplyInPlace = function (otherVector) {
  433. this.x *= otherVector.x;
  434. this.y *= otherVector.y;
  435. return this;
  436. };
  437. Vector2.prototype.multiply = function (otherVector) {
  438. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  439. };
  440. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  441. result.x = this.x * otherVector.x;
  442. result.y = this.y * otherVector.y;
  443. return this;
  444. };
  445. Vector2.prototype.multiplyByFloats = function (x, y) {
  446. return new Vector2(this.x * x, this.y * y);
  447. };
  448. Vector2.prototype.divide = function (otherVector) {
  449. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  450. };
  451. Vector2.prototype.divideToRef = function (otherVector, result) {
  452. result.x = this.x / otherVector.x;
  453. result.y = this.y / otherVector.y;
  454. return this;
  455. };
  456. Vector2.prototype.negate = function () {
  457. return new Vector2(-this.x, -this.y);
  458. };
  459. Vector2.prototype.scaleInPlace = function (scale) {
  460. this.x *= scale;
  461. this.y *= scale;
  462. return this;
  463. };
  464. Vector2.prototype.scale = function (scale) {
  465. return new Vector2(this.x * scale, this.y * scale);
  466. };
  467. Vector2.prototype.equals = function (otherVector) {
  468. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  469. };
  470. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  471. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  472. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  473. };
  474. // Properties
  475. Vector2.prototype.length = function () {
  476. return Math.sqrt(this.x * this.x + this.y * this.y);
  477. };
  478. Vector2.prototype.lengthSquared = function () {
  479. return (this.x * this.x + this.y * this.y);
  480. };
  481. // Methods
  482. Vector2.prototype.normalize = function () {
  483. var len = this.length();
  484. if (len === 0)
  485. return this;
  486. var num = 1.0 / len;
  487. this.x *= num;
  488. this.y *= num;
  489. return this;
  490. };
  491. Vector2.prototype.clone = function () {
  492. return new Vector2(this.x, this.y);
  493. };
  494. // Statics
  495. Vector2.Zero = function () {
  496. return new Vector2(0, 0);
  497. };
  498. Vector2.FromArray = function (array, offset) {
  499. if (offset === void 0) { offset = 0; }
  500. return new Vector2(array[offset], array[offset + 1]);
  501. };
  502. Vector2.FromArrayToRef = function (array, offset, result) {
  503. result.x = array[offset];
  504. result.y = array[offset + 1];
  505. };
  506. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  507. var squared = amount * amount;
  508. var cubed = amount * squared;
  509. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  510. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  511. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  512. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  513. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  514. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  515. return new Vector2(x, y);
  516. };
  517. Vector2.Clamp = function (value, min, max) {
  518. var x = value.x;
  519. x = (x > max.x) ? max.x : x;
  520. x = (x < min.x) ? min.x : x;
  521. var y = value.y;
  522. y = (y > max.y) ? max.y : y;
  523. y = (y < min.y) ? min.y : y;
  524. return new Vector2(x, y);
  525. };
  526. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  527. var squared = amount * amount;
  528. var cubed = amount * squared;
  529. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  530. var part2 = (-2.0 * cubed) + (3.0 * squared);
  531. var part3 = (cubed - (2.0 * squared)) + amount;
  532. var part4 = cubed - squared;
  533. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  534. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  535. return new Vector2(x, y);
  536. };
  537. Vector2.Lerp = function (start, end, amount) {
  538. var x = start.x + ((end.x - start.x) * amount);
  539. var y = start.y + ((end.y - start.y) * amount);
  540. return new Vector2(x, y);
  541. };
  542. Vector2.Dot = function (left, right) {
  543. return left.x * right.x + left.y * right.y;
  544. };
  545. Vector2.Normalize = function (vector) {
  546. var newVector = vector.clone();
  547. newVector.normalize();
  548. return newVector;
  549. };
  550. Vector2.Minimize = function (left, right) {
  551. var x = (left.x < right.x) ? left.x : right.x;
  552. var y = (left.y < right.y) ? left.y : right.y;
  553. return new Vector2(x, y);
  554. };
  555. Vector2.Maximize = function (left, right) {
  556. var x = (left.x > right.x) ? left.x : right.x;
  557. var y = (left.y > right.y) ? left.y : right.y;
  558. return new Vector2(x, y);
  559. };
  560. Vector2.Transform = function (vector, transformation) {
  561. var r = Vector2.Zero();
  562. Vector2.TransformToRef(vector, transformation, r);
  563. return r;
  564. };
  565. Vector2.TransformToRef = function (vector, transformation, result) {
  566. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  567. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  568. result.x = x;
  569. result.y = y;
  570. };
  571. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  572. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  573. var sign = a < 0 ? -1 : 1;
  574. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  575. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  576. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  577. };
  578. Vector2.Distance = function (value1, value2) {
  579. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  580. };
  581. Vector2.DistanceSquared = function (value1, value2) {
  582. var x = value1.x - value2.x;
  583. var y = value1.y - value2.y;
  584. return (x * x) + (y * y);
  585. };
  586. Vector2.Center = function (value1, value2) {
  587. var center = value1.add(value2);
  588. center.scaleInPlace(0.5);
  589. return center;
  590. };
  591. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  592. var l2 = Vector2.DistanceSquared(segA, segB);
  593. if (l2 === 0.0) {
  594. return Vector2.Distance(p, segA);
  595. }
  596. var v = segB.subtract(segA);
  597. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  598. var proj = segA.add(v.multiplyByFloats(t, t));
  599. return Vector2.Distance(p, proj);
  600. };
  601. return Vector2;
  602. })();
  603. BABYLON.Vector2 = Vector2;
  604. var Vector3 = (function () {
  605. function Vector3(x, y, z) {
  606. this.x = x;
  607. this.y = y;
  608. this.z = z;
  609. }
  610. Vector3.prototype.toString = function () {
  611. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  612. };
  613. Vector3.prototype.getClassName = function () {
  614. return "Vector3";
  615. };
  616. Vector3.prototype.getHashCode = function () {
  617. var hash = this.x || 0;
  618. hash = (hash * 397) ^ (this.y || 0);
  619. hash = (hash * 397) ^ (this.z || 0);
  620. return hash;
  621. };
  622. // Operators
  623. Vector3.prototype.asArray = function () {
  624. var result = [];
  625. this.toArray(result, 0);
  626. return result;
  627. };
  628. Vector3.prototype.toArray = function (array, index) {
  629. if (index === void 0) { index = 0; }
  630. array[index] = this.x;
  631. array[index + 1] = this.y;
  632. array[index + 2] = this.z;
  633. return this;
  634. };
  635. Vector3.prototype.toQuaternion = function () {
  636. var result = new Quaternion(0, 0, 0, 1);
  637. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  638. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  639. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  640. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  641. var cosy = Math.cos(this.y * 0.5);
  642. var siny = Math.sin(this.y * 0.5);
  643. result.x = coszMinusx * siny;
  644. result.y = -sinzMinusx * siny;
  645. result.z = sinxPlusz * cosy;
  646. result.w = cosxPlusz * cosy;
  647. return result;
  648. };
  649. Vector3.prototype.addInPlace = function (otherVector) {
  650. this.x += otherVector.x;
  651. this.y += otherVector.y;
  652. this.z += otherVector.z;
  653. return this;
  654. };
  655. Vector3.prototype.add = function (otherVector) {
  656. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  657. };
  658. Vector3.prototype.addToRef = function (otherVector, result) {
  659. result.x = this.x + otherVector.x;
  660. result.y = this.y + otherVector.y;
  661. result.z = this.z + otherVector.z;
  662. return this;
  663. };
  664. Vector3.prototype.subtractInPlace = function (otherVector) {
  665. this.x -= otherVector.x;
  666. this.y -= otherVector.y;
  667. this.z -= otherVector.z;
  668. return this;
  669. };
  670. Vector3.prototype.subtract = function (otherVector) {
  671. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  672. };
  673. Vector3.prototype.subtractToRef = function (otherVector, result) {
  674. result.x = this.x - otherVector.x;
  675. result.y = this.y - otherVector.y;
  676. result.z = this.z - otherVector.z;
  677. return this;
  678. };
  679. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  680. return new Vector3(this.x - x, this.y - y, this.z - z);
  681. };
  682. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  683. result.x = this.x - x;
  684. result.y = this.y - y;
  685. result.z = this.z - z;
  686. return this;
  687. };
  688. Vector3.prototype.negate = function () {
  689. return new Vector3(-this.x, -this.y, -this.z);
  690. };
  691. Vector3.prototype.scaleInPlace = function (scale) {
  692. this.x *= scale;
  693. this.y *= scale;
  694. this.z *= scale;
  695. return this;
  696. };
  697. Vector3.prototype.scale = function (scale) {
  698. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  699. };
  700. Vector3.prototype.scaleToRef = function (scale, result) {
  701. result.x = this.x * scale;
  702. result.y = this.y * scale;
  703. result.z = this.z * scale;
  704. };
  705. Vector3.prototype.equals = function (otherVector) {
  706. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  707. };
  708. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  709. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  710. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  711. };
  712. Vector3.prototype.equalsToFloats = function (x, y, z) {
  713. return this.x === x && this.y === y && this.z === z;
  714. };
  715. Vector3.prototype.multiplyInPlace = function (otherVector) {
  716. this.x *= otherVector.x;
  717. this.y *= otherVector.y;
  718. this.z *= otherVector.z;
  719. return this;
  720. };
  721. Vector3.prototype.multiply = function (otherVector) {
  722. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  723. };
  724. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  725. result.x = this.x * otherVector.x;
  726. result.y = this.y * otherVector.y;
  727. result.z = this.z * otherVector.z;
  728. return this;
  729. };
  730. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  731. return new Vector3(this.x * x, this.y * y, this.z * z);
  732. };
  733. Vector3.prototype.divide = function (otherVector) {
  734. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  735. };
  736. Vector3.prototype.divideToRef = function (otherVector, result) {
  737. result.x = this.x / otherVector.x;
  738. result.y = this.y / otherVector.y;
  739. result.z = this.z / otherVector.z;
  740. return this;
  741. };
  742. Vector3.prototype.MinimizeInPlace = function (other) {
  743. if (other.x < this.x)
  744. this.x = other.x;
  745. if (other.y < this.y)
  746. this.y = other.y;
  747. if (other.z < this.z)
  748. this.z = other.z;
  749. return this;
  750. };
  751. Vector3.prototype.MaximizeInPlace = function (other) {
  752. if (other.x > this.x)
  753. this.x = other.x;
  754. if (other.y > this.y)
  755. this.y = other.y;
  756. if (other.z > this.z)
  757. this.z = other.z;
  758. return this;
  759. };
  760. // Properties
  761. Vector3.prototype.length = function () {
  762. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  763. };
  764. Vector3.prototype.lengthSquared = function () {
  765. return (this.x * this.x + this.y * this.y + this.z * this.z);
  766. };
  767. // Methods
  768. Vector3.prototype.normalize = function () {
  769. var len = this.length();
  770. if (len === 0 || len === 1.0)
  771. return this;
  772. var num = 1.0 / len;
  773. this.x *= num;
  774. this.y *= num;
  775. this.z *= num;
  776. return this;
  777. };
  778. Vector3.prototype.clone = function () {
  779. return new Vector3(this.x, this.y, this.z);
  780. };
  781. Vector3.prototype.copyFrom = function (source) {
  782. this.x = source.x;
  783. this.y = source.y;
  784. this.z = source.z;
  785. return this;
  786. };
  787. Vector3.prototype.copyFromFloats = function (x, y, z) {
  788. this.x = x;
  789. this.y = y;
  790. this.z = z;
  791. return this;
  792. };
  793. // Statics
  794. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  795. var d0 = Vector3.Dot(vector0, axis) - size;
  796. var d1 = Vector3.Dot(vector1, axis) - size;
  797. var s = d0 / (d0 - d1);
  798. return s;
  799. };
  800. Vector3.FromArray = function (array, offset) {
  801. if (!offset) {
  802. offset = 0;
  803. }
  804. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  805. };
  806. Vector3.FromFloatArray = function (array, offset) {
  807. if (!offset) {
  808. offset = 0;
  809. }
  810. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  811. };
  812. Vector3.FromArrayToRef = function (array, offset, result) {
  813. result.x = array[offset];
  814. result.y = array[offset + 1];
  815. result.z = array[offset + 2];
  816. };
  817. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  818. result.x = array[offset];
  819. result.y = array[offset + 1];
  820. result.z = array[offset + 2];
  821. };
  822. Vector3.FromFloatsToRef = function (x, y, z, result) {
  823. result.x = x;
  824. result.y = y;
  825. result.z = z;
  826. };
  827. Vector3.Zero = function () {
  828. return new Vector3(0, 0, 0);
  829. };
  830. Vector3.Up = function () {
  831. return new Vector3(0, 1.0, 0);
  832. };
  833. Vector3.TransformCoordinates = function (vector, transformation) {
  834. var result = Vector3.Zero();
  835. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  836. return result;
  837. };
  838. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  839. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  840. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  841. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  842. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  843. result.x = x / w;
  844. result.y = y / w;
  845. result.z = z / w;
  846. };
  847. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  848. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  849. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  850. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  851. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  852. result.x = rx / rw;
  853. result.y = ry / rw;
  854. result.z = rz / rw;
  855. };
  856. Vector3.TransformNormal = function (vector, transformation) {
  857. var result = Vector3.Zero();
  858. Vector3.TransformNormalToRef(vector, transformation, result);
  859. return result;
  860. };
  861. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  862. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  863. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  864. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  865. };
  866. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  867. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  868. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  869. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  870. };
  871. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  872. var squared = amount * amount;
  873. var cubed = amount * squared;
  874. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  875. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  876. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  877. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  878. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  879. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  880. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  881. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  882. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  883. return new Vector3(x, y, z);
  884. };
  885. Vector3.Clamp = function (value, min, max) {
  886. var x = value.x;
  887. x = (x > max.x) ? max.x : x;
  888. x = (x < min.x) ? min.x : x;
  889. var y = value.y;
  890. y = (y > max.y) ? max.y : y;
  891. y = (y < min.y) ? min.y : y;
  892. var z = value.z;
  893. z = (z > max.z) ? max.z : z;
  894. z = (z < min.z) ? min.z : z;
  895. return new Vector3(x, y, z);
  896. };
  897. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  898. var squared = amount * amount;
  899. var cubed = amount * squared;
  900. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  901. var part2 = (-2.0 * cubed) + (3.0 * squared);
  902. var part3 = (cubed - (2.0 * squared)) + amount;
  903. var part4 = cubed - squared;
  904. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  905. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  906. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  907. return new Vector3(x, y, z);
  908. };
  909. Vector3.Lerp = function (start, end, amount) {
  910. var x = start.x + ((end.x - start.x) * amount);
  911. var y = start.y + ((end.y - start.y) * amount);
  912. var z = start.z + ((end.z - start.z) * amount);
  913. return new Vector3(x, y, z);
  914. };
  915. Vector3.Dot = function (left, right) {
  916. return (left.x * right.x + left.y * right.y + left.z * right.z);
  917. };
  918. Vector3.Cross = function (left, right) {
  919. var result = Vector3.Zero();
  920. Vector3.CrossToRef(left, right, result);
  921. return result;
  922. };
  923. Vector3.CrossToRef = function (left, right, result) {
  924. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  925. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  926. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  927. result.copyFrom(Tmp.Vector3[0]);
  928. };
  929. Vector3.Normalize = function (vector) {
  930. var result = Vector3.Zero();
  931. Vector3.NormalizeToRef(vector, result);
  932. return result;
  933. };
  934. Vector3.NormalizeToRef = function (vector, result) {
  935. result.copyFrom(vector);
  936. result.normalize();
  937. };
  938. Vector3.Project = function (vector, world, transform, viewport) {
  939. var cw = viewport.width;
  940. var ch = viewport.height;
  941. var cx = viewport.x;
  942. var cy = viewport.y;
  943. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  944. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1, viewportMatrix);
  945. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  946. world.multiplyToRef(transform, matrix);
  947. matrix.multiplyToRef(viewportMatrix, matrix);
  948. return Vector3.TransformCoordinates(vector, matrix);
  949. };
  950. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  951. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  952. world.multiplyToRef(transform, matrix);
  953. matrix.invert();
  954. source.x = source.x / viewportWidth * 2 - 1;
  955. source.y = -(source.y / viewportHeight * 2 - 1);
  956. var vector = Vector3.TransformCoordinates(source, matrix);
  957. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  958. if (MathTools.WithinEpsilon(num, 1.0)) {
  959. vector = vector.scale(1.0 / num);
  960. }
  961. return vector;
  962. };
  963. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  964. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  965. world.multiplyToRef(view, matrix);
  966. matrix.multiplyToRef(projection, matrix);
  967. matrix.invert();
  968. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  969. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  970. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  971. if (MathTools.WithinEpsilon(num, 1.0)) {
  972. vector = vector.scale(1.0 / num);
  973. }
  974. return vector;
  975. };
  976. Vector3.Minimize = function (left, right) {
  977. var min = left.clone();
  978. min.MinimizeInPlace(right);
  979. return min;
  980. };
  981. Vector3.Maximize = function (left, right) {
  982. var max = left.clone();
  983. max.MaximizeInPlace(right);
  984. return max;
  985. };
  986. Vector3.Distance = function (value1, value2) {
  987. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  988. };
  989. Vector3.DistanceSquared = function (value1, value2) {
  990. var x = value1.x - value2.x;
  991. var y = value1.y - value2.y;
  992. var z = value1.z - value2.z;
  993. return (x * x) + (y * y) + (z * z);
  994. };
  995. Vector3.Center = function (value1, value2) {
  996. var center = value1.add(value2);
  997. center.scaleInPlace(0.5);
  998. return center;
  999. };
  1000. /**
  1001. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1002. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1003. * to something in order to rotate it from its local system to the given target system.
  1004. */
  1005. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1006. var rotation = Vector3.Zero();
  1007. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1008. return rotation;
  1009. };
  1010. /**
  1011. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  1012. */
  1013. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1014. var u = axis1.normalize();
  1015. var w = axis3.normalize();
  1016. // world axis
  1017. var X = Axis.X;
  1018. var Y = Axis.Y;
  1019. // equation unknowns and vars
  1020. var yaw = 0.0;
  1021. var pitch = 0.0;
  1022. var roll = 0.0;
  1023. var x = 0.0;
  1024. var y = 0.0;
  1025. var z = 0.0;
  1026. var t = 0.0;
  1027. var sign = -1.0;
  1028. var nbRevert = 0;
  1029. var cross = Tmp.Vector3[0];
  1030. var dot = 0.0;
  1031. // step 1 : rotation around w
  1032. // Rv3(u) = u1, and u1 belongs to plane xOz
  1033. // Rv3(w) = w1 = w invariant
  1034. var u1 = Tmp.Vector3[1];
  1035. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1036. z = 1.0;
  1037. }
  1038. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1039. x = 1.0;
  1040. }
  1041. else {
  1042. t = w.z / w.x;
  1043. x = -t * Math.sqrt(1 / (1 + t * t));
  1044. z = Math.sqrt(1 / (1 + t * t));
  1045. }
  1046. u1.x = x;
  1047. u1.y = y;
  1048. u1.z = z;
  1049. u1.normalize();
  1050. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1051. cross.normalize();
  1052. if (Vector3.Dot(w, cross) < 0) {
  1053. sign = 1.0;
  1054. }
  1055. dot = Vector3.Dot(u, u1);
  1056. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1057. roll = Math.acos(dot) * sign;
  1058. if (Vector3.Dot(u1, X) < 0) {
  1059. roll = Math.PI + roll;
  1060. u1 = u1.scaleInPlace(-1);
  1061. nbRevert++;
  1062. }
  1063. // step 2 : rotate around u1
  1064. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1065. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1066. var w2 = Tmp.Vector3[2];
  1067. var v2 = Tmp.Vector3[3];
  1068. x = 0.0;
  1069. y = 0.0;
  1070. z = 0.0;
  1071. sign = -1.0;
  1072. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1073. x = 1.0;
  1074. }
  1075. else {
  1076. t = u1.z / u1.x;
  1077. x = -t * Math.sqrt(1 / (1 + t * t));
  1078. z = Math.sqrt(1 / (1 + t * t));
  1079. }
  1080. w2.x = x;
  1081. w2.y = y;
  1082. w2.z = z;
  1083. w2.normalize();
  1084. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1085. v2.normalize();
  1086. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1087. cross.normalize();
  1088. if (Vector3.Dot(u1, cross) < 0) {
  1089. sign = 1.0;
  1090. }
  1091. dot = Vector3.Dot(w, w2);
  1092. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1093. pitch = Math.acos(dot) * sign;
  1094. if (Vector3.Dot(v2, Y) < 0) {
  1095. pitch = Math.PI + pitch;
  1096. nbRevert++;
  1097. }
  1098. // step 3 : rotate around v2
  1099. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1100. sign = -1.0;
  1101. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1102. cross.normalize();
  1103. if (Vector3.Dot(cross, Y) < 0) {
  1104. sign = 1.0;
  1105. }
  1106. dot = Vector3.Dot(u1, X);
  1107. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1108. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1109. if (dot < 0 && nbRevert < 2) {
  1110. yaw = Math.PI + yaw;
  1111. }
  1112. ref.x = pitch;
  1113. ref.y = yaw;
  1114. ref.z = roll;
  1115. };
  1116. return Vector3;
  1117. })();
  1118. BABYLON.Vector3 = Vector3;
  1119. //Vector4 class created for EulerAngle class conversion to Quaternion
  1120. var Vector4 = (function () {
  1121. function Vector4(x, y, z, w) {
  1122. this.x = x;
  1123. this.y = y;
  1124. this.z = z;
  1125. this.w = w;
  1126. }
  1127. Vector4.prototype.toString = function () {
  1128. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1129. };
  1130. Vector4.prototype.getClassName = function () {
  1131. return "Vector4";
  1132. };
  1133. Vector4.prototype.getHashCode = function () {
  1134. var hash = this.x || 0;
  1135. hash = (hash * 397) ^ (this.y || 0);
  1136. hash = (hash * 397) ^ (this.z || 0);
  1137. hash = (hash * 397) ^ (this.w || 0);
  1138. return hash;
  1139. };
  1140. // Operators
  1141. Vector4.prototype.asArray = function () {
  1142. var result = [];
  1143. this.toArray(result, 0);
  1144. return result;
  1145. };
  1146. Vector4.prototype.toArray = function (array, index) {
  1147. if (index === undefined) {
  1148. index = 0;
  1149. }
  1150. array[index] = this.x;
  1151. array[index + 1] = this.y;
  1152. array[index + 2] = this.z;
  1153. array[index + 3] = this.w;
  1154. return this;
  1155. };
  1156. Vector4.prototype.addInPlace = function (otherVector) {
  1157. this.x += otherVector.x;
  1158. this.y += otherVector.y;
  1159. this.z += otherVector.z;
  1160. this.w += otherVector.w;
  1161. return this;
  1162. };
  1163. Vector4.prototype.add = function (otherVector) {
  1164. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1165. };
  1166. Vector4.prototype.addToRef = function (otherVector, result) {
  1167. result.x = this.x + otherVector.x;
  1168. result.y = this.y + otherVector.y;
  1169. result.z = this.z + otherVector.z;
  1170. result.w = this.w + otherVector.w;
  1171. return this;
  1172. };
  1173. Vector4.prototype.subtractInPlace = function (otherVector) {
  1174. this.x -= otherVector.x;
  1175. this.y -= otherVector.y;
  1176. this.z -= otherVector.z;
  1177. this.w -= otherVector.w;
  1178. return this;
  1179. };
  1180. Vector4.prototype.subtract = function (otherVector) {
  1181. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1182. };
  1183. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1184. result.x = this.x - otherVector.x;
  1185. result.y = this.y - otherVector.y;
  1186. result.z = this.z - otherVector.z;
  1187. result.w = this.w - otherVector.w;
  1188. return this;
  1189. };
  1190. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1191. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1192. };
  1193. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1194. result.x = this.x - x;
  1195. result.y = this.y - y;
  1196. result.z = this.z - z;
  1197. result.w = this.w - w;
  1198. return this;
  1199. };
  1200. Vector4.prototype.negate = function () {
  1201. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1202. };
  1203. Vector4.prototype.scaleInPlace = function (scale) {
  1204. this.x *= scale;
  1205. this.y *= scale;
  1206. this.z *= scale;
  1207. this.w *= scale;
  1208. return this;
  1209. };
  1210. Vector4.prototype.scale = function (scale) {
  1211. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1212. };
  1213. Vector4.prototype.scaleToRef = function (scale, result) {
  1214. result.x = this.x * scale;
  1215. result.y = this.y * scale;
  1216. result.z = this.z * scale;
  1217. result.w = this.w * scale;
  1218. };
  1219. Vector4.prototype.equals = function (otherVector) {
  1220. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1221. };
  1222. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1223. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1224. return otherVector
  1225. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1226. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1227. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1228. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1229. };
  1230. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1231. return this.x === x && this.y === y && this.z === z && this.w === w;
  1232. };
  1233. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1234. this.x *= otherVector.x;
  1235. this.y *= otherVector.y;
  1236. this.z *= otherVector.z;
  1237. this.w *= otherVector.w;
  1238. return this;
  1239. };
  1240. Vector4.prototype.multiply = function (otherVector) {
  1241. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1242. };
  1243. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1244. result.x = this.x * otherVector.x;
  1245. result.y = this.y * otherVector.y;
  1246. result.z = this.z * otherVector.z;
  1247. result.w = this.w * otherVector.w;
  1248. return this;
  1249. };
  1250. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1251. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1252. };
  1253. Vector4.prototype.divide = function (otherVector) {
  1254. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1255. };
  1256. Vector4.prototype.divideToRef = function (otherVector, result) {
  1257. result.x = this.x / otherVector.x;
  1258. result.y = this.y / otherVector.y;
  1259. result.z = this.z / otherVector.z;
  1260. result.w = this.w / otherVector.w;
  1261. return this;
  1262. };
  1263. Vector4.prototype.MinimizeInPlace = function (other) {
  1264. if (other.x < this.x)
  1265. this.x = other.x;
  1266. if (other.y < this.y)
  1267. this.y = other.y;
  1268. if (other.z < this.z)
  1269. this.z = other.z;
  1270. if (other.w < this.w)
  1271. this.w = other.w;
  1272. return this;
  1273. };
  1274. Vector4.prototype.MaximizeInPlace = function (other) {
  1275. if (other.x > this.x)
  1276. this.x = other.x;
  1277. if (other.y > this.y)
  1278. this.y = other.y;
  1279. if (other.z > this.z)
  1280. this.z = other.z;
  1281. if (other.w > this.w)
  1282. this.w = other.w;
  1283. return this;
  1284. };
  1285. // Properties
  1286. Vector4.prototype.length = function () {
  1287. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1288. };
  1289. Vector4.prototype.lengthSquared = function () {
  1290. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1291. };
  1292. // Methods
  1293. Vector4.prototype.normalize = function () {
  1294. var len = this.length();
  1295. if (len === 0)
  1296. return this;
  1297. var num = 1.0 / len;
  1298. this.x *= num;
  1299. this.y *= num;
  1300. this.z *= num;
  1301. this.w *= num;
  1302. return this;
  1303. };
  1304. Vector4.prototype.toVector3 = function () {
  1305. return new Vector3(this.x, this.y, this.z);
  1306. };
  1307. Vector4.prototype.clone = function () {
  1308. return new Vector4(this.x, this.y, this.z, this.w);
  1309. };
  1310. Vector4.prototype.copyFrom = function (source) {
  1311. this.x = source.x;
  1312. this.y = source.y;
  1313. this.z = source.z;
  1314. this.w = source.w;
  1315. return this;
  1316. };
  1317. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1318. this.x = x;
  1319. this.y = y;
  1320. this.z = z;
  1321. this.w = w;
  1322. return this;
  1323. };
  1324. // Statics
  1325. Vector4.FromArray = function (array, offset) {
  1326. if (!offset) {
  1327. offset = 0;
  1328. }
  1329. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1330. };
  1331. Vector4.FromArrayToRef = function (array, offset, result) {
  1332. result.x = array[offset];
  1333. result.y = array[offset + 1];
  1334. result.z = array[offset + 2];
  1335. result.w = array[offset + 3];
  1336. };
  1337. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1338. result.x = array[offset];
  1339. result.y = array[offset + 1];
  1340. result.z = array[offset + 2];
  1341. result.w = array[offset + 3];
  1342. };
  1343. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1344. result.x = x;
  1345. result.y = y;
  1346. result.z = z;
  1347. result.w = w;
  1348. };
  1349. Vector4.Zero = function () {
  1350. return new Vector4(0, 0, 0, 0);
  1351. };
  1352. Vector4.Normalize = function (vector) {
  1353. var result = Vector4.Zero();
  1354. Vector4.NormalizeToRef(vector, result);
  1355. return result;
  1356. };
  1357. Vector4.NormalizeToRef = function (vector, result) {
  1358. result.copyFrom(vector);
  1359. result.normalize();
  1360. };
  1361. Vector4.Minimize = function (left, right) {
  1362. var min = left.clone();
  1363. min.MinimizeInPlace(right);
  1364. return min;
  1365. };
  1366. Vector4.Maximize = function (left, right) {
  1367. var max = left.clone();
  1368. max.MaximizeInPlace(right);
  1369. return max;
  1370. };
  1371. Vector4.Distance = function (value1, value2) {
  1372. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1373. };
  1374. Vector4.DistanceSquared = function (value1, value2) {
  1375. var x = value1.x - value2.x;
  1376. var y = value1.y - value2.y;
  1377. var z = value1.z - value2.z;
  1378. var w = value1.w - value2.w;
  1379. return (x * x) + (y * y) + (z * z) + (w * w);
  1380. };
  1381. Vector4.Center = function (value1, value2) {
  1382. var center = value1.add(value2);
  1383. center.scaleInPlace(0.5);
  1384. return center;
  1385. };
  1386. return Vector4;
  1387. })();
  1388. BABYLON.Vector4 = Vector4;
  1389. var Size = (function () {
  1390. function Size(width, height) {
  1391. this.width = width;
  1392. this.height = height;
  1393. }
  1394. Size.prototype.toString = function () {
  1395. return "{W: " + this.width + ", H: " + this.height + "}";
  1396. };
  1397. Size.prototype.getClassName = function () {
  1398. return "Size";
  1399. };
  1400. Size.prototype.getHashCode = function () {
  1401. var hash = this.width || 0;
  1402. hash = (hash * 397) ^ (this.height || 0);
  1403. return hash;
  1404. };
  1405. Size.prototype.copyFrom = function (src) {
  1406. this.width = src.width;
  1407. this.height = src.height;
  1408. };
  1409. Size.prototype.copyFromFloats = function (width, height) {
  1410. this.width = width;
  1411. this.height = height;
  1412. };
  1413. Size.prototype.multiplyByFloats = function (w, h) {
  1414. return new Size(this.width * w, this.height * h);
  1415. };
  1416. Size.prototype.clone = function () {
  1417. return new Size(this.width, this.height);
  1418. };
  1419. Size.prototype.equals = function (other) {
  1420. if (!other) {
  1421. return false;
  1422. }
  1423. return (this.width === other.width) && (this.height === other.height);
  1424. };
  1425. Object.defineProperty(Size.prototype, "surface", {
  1426. get: function () {
  1427. return this.width * this.height;
  1428. },
  1429. enumerable: true,
  1430. configurable: true
  1431. });
  1432. Size.Zero = function () {
  1433. return new Size(0, 0);
  1434. };
  1435. Size.prototype.add = function (otherSize) {
  1436. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1437. return r;
  1438. };
  1439. Size.prototype.substract = function (otherSize) {
  1440. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1441. return r;
  1442. };
  1443. Size.Lerp = function (start, end, amount) {
  1444. var w = start.width + ((end.width - start.width) * amount);
  1445. var h = start.height + ((end.height - start.height) * amount);
  1446. return new Size(w, h);
  1447. };
  1448. return Size;
  1449. })();
  1450. BABYLON.Size = Size;
  1451. var Quaternion = (function () {
  1452. function Quaternion(x, y, z, w) {
  1453. if (x === void 0) { x = 0; }
  1454. if (y === void 0) { y = 0; }
  1455. if (z === void 0) { z = 0; }
  1456. if (w === void 0) { w = 1; }
  1457. this.x = x;
  1458. this.y = y;
  1459. this.z = z;
  1460. this.w = w;
  1461. }
  1462. Quaternion.prototype.toString = function () {
  1463. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1464. };
  1465. Quaternion.prototype.getClassName = function () {
  1466. return "Quaternion";
  1467. };
  1468. Quaternion.prototype.getHashCode = function () {
  1469. var hash = this.x || 0;
  1470. hash = (hash * 397) ^ (this.y || 0);
  1471. hash = (hash * 397) ^ (this.z || 0);
  1472. hash = (hash * 397) ^ (this.w || 0);
  1473. return hash;
  1474. };
  1475. Quaternion.prototype.asArray = function () {
  1476. return [this.x, this.y, this.z, this.w];
  1477. };
  1478. Quaternion.prototype.equals = function (otherQuaternion) {
  1479. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1480. };
  1481. Quaternion.prototype.clone = function () {
  1482. return new Quaternion(this.x, this.y, this.z, this.w);
  1483. };
  1484. Quaternion.prototype.copyFrom = function (other) {
  1485. this.x = other.x;
  1486. this.y = other.y;
  1487. this.z = other.z;
  1488. this.w = other.w;
  1489. return this;
  1490. };
  1491. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1492. this.x = x;
  1493. this.y = y;
  1494. this.z = z;
  1495. this.w = w;
  1496. return this;
  1497. };
  1498. Quaternion.prototype.add = function (other) {
  1499. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1500. };
  1501. Quaternion.prototype.subtract = function (other) {
  1502. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1503. };
  1504. Quaternion.prototype.scale = function (value) {
  1505. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1506. };
  1507. Quaternion.prototype.multiply = function (q1) {
  1508. var result = new Quaternion(0, 0, 0, 1.0);
  1509. this.multiplyToRef(q1, result);
  1510. return result;
  1511. };
  1512. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1513. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1514. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1515. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1516. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1517. result.copyFromFloats(x, y, z, w);
  1518. return this;
  1519. };
  1520. Quaternion.prototype.multiplyInPlace = function (q1) {
  1521. this.multiplyToRef(q1, this);
  1522. return this;
  1523. };
  1524. Quaternion.prototype.conjugateToRef = function (ref) {
  1525. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1526. return this;
  1527. };
  1528. Quaternion.prototype.conjugateInPlace = function () {
  1529. this.x *= -1;
  1530. this.y *= -1;
  1531. this.z *= -1;
  1532. return this;
  1533. };
  1534. Quaternion.prototype.conjugate = function () {
  1535. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1536. return result;
  1537. };
  1538. Quaternion.prototype.length = function () {
  1539. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1540. };
  1541. Quaternion.prototype.normalize = function () {
  1542. var length = 1.0 / this.length();
  1543. this.x *= length;
  1544. this.y *= length;
  1545. this.z *= length;
  1546. this.w *= length;
  1547. return this;
  1548. };
  1549. Quaternion.prototype.toEulerAngles = function (order) {
  1550. if (order === void 0) { order = "YZX"; }
  1551. var result = Vector3.Zero();
  1552. this.toEulerAnglesToRef(result, order);
  1553. return result;
  1554. };
  1555. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1556. if (order === void 0) { order = "YZX"; }
  1557. var heading, attitude, bank;
  1558. var x = this.x, y = this.y, z = this.z, w = this.w;
  1559. switch (order) {
  1560. case "YZX":
  1561. var test = x * y + z * w;
  1562. if (test > 0.499) {
  1563. heading = 2 * Math.atan2(x, w);
  1564. attitude = Math.PI / 2;
  1565. bank = 0;
  1566. }
  1567. if (test < -0.499) {
  1568. heading = -2 * Math.atan2(x, w);
  1569. attitude = -Math.PI / 2;
  1570. bank = 0;
  1571. }
  1572. if (isNaN(heading)) {
  1573. var sqx = x * x;
  1574. var sqy = y * y;
  1575. var sqz = z * z;
  1576. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1577. attitude = Math.asin(2 * test); // attitude
  1578. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1579. }
  1580. break;
  1581. default:
  1582. throw new Error("Euler order " + order + " not supported yet.");
  1583. }
  1584. result.y = heading;
  1585. result.z = attitude;
  1586. result.x = bank;
  1587. return this;
  1588. };
  1589. ;
  1590. Quaternion.prototype.toRotationMatrix = function (result) {
  1591. var xx = this.x * this.x;
  1592. var yy = this.y * this.y;
  1593. var zz = this.z * this.z;
  1594. var xy = this.x * this.y;
  1595. var zw = this.z * this.w;
  1596. var zx = this.z * this.x;
  1597. var yw = this.y * this.w;
  1598. var yz = this.y * this.z;
  1599. var xw = this.x * this.w;
  1600. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1601. result.m[1] = 2.0 * (xy + zw);
  1602. result.m[2] = 2.0 * (zx - yw);
  1603. result.m[3] = 0;
  1604. result.m[4] = 2.0 * (xy - zw);
  1605. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1606. result.m[6] = 2.0 * (yz + xw);
  1607. result.m[7] = 0;
  1608. result.m[8] = 2.0 * (zx + yw);
  1609. result.m[9] = 2.0 * (yz - xw);
  1610. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1611. result.m[11] = 0;
  1612. result.m[12] = 0;
  1613. result.m[13] = 0;
  1614. result.m[14] = 0;
  1615. result.m[15] = 1.0;
  1616. return this;
  1617. };
  1618. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1619. Quaternion.FromRotationMatrixToRef(matrix, this);
  1620. return this;
  1621. };
  1622. // Statics
  1623. Quaternion.FromRotationMatrix = function (matrix) {
  1624. var result = new Quaternion();
  1625. Quaternion.FromRotationMatrixToRef(matrix, result);
  1626. return result;
  1627. };
  1628. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1629. var data = matrix.m;
  1630. var m11 = data[0], m12 = data[4], m13 = data[8];
  1631. var m21 = data[1], m22 = data[5], m23 = data[9];
  1632. var m31 = data[2], m32 = data[6], m33 = data[10];
  1633. var trace = m11 + m22 + m33;
  1634. var s;
  1635. if (trace > 0) {
  1636. s = 0.5 / Math.sqrt(trace + 1.0);
  1637. result.w = 0.25 / s;
  1638. result.x = (m32 - m23) * s;
  1639. result.y = (m13 - m31) * s;
  1640. result.z = (m21 - m12) * s;
  1641. }
  1642. else if (m11 > m22 && m11 > m33) {
  1643. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1644. result.w = (m32 - m23) / s;
  1645. result.x = 0.25 * s;
  1646. result.y = (m12 + m21) / s;
  1647. result.z = (m13 + m31) / s;
  1648. }
  1649. else if (m22 > m33) {
  1650. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1651. result.w = (m13 - m31) / s;
  1652. result.x = (m12 + m21) / s;
  1653. result.y = 0.25 * s;
  1654. result.z = (m23 + m32) / s;
  1655. }
  1656. else {
  1657. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1658. result.w = (m21 - m12) / s;
  1659. result.x = (m13 + m31) / s;
  1660. result.y = (m23 + m32) / s;
  1661. result.z = 0.25 * s;
  1662. }
  1663. };
  1664. Quaternion.Inverse = function (q) {
  1665. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1666. };
  1667. Quaternion.Identity = function () {
  1668. return new Quaternion(0, 0, 0, 1);
  1669. };
  1670. Quaternion.RotationAxis = function (axis, angle) {
  1671. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1672. };
  1673. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1674. var sin = Math.sin(angle / 2);
  1675. axis.normalize();
  1676. result.w = Math.cos(angle / 2);
  1677. result.x = axis.x * sin;
  1678. result.y = axis.y * sin;
  1679. result.z = axis.z * sin;
  1680. return result;
  1681. };
  1682. Quaternion.FromArray = function (array, offset) {
  1683. if (!offset) {
  1684. offset = 0;
  1685. }
  1686. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1687. };
  1688. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1689. var q = new Quaternion();
  1690. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1691. return q;
  1692. };
  1693. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1694. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1695. var halfRoll = roll * 0.5;
  1696. var halfPitch = pitch * 0.5;
  1697. var halfYaw = yaw * 0.5;
  1698. var sinRoll = Math.sin(halfRoll);
  1699. var cosRoll = Math.cos(halfRoll);
  1700. var sinPitch = Math.sin(halfPitch);
  1701. var cosPitch = Math.cos(halfPitch);
  1702. var sinYaw = Math.sin(halfYaw);
  1703. var cosYaw = Math.cos(halfYaw);
  1704. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1705. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1706. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1707. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1708. };
  1709. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1710. var result = new Quaternion();
  1711. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1712. return result;
  1713. };
  1714. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1715. // Produces a quaternion from Euler angles in the z-x-z orientation
  1716. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1717. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1718. var halfBeta = beta * 0.5;
  1719. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1720. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1721. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1722. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1723. };
  1724. Quaternion.Slerp = function (left, right, amount) {
  1725. var num2;
  1726. var num3;
  1727. var num = amount;
  1728. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1729. var flag = false;
  1730. if (num4 < 0) {
  1731. flag = true;
  1732. num4 = -num4;
  1733. }
  1734. if (num4 > 0.999999) {
  1735. num3 = 1 - num;
  1736. num2 = flag ? -num : num;
  1737. }
  1738. else {
  1739. var num5 = Math.acos(num4);
  1740. var num6 = (1.0 / Math.sin(num5));
  1741. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1742. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1743. }
  1744. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1745. };
  1746. return Quaternion;
  1747. })();
  1748. BABYLON.Quaternion = Quaternion;
  1749. var Matrix = (function () {
  1750. function Matrix() {
  1751. this.m = new Float32Array(16);
  1752. }
  1753. // Properties
  1754. Matrix.prototype.isIdentity = function () {
  1755. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1756. return false;
  1757. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1758. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1759. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1760. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1761. return false;
  1762. return true;
  1763. };
  1764. Matrix.prototype.determinant = function () {
  1765. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1766. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1767. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1768. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1769. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1770. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1771. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1772. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1773. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1774. };
  1775. // Methods
  1776. Matrix.prototype.toArray = function () {
  1777. return this.m;
  1778. };
  1779. Matrix.prototype.asArray = function () {
  1780. return this.toArray();
  1781. };
  1782. Matrix.prototype.invert = function () {
  1783. this.invertToRef(this);
  1784. return this;
  1785. };
  1786. Matrix.prototype.reset = function () {
  1787. for (var index = 0; index < 16; index++) {
  1788. this.m[index] = 0;
  1789. }
  1790. return this;
  1791. };
  1792. Matrix.prototype.add = function (other) {
  1793. var result = new Matrix();
  1794. this.addToRef(other, result);
  1795. return result;
  1796. };
  1797. Matrix.prototype.addToRef = function (other, result) {
  1798. for (var index = 0; index < 16; index++) {
  1799. result.m[index] = this.m[index] + other.m[index];
  1800. }
  1801. return this;
  1802. };
  1803. Matrix.prototype.addToSelf = function (other) {
  1804. for (var index = 0; index < 16; index++) {
  1805. this.m[index] += other.m[index];
  1806. }
  1807. return this;
  1808. };
  1809. Matrix.prototype.invertToRef = function (other) {
  1810. var l1 = this.m[0];
  1811. var l2 = this.m[1];
  1812. var l3 = this.m[2];
  1813. var l4 = this.m[3];
  1814. var l5 = this.m[4];
  1815. var l6 = this.m[5];
  1816. var l7 = this.m[6];
  1817. var l8 = this.m[7];
  1818. var l9 = this.m[8];
  1819. var l10 = this.m[9];
  1820. var l11 = this.m[10];
  1821. var l12 = this.m[11];
  1822. var l13 = this.m[12];
  1823. var l14 = this.m[13];
  1824. var l15 = this.m[14];
  1825. var l16 = this.m[15];
  1826. var l17 = (l11 * l16) - (l12 * l15);
  1827. var l18 = (l10 * l16) - (l12 * l14);
  1828. var l19 = (l10 * l15) - (l11 * l14);
  1829. var l20 = (l9 * l16) - (l12 * l13);
  1830. var l21 = (l9 * l15) - (l11 * l13);
  1831. var l22 = (l9 * l14) - (l10 * l13);
  1832. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1833. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1834. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1835. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1836. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1837. var l28 = (l7 * l16) - (l8 * l15);
  1838. var l29 = (l6 * l16) - (l8 * l14);
  1839. var l30 = (l6 * l15) - (l7 * l14);
  1840. var l31 = (l5 * l16) - (l8 * l13);
  1841. var l32 = (l5 * l15) - (l7 * l13);
  1842. var l33 = (l5 * l14) - (l6 * l13);
  1843. var l34 = (l7 * l12) - (l8 * l11);
  1844. var l35 = (l6 * l12) - (l8 * l10);
  1845. var l36 = (l6 * l11) - (l7 * l10);
  1846. var l37 = (l5 * l12) - (l8 * l9);
  1847. var l38 = (l5 * l11) - (l7 * l9);
  1848. var l39 = (l5 * l10) - (l6 * l9);
  1849. other.m[0] = l23 * l27;
  1850. other.m[4] = l24 * l27;
  1851. other.m[8] = l25 * l27;
  1852. other.m[12] = l26 * l27;
  1853. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1854. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1855. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1856. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1857. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1858. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1859. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1860. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1861. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1862. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1863. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1864. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1865. return this;
  1866. };
  1867. Matrix.prototype.setTranslation = function (vector3) {
  1868. this.m[12] = vector3.x;
  1869. this.m[13] = vector3.y;
  1870. this.m[14] = vector3.z;
  1871. return this;
  1872. };
  1873. Matrix.prototype.getTranslation = function () {
  1874. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1875. };
  1876. Matrix.prototype.multiply = function (other) {
  1877. var result = new Matrix();
  1878. this.multiplyToRef(other, result);
  1879. return result;
  1880. };
  1881. Matrix.prototype.copyFrom = function (other) {
  1882. for (var index = 0; index < 16; index++) {
  1883. this.m[index] = other.m[index];
  1884. }
  1885. return this;
  1886. };
  1887. Matrix.prototype.copyToArray = function (array, offset) {
  1888. if (offset === void 0) { offset = 0; }
  1889. for (var index = 0; index < 16; index++) {
  1890. array[offset + index] = this.m[index];
  1891. }
  1892. return this;
  1893. };
  1894. Matrix.prototype.multiplyToRef = function (other, result) {
  1895. this.multiplyToArray(other, result.m, 0);
  1896. return this;
  1897. };
  1898. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1899. var tm0 = this.m[0];
  1900. var tm1 = this.m[1];
  1901. var tm2 = this.m[2];
  1902. var tm3 = this.m[3];
  1903. var tm4 = this.m[4];
  1904. var tm5 = this.m[5];
  1905. var tm6 = this.m[6];
  1906. var tm7 = this.m[7];
  1907. var tm8 = this.m[8];
  1908. var tm9 = this.m[9];
  1909. var tm10 = this.m[10];
  1910. var tm11 = this.m[11];
  1911. var tm12 = this.m[12];
  1912. var tm13 = this.m[13];
  1913. var tm14 = this.m[14];
  1914. var tm15 = this.m[15];
  1915. var om0 = other.m[0];
  1916. var om1 = other.m[1];
  1917. var om2 = other.m[2];
  1918. var om3 = other.m[3];
  1919. var om4 = other.m[4];
  1920. var om5 = other.m[5];
  1921. var om6 = other.m[6];
  1922. var om7 = other.m[7];
  1923. var om8 = other.m[8];
  1924. var om9 = other.m[9];
  1925. var om10 = other.m[10];
  1926. var om11 = other.m[11];
  1927. var om12 = other.m[12];
  1928. var om13 = other.m[13];
  1929. var om14 = other.m[14];
  1930. var om15 = other.m[15];
  1931. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1932. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1933. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1934. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1935. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1936. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1937. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1938. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1939. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1940. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1941. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1942. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1943. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1944. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1945. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1946. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1947. return this;
  1948. };
  1949. Matrix.prototype.equals = function (value) {
  1950. return value &&
  1951. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1952. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1953. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1954. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1955. };
  1956. Matrix.prototype.clone = function () {
  1957. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1958. };
  1959. Matrix.prototype.getClassName = function () {
  1960. return "Matrix";
  1961. };
  1962. Matrix.prototype.getHashCode = function () {
  1963. var hash = this.m[0] || 0;
  1964. for (var i = 1; i < 16; i++) {
  1965. hash = (hash * 397) ^ (this.m[i] || 0);
  1966. }
  1967. return hash;
  1968. };
  1969. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1970. translation.x = this.m[12];
  1971. translation.y = this.m[13];
  1972. translation.z = this.m[14];
  1973. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1974. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1975. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1976. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1977. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1978. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1979. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1980. rotation.x = 0;
  1981. rotation.y = 0;
  1982. rotation.z = 0;
  1983. rotation.w = 1;
  1984. return false;
  1985. }
  1986. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1987. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1988. return true;
  1989. };
  1990. // Statics
  1991. Matrix.FromArray = function (array, offset) {
  1992. var result = new Matrix();
  1993. if (!offset) {
  1994. offset = 0;
  1995. }
  1996. Matrix.FromArrayToRef(array, offset, result);
  1997. return result;
  1998. };
  1999. Matrix.FromArrayToRef = function (array, offset, result) {
  2000. for (var index = 0; index < 16; index++) {
  2001. result.m[index] = array[index + offset];
  2002. }
  2003. };
  2004. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  2005. for (var index = 0; index < 16; index++) {
  2006. result.m[index] = array[index + offset] * scale;
  2007. }
  2008. };
  2009. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2010. result.m[0] = initialM11;
  2011. result.m[1] = initialM12;
  2012. result.m[2] = initialM13;
  2013. result.m[3] = initialM14;
  2014. result.m[4] = initialM21;
  2015. result.m[5] = initialM22;
  2016. result.m[6] = initialM23;
  2017. result.m[7] = initialM24;
  2018. result.m[8] = initialM31;
  2019. result.m[9] = initialM32;
  2020. result.m[10] = initialM33;
  2021. result.m[11] = initialM34;
  2022. result.m[12] = initialM41;
  2023. result.m[13] = initialM42;
  2024. result.m[14] = initialM43;
  2025. result.m[15] = initialM44;
  2026. };
  2027. Matrix.prototype.getRow = function (index) {
  2028. if (index < 0 || index > 3) {
  2029. return null;
  2030. }
  2031. var i = index * 4;
  2032. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2033. };
  2034. Matrix.prototype.setRow = function (index, row) {
  2035. if (index < 0 || index > 3) {
  2036. return this;
  2037. }
  2038. var i = index * 4;
  2039. this.m[i + 0] = row.x;
  2040. this.m[i + 1] = row.y;
  2041. this.m[i + 2] = row.z;
  2042. this.m[i + 3] = row.w;
  2043. return this;
  2044. };
  2045. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2046. var result = new Matrix();
  2047. result.m[0] = initialM11;
  2048. result.m[1] = initialM12;
  2049. result.m[2] = initialM13;
  2050. result.m[3] = initialM14;
  2051. result.m[4] = initialM21;
  2052. result.m[5] = initialM22;
  2053. result.m[6] = initialM23;
  2054. result.m[7] = initialM24;
  2055. result.m[8] = initialM31;
  2056. result.m[9] = initialM32;
  2057. result.m[10] = initialM33;
  2058. result.m[11] = initialM34;
  2059. result.m[12] = initialM41;
  2060. result.m[13] = initialM42;
  2061. result.m[14] = initialM43;
  2062. result.m[15] = initialM44;
  2063. return result;
  2064. };
  2065. Matrix.Compose = function (scale, rotation, translation) {
  2066. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2067. var rotationMatrix = Matrix.Identity();
  2068. rotation.toRotationMatrix(rotationMatrix);
  2069. result = result.multiply(rotationMatrix);
  2070. result.setTranslation(translation);
  2071. return result;
  2072. };
  2073. Matrix.Identity = function () {
  2074. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2075. };
  2076. Matrix.IdentityToRef = function (result) {
  2077. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2078. };
  2079. Matrix.Zero = function () {
  2080. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2081. };
  2082. Matrix.RotationX = function (angle) {
  2083. var result = new Matrix();
  2084. Matrix.RotationXToRef(angle, result);
  2085. return result;
  2086. };
  2087. Matrix.Invert = function (source) {
  2088. var result = new Matrix();
  2089. source.invertToRef(result);
  2090. return result;
  2091. };
  2092. Matrix.RotationXToRef = function (angle, result) {
  2093. var s = Math.sin(angle);
  2094. var c = Math.cos(angle);
  2095. result.m[0] = 1.0;
  2096. result.m[15] = 1.0;
  2097. result.m[5] = c;
  2098. result.m[10] = c;
  2099. result.m[9] = -s;
  2100. result.m[6] = s;
  2101. result.m[1] = 0;
  2102. result.m[2] = 0;
  2103. result.m[3] = 0;
  2104. result.m[4] = 0;
  2105. result.m[7] = 0;
  2106. result.m[8] = 0;
  2107. result.m[11] = 0;
  2108. result.m[12] = 0;
  2109. result.m[13] = 0;
  2110. result.m[14] = 0;
  2111. };
  2112. Matrix.RotationY = function (angle) {
  2113. var result = new Matrix();
  2114. Matrix.RotationYToRef(angle, result);
  2115. return result;
  2116. };
  2117. Matrix.RotationYToRef = function (angle, result) {
  2118. var s = Math.sin(angle);
  2119. var c = Math.cos(angle);
  2120. result.m[5] = 1.0;
  2121. result.m[15] = 1.0;
  2122. result.m[0] = c;
  2123. result.m[2] = -s;
  2124. result.m[8] = s;
  2125. result.m[10] = c;
  2126. result.m[1] = 0;
  2127. result.m[3] = 0;
  2128. result.m[4] = 0;
  2129. result.m[6] = 0;
  2130. result.m[7] = 0;
  2131. result.m[9] = 0;
  2132. result.m[11] = 0;
  2133. result.m[12] = 0;
  2134. result.m[13] = 0;
  2135. result.m[14] = 0;
  2136. };
  2137. Matrix.RotationZ = function (angle) {
  2138. var result = new Matrix();
  2139. Matrix.RotationZToRef(angle, result);
  2140. return result;
  2141. };
  2142. Matrix.RotationZToRef = function (angle, result) {
  2143. var s = Math.sin(angle);
  2144. var c = Math.cos(angle);
  2145. result.m[10] = 1.0;
  2146. result.m[15] = 1.0;
  2147. result.m[0] = c;
  2148. result.m[1] = s;
  2149. result.m[4] = -s;
  2150. result.m[5] = c;
  2151. result.m[2] = 0;
  2152. result.m[3] = 0;
  2153. result.m[6] = 0;
  2154. result.m[7] = 0;
  2155. result.m[8] = 0;
  2156. result.m[9] = 0;
  2157. result.m[11] = 0;
  2158. result.m[12] = 0;
  2159. result.m[13] = 0;
  2160. result.m[14] = 0;
  2161. };
  2162. Matrix.RotationAxis = function (axis, angle) {
  2163. var result = Matrix.Zero();
  2164. Matrix.RotationAxisToRef(axis, angle, result);
  2165. return result;
  2166. };
  2167. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2168. var s = Math.sin(-angle);
  2169. var c = Math.cos(-angle);
  2170. var c1 = 1 - c;
  2171. axis.normalize();
  2172. result.m[0] = (axis.x * axis.x) * c1 + c;
  2173. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2174. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2175. result.m[3] = 0.0;
  2176. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2177. result.m[5] = (axis.y * axis.y) * c1 + c;
  2178. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2179. result.m[7] = 0.0;
  2180. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2181. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2182. result.m[10] = (axis.z * axis.z) * c1 + c;
  2183. result.m[11] = 0.0;
  2184. result.m[15] = 1.0;
  2185. };
  2186. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2187. var result = new Matrix();
  2188. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2189. return result;
  2190. };
  2191. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2192. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2193. this._tempQuaternion.toRotationMatrix(result);
  2194. };
  2195. Matrix.Scaling = function (x, y, z) {
  2196. var result = Matrix.Zero();
  2197. Matrix.ScalingToRef(x, y, z, result);
  2198. return result;
  2199. };
  2200. Matrix.ScalingToRef = function (x, y, z, result) {
  2201. result.m[0] = x;
  2202. result.m[1] = 0;
  2203. result.m[2] = 0;
  2204. result.m[3] = 0;
  2205. result.m[4] = 0;
  2206. result.m[5] = y;
  2207. result.m[6] = 0;
  2208. result.m[7] = 0;
  2209. result.m[8] = 0;
  2210. result.m[9] = 0;
  2211. result.m[10] = z;
  2212. result.m[11] = 0;
  2213. result.m[12] = 0;
  2214. result.m[13] = 0;
  2215. result.m[14] = 0;
  2216. result.m[15] = 1.0;
  2217. };
  2218. Matrix.Translation = function (x, y, z) {
  2219. var result = Matrix.Identity();
  2220. Matrix.TranslationToRef(x, y, z, result);
  2221. return result;
  2222. };
  2223. Matrix.TranslationToRef = function (x, y, z, result) {
  2224. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2225. };
  2226. Matrix.Lerp = function (startValue, endValue, gradient) {
  2227. var result = Matrix.Zero();
  2228. for (var index = 0; index < 16; index++) {
  2229. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2230. }
  2231. return result;
  2232. };
  2233. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2234. var startScale = new Vector3(0, 0, 0);
  2235. var startRotation = new Quaternion();
  2236. var startTranslation = new Vector3(0, 0, 0);
  2237. startValue.decompose(startScale, startRotation, startTranslation);
  2238. var endScale = new Vector3(0, 0, 0);
  2239. var endRotation = new Quaternion();
  2240. var endTranslation = new Vector3(0, 0, 0);
  2241. endValue.decompose(endScale, endRotation, endTranslation);
  2242. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2243. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2244. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2245. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2246. };
  2247. Matrix.LookAtLH = function (eye, target, up) {
  2248. var result = Matrix.Zero();
  2249. Matrix.LookAtLHToRef(eye, target, up, result);
  2250. return result;
  2251. };
  2252. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2253. // Z axis
  2254. target.subtractToRef(eye, this._zAxis);
  2255. this._zAxis.normalize();
  2256. // X axis
  2257. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2258. if (this._xAxis.lengthSquared() === 0) {
  2259. this._xAxis.x = 1.0;
  2260. }
  2261. else {
  2262. this._xAxis.normalize();
  2263. }
  2264. // Y axis
  2265. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2266. this._yAxis.normalize();
  2267. // Eye angles
  2268. var ex = -Vector3.Dot(this._xAxis, eye);
  2269. var ey = -Vector3.Dot(this._yAxis, eye);
  2270. var ez = -Vector3.Dot(this._zAxis, eye);
  2271. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  2272. };
  2273. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2274. var matrix = Matrix.Zero();
  2275. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2276. return matrix;
  2277. };
  2278. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2279. var hw = 2.0 / width;
  2280. var hh = 2.0 / height;
  2281. var id = 1.0 / (zfar - znear);
  2282. var nid = znear / (znear - zfar);
  2283. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2284. };
  2285. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2286. var matrix = Matrix.Zero();
  2287. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2288. return matrix;
  2289. };
  2290. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2291. result.m[0] = 2.0 / (right - left);
  2292. result.m[1] = result.m[2] = result.m[3] = 0;
  2293. result.m[5] = 2.0 / (top - bottom);
  2294. result.m[4] = result.m[6] = result.m[7] = 0;
  2295. result.m[10] = -1.0 / (znear - zfar);
  2296. result.m[8] = result.m[9] = result.m[11] = 0;
  2297. result.m[12] = (left + right) / (left - right);
  2298. result.m[13] = (top + bottom) / (bottom - top);
  2299. result.m[14] = znear / (znear - zfar);
  2300. result.m[15] = 1.0;
  2301. };
  2302. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2303. var matrix = Matrix.Zero();
  2304. matrix.m[0] = (2.0 * znear) / width;
  2305. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2306. matrix.m[5] = (2.0 * znear) / height;
  2307. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2308. matrix.m[10] = -zfar / (znear - zfar);
  2309. matrix.m[8] = matrix.m[9] = 0.0;
  2310. matrix.m[11] = 1.0;
  2311. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2312. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2313. return matrix;
  2314. };
  2315. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2316. var matrix = Matrix.Zero();
  2317. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2318. return matrix;
  2319. };
  2320. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2321. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2322. var tan = 1.0 / (Math.tan(fov * 0.5));
  2323. if (isVerticalFovFixed) {
  2324. result.m[0] = tan / aspect;
  2325. }
  2326. else {
  2327. result.m[0] = tan;
  2328. }
  2329. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2330. if (isVerticalFovFixed) {
  2331. result.m[5] = tan;
  2332. }
  2333. else {
  2334. result.m[5] = tan * aspect;
  2335. }
  2336. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2337. result.m[8] = result.m[9] = 0.0;
  2338. result.m[10] = -zfar / (znear - zfar);
  2339. result.m[11] = 1.0;
  2340. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2341. result.m[14] = (znear * zfar) / (znear - zfar);
  2342. };
  2343. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2344. var cw = viewport.width;
  2345. var ch = viewport.height;
  2346. var cx = viewport.x;
  2347. var cy = viewport.y;
  2348. 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);
  2349. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2350. };
  2351. Matrix.GetAsMatrix2x2 = function (matrix) {
  2352. return new Float32Array([
  2353. matrix.m[0], matrix.m[1],
  2354. matrix.m[4], matrix.m[5]
  2355. ]);
  2356. };
  2357. Matrix.GetAsMatrix3x3 = function (matrix) {
  2358. return new Float32Array([
  2359. matrix.m[0], matrix.m[1], matrix.m[2],
  2360. matrix.m[4], matrix.m[5], matrix.m[6],
  2361. matrix.m[8], matrix.m[9], matrix.m[10]
  2362. ]);
  2363. };
  2364. Matrix.Transpose = function (matrix) {
  2365. var result = new Matrix();
  2366. result.m[0] = matrix.m[0];
  2367. result.m[1] = matrix.m[4];
  2368. result.m[2] = matrix.m[8];
  2369. result.m[3] = matrix.m[12];
  2370. result.m[4] = matrix.m[1];
  2371. result.m[5] = matrix.m[5];
  2372. result.m[6] = matrix.m[9];
  2373. result.m[7] = matrix.m[13];
  2374. result.m[8] = matrix.m[2];
  2375. result.m[9] = matrix.m[6];
  2376. result.m[10] = matrix.m[10];
  2377. result.m[11] = matrix.m[14];
  2378. result.m[12] = matrix.m[3];
  2379. result.m[13] = matrix.m[7];
  2380. result.m[14] = matrix.m[11];
  2381. result.m[15] = matrix.m[15];
  2382. return result;
  2383. };
  2384. Matrix.Reflection = function (plane) {
  2385. var matrix = new Matrix();
  2386. Matrix.ReflectionToRef(plane, matrix);
  2387. return matrix;
  2388. };
  2389. Matrix.ReflectionToRef = function (plane, result) {
  2390. plane.normalize();
  2391. var x = plane.normal.x;
  2392. var y = plane.normal.y;
  2393. var z = plane.normal.z;
  2394. var temp = -2 * x;
  2395. var temp2 = -2 * y;
  2396. var temp3 = -2 * z;
  2397. result.m[0] = (temp * x) + 1;
  2398. result.m[1] = temp2 * x;
  2399. result.m[2] = temp3 * x;
  2400. result.m[3] = 0.0;
  2401. result.m[4] = temp * y;
  2402. result.m[5] = (temp2 * y) + 1;
  2403. result.m[6] = temp3 * y;
  2404. result.m[7] = 0.0;
  2405. result.m[8] = temp * z;
  2406. result.m[9] = temp2 * z;
  2407. result.m[10] = (temp3 * z) + 1;
  2408. result.m[11] = 0.0;
  2409. result.m[12] = temp * plane.d;
  2410. result.m[13] = temp2 * plane.d;
  2411. result.m[14] = temp3 * plane.d;
  2412. result.m[15] = 1.0;
  2413. };
  2414. Matrix._tempQuaternion = new Quaternion();
  2415. Matrix._xAxis = Vector3.Zero();
  2416. Matrix._yAxis = Vector3.Zero();
  2417. Matrix._zAxis = Vector3.Zero();
  2418. return Matrix;
  2419. })();
  2420. BABYLON.Matrix = Matrix;
  2421. var Plane = (function () {
  2422. function Plane(a, b, c, d) {
  2423. this.normal = new Vector3(a, b, c);
  2424. this.d = d;
  2425. }
  2426. Plane.prototype.asArray = function () {
  2427. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2428. };
  2429. // Methods
  2430. Plane.prototype.clone = function () {
  2431. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2432. };
  2433. Plane.prototype.getClassName = function () {
  2434. return "Plane";
  2435. };
  2436. Plane.prototype.getHashCode = function () {
  2437. var hash = this.normal.getHashCode();
  2438. hash = (hash * 397) ^ (this.d || 0);
  2439. return hash;
  2440. };
  2441. Plane.prototype.normalize = function () {
  2442. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2443. var magnitude = 0;
  2444. if (norm !== 0) {
  2445. magnitude = 1.0 / norm;
  2446. }
  2447. this.normal.x *= magnitude;
  2448. this.normal.y *= magnitude;
  2449. this.normal.z *= magnitude;
  2450. this.d *= magnitude;
  2451. return this;
  2452. };
  2453. Plane.prototype.transform = function (transformation) {
  2454. var transposedMatrix = Matrix.Transpose(transformation);
  2455. var x = this.normal.x;
  2456. var y = this.normal.y;
  2457. var z = this.normal.z;
  2458. var d = this.d;
  2459. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2460. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2461. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2462. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2463. return new Plane(normalX, normalY, normalZ, finalD);
  2464. };
  2465. Plane.prototype.dotCoordinate = function (point) {
  2466. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2467. };
  2468. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2469. var x1 = point2.x - point1.x;
  2470. var y1 = point2.y - point1.y;
  2471. var z1 = point2.z - point1.z;
  2472. var x2 = point3.x - point1.x;
  2473. var y2 = point3.y - point1.y;
  2474. var z2 = point3.z - point1.z;
  2475. var yz = (y1 * z2) - (z1 * y2);
  2476. var xz = (z1 * x2) - (x1 * z2);
  2477. var xy = (x1 * y2) - (y1 * x2);
  2478. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2479. var invPyth;
  2480. if (pyth !== 0) {
  2481. invPyth = 1.0 / pyth;
  2482. }
  2483. else {
  2484. invPyth = 0;
  2485. }
  2486. this.normal.x = yz * invPyth;
  2487. this.normal.y = xz * invPyth;
  2488. this.normal.z = xy * invPyth;
  2489. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2490. return this;
  2491. };
  2492. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2493. var dot = Vector3.Dot(this.normal, direction);
  2494. return (dot <= epsilon);
  2495. };
  2496. Plane.prototype.signedDistanceTo = function (point) {
  2497. return Vector3.Dot(point, this.normal) + this.d;
  2498. };
  2499. // Statics
  2500. Plane.FromArray = function (array) {
  2501. return new Plane(array[0], array[1], array[2], array[3]);
  2502. };
  2503. Plane.FromPoints = function (point1, point2, point3) {
  2504. var result = new Plane(0, 0, 0, 0);
  2505. result.copyFromPoints(point1, point2, point3);
  2506. return result;
  2507. };
  2508. Plane.FromPositionAndNormal = function (origin, normal) {
  2509. var result = new Plane(0, 0, 0, 0);
  2510. normal.normalize();
  2511. result.normal = normal;
  2512. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2513. return result;
  2514. };
  2515. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2516. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2517. return Vector3.Dot(point, normal) + d;
  2518. };
  2519. return Plane;
  2520. })();
  2521. BABYLON.Plane = Plane;
  2522. var Viewport = (function () {
  2523. function Viewport(x, y, width, height) {
  2524. this.x = x;
  2525. this.y = y;
  2526. this.width = width;
  2527. this.height = height;
  2528. }
  2529. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2530. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2531. };
  2532. return Viewport;
  2533. })();
  2534. BABYLON.Viewport = Viewport;
  2535. var Frustum = (function () {
  2536. function Frustum() {
  2537. }
  2538. Frustum.GetPlanes = function (transform) {
  2539. var frustumPlanes = [];
  2540. for (var index = 0; index < 6; index++) {
  2541. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2542. }
  2543. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2544. return frustumPlanes;
  2545. };
  2546. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2547. // Near
  2548. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2549. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2550. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2551. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2552. frustumPlanes[0].normalize();
  2553. // Far
  2554. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2555. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2556. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2557. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2558. frustumPlanes[1].normalize();
  2559. // Left
  2560. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2561. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2562. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2563. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2564. frustumPlanes[2].normalize();
  2565. // Right
  2566. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2567. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2568. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2569. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2570. frustumPlanes[3].normalize();
  2571. // Top
  2572. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2573. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2574. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2575. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2576. frustumPlanes[4].normalize();
  2577. // Bottom
  2578. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2579. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2580. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2581. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2582. frustumPlanes[5].normalize();
  2583. };
  2584. return Frustum;
  2585. })();
  2586. BABYLON.Frustum = Frustum;
  2587. (function (Space) {
  2588. Space[Space["LOCAL"] = 0] = "LOCAL";
  2589. Space[Space["WORLD"] = 1] = "WORLD";
  2590. })(BABYLON.Space || (BABYLON.Space = {}));
  2591. var Space = BABYLON.Space;
  2592. var Axis = (function () {
  2593. function Axis() {
  2594. }
  2595. Axis.X = new Vector3(1, 0, 0);
  2596. Axis.Y = new Vector3(0, 1, 0);
  2597. Axis.Z = new Vector3(0, 0, 1);
  2598. return Axis;
  2599. })();
  2600. BABYLON.Axis = Axis;
  2601. ;
  2602. var BezierCurve = (function () {
  2603. function BezierCurve() {
  2604. }
  2605. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2606. // Extract X (which is equal to time here)
  2607. var f0 = 1 - 3 * x2 + 3 * x1;
  2608. var f1 = 3 * x2 - 6 * x1;
  2609. var f2 = 3 * x1;
  2610. var refinedT = t;
  2611. for (var i = 0; i < 5; i++) {
  2612. var refinedT2 = refinedT * refinedT;
  2613. var refinedT3 = refinedT2 * refinedT;
  2614. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2615. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2616. refinedT -= (x - t) * slope;
  2617. refinedT = Math.min(1, Math.max(0, refinedT));
  2618. }
  2619. // Resolve cubic bezier for the given x
  2620. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2621. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2622. Math.pow(refinedT, 3);
  2623. };
  2624. return BezierCurve;
  2625. })();
  2626. BABYLON.BezierCurve = BezierCurve;
  2627. (function (Orientation) {
  2628. Orientation[Orientation["CW"] = 0] = "CW";
  2629. Orientation[Orientation["CCW"] = 1] = "CCW";
  2630. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2631. var Orientation = BABYLON.Orientation;
  2632. var Angle = (function () {
  2633. function Angle(radians) {
  2634. var _this = this;
  2635. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2636. this.radians = function () { return _this._radians; };
  2637. this._radians = radians;
  2638. if (this._radians < 0)
  2639. this._radians += (2 * Math.PI);
  2640. }
  2641. Angle.BetweenTwoPoints = function (a, b) {
  2642. var delta = b.subtract(a);
  2643. var theta = Math.atan2(delta.y, delta.x);
  2644. return new Angle(theta);
  2645. };
  2646. Angle.FromRadians = function (radians) {
  2647. return new Angle(radians);
  2648. };
  2649. Angle.FromDegrees = function (degrees) {
  2650. return new Angle(degrees * Math.PI / 180);
  2651. };
  2652. return Angle;
  2653. })();
  2654. BABYLON.Angle = Angle;
  2655. var Arc2 = (function () {
  2656. function Arc2(startPoint, midPoint, endPoint) {
  2657. this.startPoint = startPoint;
  2658. this.midPoint = midPoint;
  2659. this.endPoint = endPoint;
  2660. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2661. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2662. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2663. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2664. 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);
  2665. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2666. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2667. var a1 = this.startAngle.degrees();
  2668. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2669. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2670. // angles correction
  2671. if (a2 - a1 > +180.0)
  2672. a2 -= 360.0;
  2673. if (a2 - a1 < -180.0)
  2674. a2 += 360.0;
  2675. if (a3 - a2 > +180.0)
  2676. a3 -= 360.0;
  2677. if (a3 - a2 < -180.0)
  2678. a3 += 360.0;
  2679. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2680. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2681. }
  2682. return Arc2;
  2683. })();
  2684. BABYLON.Arc2 = Arc2;
  2685. var Path2 = (function () {
  2686. function Path2(x, y) {
  2687. this._points = new Array();
  2688. this._length = 0;
  2689. this.closed = false;
  2690. this._points.push(new Vector2(x, y));
  2691. }
  2692. Path2.prototype.addLineTo = function (x, y) {
  2693. if (closed) {
  2694. //Tools.Error("cannot add lines to closed paths");
  2695. return this;
  2696. }
  2697. var newPoint = new Vector2(x, y);
  2698. var previousPoint = this._points[this._points.length - 1];
  2699. this._points.push(newPoint);
  2700. this._length += newPoint.subtract(previousPoint).length();
  2701. return this;
  2702. };
  2703. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2704. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2705. if (closed) {
  2706. //Tools.Error("cannot add arcs to closed paths");
  2707. return this;
  2708. }
  2709. var startPoint = this._points[this._points.length - 1];
  2710. var midPoint = new Vector2(midX, midY);
  2711. var endPoint = new Vector2(endX, endY);
  2712. var arc = new Arc2(startPoint, midPoint, endPoint);
  2713. var increment = arc.angle.radians() / numberOfSegments;
  2714. if (arc.orientation === Orientation.CW)
  2715. increment *= -1;
  2716. var currentAngle = arc.startAngle.radians() + increment;
  2717. for (var i = 0; i < numberOfSegments; i++) {
  2718. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2719. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2720. this.addLineTo(x, y);
  2721. currentAngle += increment;
  2722. }
  2723. return this;
  2724. };
  2725. Path2.prototype.close = function () {
  2726. this.closed = true;
  2727. return this;
  2728. };
  2729. Path2.prototype.length = function () {
  2730. var result = this._length;
  2731. if (!this.closed) {
  2732. var lastPoint = this._points[this._points.length - 1];
  2733. var firstPoint = this._points[0];
  2734. result += (firstPoint.subtract(lastPoint).length());
  2735. }
  2736. return result;
  2737. };
  2738. Path2.prototype.getPoints = function () {
  2739. return this._points;
  2740. };
  2741. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2742. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2743. //Tools.Error("normalized length position should be between 0 and 1.");
  2744. return Vector2.Zero();
  2745. }
  2746. var lengthPosition = normalizedLengthPosition * this.length();
  2747. var previousOffset = 0;
  2748. for (var i = 0; i < this._points.length; i++) {
  2749. var j = (i + 1) % this._points.length;
  2750. var a = this._points[i];
  2751. var b = this._points[j];
  2752. var bToA = b.subtract(a);
  2753. var nextOffset = (bToA.length() + previousOffset);
  2754. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2755. var dir = bToA.normalize();
  2756. var localOffset = lengthPosition - previousOffset;
  2757. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2758. }
  2759. previousOffset = nextOffset;
  2760. }
  2761. //Tools.Error("internal error");
  2762. return Vector2.Zero();
  2763. };
  2764. Path2.StartingAt = function (x, y) {
  2765. return new Path2(x, y);
  2766. };
  2767. return Path2;
  2768. })();
  2769. BABYLON.Path2 = Path2;
  2770. var Path3D = (function () {
  2771. /**
  2772. * new Path3D(path, normal, raw)
  2773. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2774. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2775. * path : an array of Vector3, the curve axis of the Path3D
  2776. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2777. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2778. */
  2779. function Path3D(path, firstNormal, raw) {
  2780. this.path = path;
  2781. this._curve = new Array();
  2782. this._distances = new Array();
  2783. this._tangents = new Array();
  2784. this._normals = new Array();
  2785. this._binormals = new Array();
  2786. for (var p = 0; p < path.length; p++) {
  2787. this._curve[p] = path[p].clone(); // hard copy
  2788. }
  2789. this._raw = raw || false;
  2790. this._compute(firstNormal);
  2791. }
  2792. /**
  2793. * Returns the Path3D array of successive Vector3 designing its curve.
  2794. */
  2795. Path3D.prototype.getCurve = function () {
  2796. return this._curve;
  2797. };
  2798. /**
  2799. * Returns an array populated with tangent vectors on each Path3D curve point.
  2800. */
  2801. Path3D.prototype.getTangents = function () {
  2802. return this._tangents;
  2803. };
  2804. /**
  2805. * Returns an array populated with normal vectors on each Path3D curve point.
  2806. */
  2807. Path3D.prototype.getNormals = function () {
  2808. return this._normals;
  2809. };
  2810. /**
  2811. * Returns an array populated with binormal vectors on each Path3D curve point.
  2812. */
  2813. Path3D.prototype.getBinormals = function () {
  2814. return this._binormals;
  2815. };
  2816. /**
  2817. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2818. */
  2819. Path3D.prototype.getDistances = function () {
  2820. return this._distances;
  2821. };
  2822. /**
  2823. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2824. * Returns the same object updated.
  2825. */
  2826. Path3D.prototype.update = function (path, firstNormal) {
  2827. for (var p = 0; p < path.length; p++) {
  2828. this._curve[p].x = path[p].x;
  2829. this._curve[p].y = path[p].y;
  2830. this._curve[p].z = path[p].z;
  2831. }
  2832. this._compute(firstNormal);
  2833. return this;
  2834. };
  2835. // private function compute() : computes tangents, normals and binormals
  2836. Path3D.prototype._compute = function (firstNormal) {
  2837. var l = this._curve.length;
  2838. // first and last tangents
  2839. this._tangents[0] = this._getFirstNonNullVector(0);
  2840. if (!this._raw) {
  2841. this._tangents[0].normalize();
  2842. }
  2843. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2844. if (!this._raw) {
  2845. this._tangents[l - 1].normalize();
  2846. }
  2847. // normals and binormals at first point : arbitrary vector with _normalVector()
  2848. var tg0 = this._tangents[0];
  2849. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2850. this._normals[0] = pp0;
  2851. if (!this._raw) {
  2852. this._normals[0].normalize();
  2853. }
  2854. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2855. if (!this._raw) {
  2856. this._binormals[0].normalize();
  2857. }
  2858. this._distances[0] = 0.0;
  2859. // normals and binormals : next points
  2860. var prev; // previous vector (segment)
  2861. var cur; // current vector (segment)
  2862. var curTang; // current tangent
  2863. // previous normal
  2864. var prevBinor; // previous binormal
  2865. for (var i = 1; i < l; i++) {
  2866. // tangents
  2867. prev = this._getLastNonNullVector(i);
  2868. if (i < l - 1) {
  2869. cur = this._getFirstNonNullVector(i);
  2870. this._tangents[i] = prev.add(cur);
  2871. this._tangents[i].normalize();
  2872. }
  2873. this._distances[i] = this._distances[i - 1] + prev.length();
  2874. // normals and binormals
  2875. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2876. curTang = this._tangents[i];
  2877. prevBinor = this._binormals[i - 1];
  2878. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2879. if (!this._raw) {
  2880. this._normals[i].normalize();
  2881. }
  2882. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2883. if (!this._raw) {
  2884. this._binormals[i].normalize();
  2885. }
  2886. }
  2887. };
  2888. // private function getFirstNonNullVector(index)
  2889. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2890. Path3D.prototype._getFirstNonNullVector = function (index) {
  2891. var i = 1;
  2892. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2893. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2894. i++;
  2895. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2896. }
  2897. return nNVector;
  2898. };
  2899. // private function getLastNonNullVector(index)
  2900. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2901. Path3D.prototype._getLastNonNullVector = function (index) {
  2902. var i = 1;
  2903. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2904. while (nLVector.length() === 0 && index > i + 1) {
  2905. i++;
  2906. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2907. }
  2908. return nLVector;
  2909. };
  2910. // private function normalVector(v0, vt, va) :
  2911. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2912. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2913. Path3D.prototype._normalVector = function (v0, vt, va) {
  2914. var normal0;
  2915. var tgl = vt.length();
  2916. if (tgl === 0.0) {
  2917. tgl = 1.0;
  2918. }
  2919. if (va === undefined || va === null) {
  2920. var point;
  2921. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  2922. point = new Vector3(0.0, -1.0, 0.0);
  2923. }
  2924. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  2925. point = new Vector3(1.0, 0.0, 0.0);
  2926. }
  2927. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  2928. point = new Vector3(0.0, 0.0, 1.0);
  2929. }
  2930. normal0 = Vector3.Cross(vt, point);
  2931. }
  2932. else {
  2933. normal0 = Vector3.Cross(vt, va);
  2934. Vector3.CrossToRef(normal0, vt, normal0);
  2935. }
  2936. normal0.normalize();
  2937. return normal0;
  2938. };
  2939. return Path3D;
  2940. })();
  2941. BABYLON.Path3D = Path3D;
  2942. var Curve3 = (function () {
  2943. /**
  2944. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  2945. * A Curve3 is designed from a series of successive Vector3.
  2946. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  2947. */
  2948. function Curve3(points) {
  2949. this._length = 0.0;
  2950. this._points = points;
  2951. this._length = this._computeLength(points);
  2952. }
  2953. /**
  2954. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  2955. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  2956. * @param v1 (Vector3) the control point
  2957. * @param v2 (Vector3) the end point of the Quadratic Bezier
  2958. * @param nbPoints (integer) the wanted number of points in the curve
  2959. */
  2960. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2961. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2962. var bez = new Array();
  2963. var equation = function (t, val0, val1, val2) {
  2964. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  2965. return res;
  2966. };
  2967. for (var i = 0; i <= nbPoints; i++) {
  2968. 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)));
  2969. }
  2970. return new Curve3(bez);
  2971. };
  2972. /**
  2973. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  2974. * @param v0 (Vector3) the origin point of the Cubic Bezier
  2975. * @param v1 (Vector3) the first control point
  2976. * @param v2 (Vector3) the second control point
  2977. * @param v3 (Vector3) the end point of the Cubic Bezier
  2978. * @param nbPoints (integer) the wanted number of points in the curve
  2979. */
  2980. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2981. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2982. var bez = new Array();
  2983. var equation = function (t, val0, val1, val2, val3) {
  2984. 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;
  2985. return res;
  2986. };
  2987. for (var i = 0; i <= nbPoints; i++) {
  2988. 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)));
  2989. }
  2990. return new Curve3(bez);
  2991. };
  2992. /**
  2993. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  2994. * @param p1 (Vector3) the origin point of the Hermite Spline
  2995. * @param t1 (Vector3) the tangent vector at the origin point
  2996. * @param p2 (Vector3) the end point of the Hermite Spline
  2997. * @param t2 (Vector3) the tangent vector at the end point
  2998. * @param nbPoints (integer) the wanted number of points in the curve
  2999. */
  3000. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3001. var hermite = new Array();
  3002. var step = 1.0 / nbPoints;
  3003. for (var i = 0; i <= nbPoints; i++) {
  3004. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3005. }
  3006. return new Curve3(hermite);
  3007. };
  3008. /**
  3009. * Returns the Curve3 stored array of successive Vector3
  3010. */
  3011. Curve3.prototype.getPoints = function () {
  3012. return this._points;
  3013. };
  3014. /**
  3015. * Returns the computed length (float) of the curve.
  3016. */
  3017. Curve3.prototype.length = function () {
  3018. return this._length;
  3019. };
  3020. /**
  3021. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3022. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3023. * curveA and curveB keep unchanged.
  3024. */
  3025. Curve3.prototype.continue = function (curve) {
  3026. var lastPoint = this._points[this._points.length - 1];
  3027. var continuedPoints = this._points.slice();
  3028. var curvePoints = curve.getPoints();
  3029. for (var i = 1; i < curvePoints.length; i++) {
  3030. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3031. }
  3032. var continuedCurve = new Curve3(continuedPoints);
  3033. return continuedCurve;
  3034. };
  3035. Curve3.prototype._computeLength = function (path) {
  3036. var l = 0;
  3037. for (var i = 1; i < path.length; i++) {
  3038. l += (path[i].subtract(path[i - 1])).length();
  3039. }
  3040. return l;
  3041. };
  3042. return Curve3;
  3043. })();
  3044. BABYLON.Curve3 = Curve3;
  3045. // SphericalHarmonics
  3046. var SphericalHarmonics = (function () {
  3047. function SphericalHarmonics() {
  3048. this.L00 = Vector3.Zero();
  3049. this.L1_1 = Vector3.Zero();
  3050. this.L10 = Vector3.Zero();
  3051. this.L11 = Vector3.Zero();
  3052. this.L2_2 = Vector3.Zero();
  3053. this.L2_1 = Vector3.Zero();
  3054. this.L20 = Vector3.Zero();
  3055. this.L21 = Vector3.Zero();
  3056. this.L22 = Vector3.Zero();
  3057. }
  3058. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3059. var colorVector = new Vector3(color.r, color.g, color.b);
  3060. var c = colorVector.scale(deltaSolidAngle);
  3061. this.L00 = this.L00.add(c.scale(0.282095));
  3062. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3063. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3064. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3065. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3066. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3067. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3068. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3069. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3070. };
  3071. SphericalHarmonics.prototype.scale = function (scale) {
  3072. this.L00 = this.L00.scale(scale);
  3073. this.L1_1 = this.L1_1.scale(scale);
  3074. this.L10 = this.L10.scale(scale);
  3075. this.L11 = this.L11.scale(scale);
  3076. this.L2_2 = this.L2_2.scale(scale);
  3077. this.L2_1 = this.L2_1.scale(scale);
  3078. this.L20 = this.L20.scale(scale);
  3079. this.L21 = this.L21.scale(scale);
  3080. this.L22 = this.L22.scale(scale);
  3081. };
  3082. return SphericalHarmonics;
  3083. })();
  3084. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3085. // SphericalPolynomial
  3086. var SphericalPolynomial = (function () {
  3087. function SphericalPolynomial() {
  3088. this.x = Vector3.Zero();
  3089. this.y = Vector3.Zero();
  3090. this.z = Vector3.Zero();
  3091. this.xx = Vector3.Zero();
  3092. this.yy = Vector3.Zero();
  3093. this.zz = Vector3.Zero();
  3094. this.xy = Vector3.Zero();
  3095. this.yz = Vector3.Zero();
  3096. this.zx = Vector3.Zero();
  3097. }
  3098. SphericalPolynomial.prototype.addAmbient = function (color) {
  3099. var colorVector = new Vector3(color.r, color.g, color.b);
  3100. this.xx = this.xx.add(colorVector);
  3101. this.yy = this.yy.add(colorVector);
  3102. this.zz = this.zz.add(colorVector);
  3103. };
  3104. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3105. var result = new SphericalPolynomial();
  3106. result.x = harmonics.L11.scale(1.02333);
  3107. result.y = harmonics.L1_1.scale(1.02333);
  3108. result.z = harmonics.L10.scale(1.02333);
  3109. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3110. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3111. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3112. result.yz = harmonics.L2_1.scale(0.858086);
  3113. result.zx = harmonics.L21.scale(0.858086);
  3114. result.xy = harmonics.L2_2.scale(0.858086);
  3115. return result;
  3116. };
  3117. return SphericalPolynomial;
  3118. })();
  3119. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3120. // Vertex formats
  3121. var PositionNormalVertex = (function () {
  3122. function PositionNormalVertex(position, normal) {
  3123. if (position === void 0) { position = Vector3.Zero(); }
  3124. if (normal === void 0) { normal = Vector3.Up(); }
  3125. this.position = position;
  3126. this.normal = normal;
  3127. }
  3128. PositionNormalVertex.prototype.clone = function () {
  3129. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3130. };
  3131. return PositionNormalVertex;
  3132. })();
  3133. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3134. var PositionNormalTextureVertex = (function () {
  3135. function PositionNormalTextureVertex(position, normal, uv) {
  3136. if (position === void 0) { position = Vector3.Zero(); }
  3137. if (normal === void 0) { normal = Vector3.Up(); }
  3138. if (uv === void 0) { uv = Vector2.Zero(); }
  3139. this.position = position;
  3140. this.normal = normal;
  3141. this.uv = uv;
  3142. }
  3143. PositionNormalTextureVertex.prototype.clone = function () {
  3144. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3145. };
  3146. return PositionNormalTextureVertex;
  3147. })();
  3148. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3149. // Temporary pre-allocated objects for engine internal use
  3150. // usage in any internal function :
  3151. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3152. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3153. var Tmp = (function () {
  3154. function Tmp() {
  3155. }
  3156. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3157. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3158. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3159. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3160. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3161. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3162. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3163. Matrix.Zero(), Matrix.Zero(),
  3164. Matrix.Zero(), Matrix.Zero(),
  3165. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3166. return Tmp;
  3167. })();
  3168. BABYLON.Tmp = Tmp;
  3169. })(BABYLON || (BABYLON = {}));
  3170. var BABYLON;
  3171. (function (BABYLON) {
  3172. function generateSerializableMember(type, sourceName) {
  3173. return function (target, propertyKey) {
  3174. if (!target.__serializableMembers) {
  3175. target.__serializableMembers = {};
  3176. }
  3177. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3178. };
  3179. }
  3180. function serialize(sourceName) {
  3181. return generateSerializableMember(0, sourceName); // value member
  3182. }
  3183. BABYLON.serialize = serialize;
  3184. function serializeAsTexture(sourceName) {
  3185. return generateSerializableMember(1, sourceName); // texture member
  3186. }
  3187. BABYLON.serializeAsTexture = serializeAsTexture;
  3188. function serializeAsColor3(sourceName) {
  3189. return generateSerializableMember(2, sourceName); // color3 member
  3190. }
  3191. BABYLON.serializeAsColor3 = serializeAsColor3;
  3192. function serializeAsFresnelParameters(sourceName) {
  3193. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3194. }
  3195. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3196. function serializeAsVector2(sourceName) {
  3197. return generateSerializableMember(4, sourceName); // vector2 member
  3198. }
  3199. BABYLON.serializeAsVector2 = serializeAsVector2;
  3200. function serializeAsVector3(sourceName) {
  3201. return generateSerializableMember(5, sourceName); // vector3 member
  3202. }
  3203. BABYLON.serializeAsVector3 = serializeAsVector3;
  3204. function serializeAsMeshReference(sourceName) {
  3205. return generateSerializableMember(6, sourceName); // mesh reference member
  3206. }
  3207. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3208. function serializeAsColorCurves(sourceName) {
  3209. return generateSerializableMember(7, sourceName); // color curves
  3210. }
  3211. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3212. var SerializationHelper = (function () {
  3213. function SerializationHelper() {
  3214. }
  3215. SerializationHelper.Serialize = function (entity, serializationObject) {
  3216. if (!serializationObject) {
  3217. serializationObject = {};
  3218. }
  3219. // Tags
  3220. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3221. // Properties
  3222. for (var property in entity.__serializableMembers) {
  3223. var propertyDescriptor = entity.__serializableMembers[property];
  3224. var targetPropertyName = propertyDescriptor.sourceName || property;
  3225. var propertyType = propertyDescriptor.type;
  3226. var sourceProperty = entity[property];
  3227. if (sourceProperty !== undefined && sourceProperty !== null) {
  3228. switch (propertyType) {
  3229. case 0:
  3230. serializationObject[targetPropertyName] = sourceProperty;
  3231. break;
  3232. case 1:
  3233. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3234. break;
  3235. case 2:
  3236. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3237. break;
  3238. case 3:
  3239. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3240. break;
  3241. case 4:
  3242. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3243. break;
  3244. case 5:
  3245. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3246. break;
  3247. case 6:
  3248. serializationObject[targetPropertyName] = sourceProperty.id;
  3249. break;
  3250. case 7:
  3251. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3252. break;
  3253. }
  3254. }
  3255. }
  3256. return serializationObject;
  3257. };
  3258. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3259. var destination = creationFunction();
  3260. // Tags
  3261. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3262. // Properties
  3263. for (var property in destination.__serializableMembers) {
  3264. var propertyDescriptor = destination.__serializableMembers[property];
  3265. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3266. var propertyType = propertyDescriptor.type;
  3267. if (sourceProperty !== undefined && sourceProperty !== null) {
  3268. switch (propertyType) {
  3269. case 0:
  3270. destination[property] = sourceProperty;
  3271. break;
  3272. case 1:
  3273. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3274. break;
  3275. case 2:
  3276. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3277. break;
  3278. case 3:
  3279. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3280. break;
  3281. case 4:
  3282. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3283. break;
  3284. case 5:
  3285. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3286. break;
  3287. case 6:
  3288. destination[property] = scene.getLastMeshByID(sourceProperty);
  3289. break;
  3290. case 7:
  3291. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3292. break;
  3293. }
  3294. }
  3295. }
  3296. return destination;
  3297. };
  3298. SerializationHelper.Clone = function (creationFunction, source) {
  3299. var destination = creationFunction();
  3300. // Tags
  3301. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3302. // Properties
  3303. for (var property in destination.__serializableMembers) {
  3304. var propertyDescriptor = destination.__serializableMembers[property];
  3305. var sourceProperty = source[property];
  3306. var propertyType = propertyDescriptor.type;
  3307. if (sourceProperty !== undefined && sourceProperty !== null) {
  3308. switch (propertyType) {
  3309. case 0: // Value
  3310. case 6:
  3311. destination[property] = sourceProperty;
  3312. break;
  3313. case 1: // Texture
  3314. case 2: // Color3
  3315. case 3: // FresnelParameters
  3316. case 4: // Vector2
  3317. case 5: // Vector3
  3318. case 7:
  3319. destination[property] = sourceProperty.clone();
  3320. break;
  3321. }
  3322. }
  3323. }
  3324. return destination;
  3325. };
  3326. return SerializationHelper;
  3327. })();
  3328. BABYLON.SerializationHelper = SerializationHelper;
  3329. })(BABYLON || (BABYLON = {}));
  3330. var BABYLON;
  3331. (function (BABYLON) {
  3332. /**
  3333. * A class serves as a medium between the observable and its observers
  3334. */
  3335. var EventState = (function () {
  3336. /**
  3337. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3338. */
  3339. function EventState(mask, skipNextObservers) {
  3340. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3341. this.initalize(mask, skipNextObservers);
  3342. }
  3343. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3344. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3345. this.mask = mask;
  3346. this.skipNextObservers = skipNextObservers;
  3347. return this;
  3348. };
  3349. return EventState;
  3350. })();
  3351. BABYLON.EventState = EventState;
  3352. /**
  3353. * Represent an Observer registered to a given Observable object.
  3354. */
  3355. var Observer = (function () {
  3356. function Observer(callback, mask) {
  3357. this.callback = callback;
  3358. this.mask = mask;
  3359. }
  3360. return Observer;
  3361. })();
  3362. BABYLON.Observer = Observer;
  3363. /**
  3364. * The Observable class is a simple implementation of the Observable pattern.
  3365. * 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.
  3366. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3367. * 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).
  3368. * 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.
  3369. */
  3370. var Observable = (function () {
  3371. function Observable() {
  3372. this._observers = new Array();
  3373. }
  3374. /**
  3375. * Create a new Observer with the specified callback
  3376. * @param callback the callback that will be executed for that Observer
  3377. * @param mask the mask used to filter observers
  3378. * @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.
  3379. */
  3380. Observable.prototype.add = function (callback, mask, insertFirst) {
  3381. if (mask === void 0) { mask = -1; }
  3382. if (insertFirst === void 0) { insertFirst = false; }
  3383. if (!callback) {
  3384. return null;
  3385. }
  3386. var observer = new Observer(callback, mask);
  3387. if (insertFirst) {
  3388. this._observers.unshift(observer);
  3389. }
  3390. else {
  3391. this._observers.push(observer);
  3392. }
  3393. return observer;
  3394. };
  3395. /**
  3396. * Remove an Observer from the Observable object
  3397. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3398. */
  3399. Observable.prototype.remove = function (observer) {
  3400. var index = this._observers.indexOf(observer);
  3401. if (index !== -1) {
  3402. this._observers.splice(index, 1);
  3403. return true;
  3404. }
  3405. return false;
  3406. };
  3407. /**
  3408. * Remove a callback from the Observable object
  3409. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3410. */
  3411. Observable.prototype.removeCallback = function (callback) {
  3412. for (var index = 0; index < this._observers.length; index++) {
  3413. if (this._observers[index].callback === callback) {
  3414. this._observers.splice(index, 1);
  3415. return true;
  3416. }
  3417. }
  3418. return false;
  3419. };
  3420. /**
  3421. * Notify all Observers by calling their respective callback with the given data
  3422. * @param eventData
  3423. * @param mask
  3424. */
  3425. Observable.prototype.notifyObservers = function (eventData, mask) {
  3426. if (mask === void 0) { mask = -1; }
  3427. var state = Observable._pooledEventState ? Observable._pooledEventState.initalize(mask) : new EventState(mask);
  3428. Observable._pooledEventState = null;
  3429. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3430. var obs = _a[_i];
  3431. if (obs.mask & mask) {
  3432. obs.callback(eventData, state);
  3433. }
  3434. if (state.skipNextObservers) {
  3435. break;
  3436. }
  3437. }
  3438. Observable._pooledEventState = state;
  3439. };
  3440. /**
  3441. * return true is the Observable has at least one Observer registered
  3442. */
  3443. Observable.prototype.hasObservers = function () {
  3444. return this._observers.length > 0;
  3445. };
  3446. /**
  3447. * Clear the list of observers
  3448. */
  3449. Observable.prototype.clear = function () {
  3450. this._observers = new Array();
  3451. };
  3452. /**
  3453. * Clone the current observable
  3454. */
  3455. Observable.prototype.clone = function () {
  3456. var result = new Observable();
  3457. result._observers = this._observers.slice(0);
  3458. return result;
  3459. };
  3460. Observable._pooledEventState = null;
  3461. return Observable;
  3462. })();
  3463. BABYLON.Observable = Observable;
  3464. })(BABYLON || (BABYLON = {}));
  3465. var BABYLON;
  3466. (function (BABYLON) {
  3467. var Database = (function () {
  3468. function Database(urlToScene, callbackManifestChecked) {
  3469. // Handling various flavors of prefixed version of IndexedDB
  3470. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3471. this.callbackManifestChecked = callbackManifestChecked;
  3472. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3473. this.db = null;
  3474. this.enableSceneOffline = false;
  3475. this.enableTexturesOffline = false;
  3476. this.manifestVersionFound = 0;
  3477. this.mustUpdateRessources = false;
  3478. this.hasReachedQuota = false;
  3479. if (!Database.IDBStorageEnabled) {
  3480. this.callbackManifestChecked(true);
  3481. }
  3482. else {
  3483. this.checkManifestFile();
  3484. }
  3485. }
  3486. Database.prototype.checkManifestFile = function () {
  3487. var _this = this;
  3488. function noManifestFile() {
  3489. that.enableSceneOffline = false;
  3490. that.enableTexturesOffline = false;
  3491. that.callbackManifestChecked(false);
  3492. }
  3493. var that = this;
  3494. var timeStampUsed = false;
  3495. var manifestURL = this.currentSceneUrl + ".manifest";
  3496. var xhr = new XMLHttpRequest();
  3497. if (navigator.onLine) {
  3498. // Adding a timestamp to by-pass browsers' cache
  3499. timeStampUsed = true;
  3500. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3501. }
  3502. xhr.open("GET", manifestURL, true);
  3503. xhr.addEventListener("load", function () {
  3504. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3505. try {
  3506. var manifestFile = JSON.parse(xhr.response);
  3507. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3508. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3509. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3510. _this.manifestVersionFound = manifestFile.version;
  3511. }
  3512. if (_this.callbackManifestChecked) {
  3513. _this.callbackManifestChecked(true);
  3514. }
  3515. }
  3516. catch (ex) {
  3517. noManifestFile();
  3518. }
  3519. }
  3520. else {
  3521. noManifestFile();
  3522. }
  3523. }, false);
  3524. xhr.addEventListener("error", function (event) {
  3525. if (timeStampUsed) {
  3526. timeStampUsed = false;
  3527. // Let's retry without the timeStamp
  3528. // It could fail when coupled with HTML5 Offline API
  3529. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3530. xhr.open("GET", retryManifestURL, true);
  3531. xhr.send();
  3532. }
  3533. else {
  3534. noManifestFile();
  3535. }
  3536. }, false);
  3537. try {
  3538. xhr.send();
  3539. }
  3540. catch (ex) {
  3541. BABYLON.Tools.Error("Error on XHR send request.");
  3542. that.callbackManifestChecked(false);
  3543. }
  3544. };
  3545. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3546. var _this = this;
  3547. function handleError() {
  3548. that.isSupported = false;
  3549. if (errorCallback)
  3550. errorCallback();
  3551. }
  3552. var that = this;
  3553. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3554. // Your browser doesn't support IndexedDB
  3555. this.isSupported = false;
  3556. if (errorCallback)
  3557. errorCallback();
  3558. }
  3559. else {
  3560. // If the DB hasn't been opened or created yet
  3561. if (!this.db) {
  3562. this.hasReachedQuota = false;
  3563. this.isSupported = true;
  3564. var request = this.idbFactory.open("babylonjs", 1);
  3565. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3566. request.onerror = function (event) {
  3567. handleError();
  3568. };
  3569. // executes when a version change transaction cannot complete due to other active transactions
  3570. request.onblocked = function (event) {
  3571. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3572. handleError();
  3573. };
  3574. // DB has been opened successfully
  3575. request.onsuccess = function (event) {
  3576. _this.db = request.result;
  3577. successCallback();
  3578. };
  3579. // Initialization of the DB. Creating Scenes & Textures stores
  3580. request.onupgradeneeded = function (event) {
  3581. _this.db = (event.target).result;
  3582. try {
  3583. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3584. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3585. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3586. }
  3587. catch (ex) {
  3588. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3589. handleError();
  3590. }
  3591. };
  3592. }
  3593. else {
  3594. if (successCallback)
  3595. successCallback();
  3596. }
  3597. }
  3598. };
  3599. Database.prototype.loadImageFromDB = function (url, image) {
  3600. var _this = this;
  3601. var completeURL = Database.ReturnFullUrlLocation(url);
  3602. var saveAndLoadImage = function () {
  3603. if (!_this.hasReachedQuota && _this.db !== null) {
  3604. // the texture is not yet in the DB, let's try to save it
  3605. _this._saveImageIntoDBAsync(completeURL, image);
  3606. }
  3607. else {
  3608. image.src = url;
  3609. }
  3610. };
  3611. if (!this.mustUpdateRessources) {
  3612. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3613. }
  3614. else {
  3615. saveAndLoadImage();
  3616. }
  3617. };
  3618. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3619. if (this.isSupported && this.db !== null) {
  3620. var texture;
  3621. var transaction = this.db.transaction(["textures"]);
  3622. transaction.onabort = function (event) {
  3623. image.src = url;
  3624. };
  3625. transaction.oncomplete = function (event) {
  3626. var blobTextureURL;
  3627. if (texture) {
  3628. var URL = window.URL || window.webkitURL;
  3629. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3630. image.onerror = function () {
  3631. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3632. image.src = url;
  3633. };
  3634. image.src = blobTextureURL;
  3635. }
  3636. else {
  3637. notInDBCallback();
  3638. }
  3639. };
  3640. var getRequest = transaction.objectStore("textures").get(url);
  3641. getRequest.onsuccess = function (event) {
  3642. texture = (event.target).result;
  3643. };
  3644. getRequest.onerror = function (event) {
  3645. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3646. image.src = url;
  3647. };
  3648. }
  3649. else {
  3650. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3651. image.src = url;
  3652. }
  3653. };
  3654. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3655. var _this = this;
  3656. if (this.isSupported) {
  3657. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3658. var generateBlobUrl = function () {
  3659. var blobTextureURL;
  3660. if (blob) {
  3661. var URL = window.URL || window.webkitURL;
  3662. try {
  3663. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3664. }
  3665. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3666. catch (ex) {
  3667. blobTextureURL = URL.createObjectURL(blob);
  3668. }
  3669. }
  3670. image.src = blobTextureURL;
  3671. };
  3672. if (Database.IsUASupportingBlobStorage) {
  3673. var xhr = new XMLHttpRequest(), blob;
  3674. xhr.open("GET", url, true);
  3675. xhr.responseType = "blob";
  3676. xhr.addEventListener("load", function () {
  3677. if (xhr.status === 200) {
  3678. // Blob as response (XHR2)
  3679. blob = xhr.response;
  3680. var transaction = _this.db.transaction(["textures"], "readwrite");
  3681. // the transaction could abort because of a QuotaExceededError error
  3682. transaction.onabort = function (event) {
  3683. try {
  3684. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3685. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3686. this.hasReachedQuota = true;
  3687. }
  3688. }
  3689. catch (ex) { }
  3690. generateBlobUrl();
  3691. };
  3692. transaction.oncomplete = function (event) {
  3693. generateBlobUrl();
  3694. };
  3695. var newTexture = { textureUrl: url, data: blob };
  3696. try {
  3697. // Put the blob into the dabase
  3698. var addRequest = transaction.objectStore("textures").put(newTexture);
  3699. addRequest.onsuccess = function (event) {
  3700. };
  3701. addRequest.onerror = function (event) {
  3702. generateBlobUrl();
  3703. };
  3704. }
  3705. catch (ex) {
  3706. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3707. if (ex.code === 25) {
  3708. Database.IsUASupportingBlobStorage = false;
  3709. }
  3710. image.src = url;
  3711. }
  3712. }
  3713. else {
  3714. image.src = url;
  3715. }
  3716. }, false);
  3717. xhr.addEventListener("error", function (event) {
  3718. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3719. image.src = url;
  3720. }, false);
  3721. xhr.send();
  3722. }
  3723. else {
  3724. image.src = url;
  3725. }
  3726. }
  3727. else {
  3728. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3729. image.src = url;
  3730. }
  3731. };
  3732. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3733. var _this = this;
  3734. var updateVersion = function (event) {
  3735. // the version is not yet in the DB or we need to update it
  3736. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3737. };
  3738. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3739. };
  3740. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3741. var _this = this;
  3742. if (this.isSupported) {
  3743. var version;
  3744. try {
  3745. var transaction = this.db.transaction(["versions"]);
  3746. transaction.oncomplete = function (event) {
  3747. if (version) {
  3748. // If the version in the JSON file is > than the version in DB
  3749. if (_this.manifestVersionFound > version.data) {
  3750. _this.mustUpdateRessources = true;
  3751. updateInDBCallback();
  3752. }
  3753. else {
  3754. callback(version.data);
  3755. }
  3756. }
  3757. else {
  3758. _this.mustUpdateRessources = true;
  3759. updateInDBCallback();
  3760. }
  3761. };
  3762. transaction.onabort = function (event) {
  3763. callback(-1);
  3764. };
  3765. var getRequest = transaction.objectStore("versions").get(url);
  3766. getRequest.onsuccess = function (event) {
  3767. version = (event.target).result;
  3768. };
  3769. getRequest.onerror = function (event) {
  3770. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3771. callback(-1);
  3772. };
  3773. }
  3774. catch (ex) {
  3775. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3776. callback(-1);
  3777. }
  3778. }
  3779. else {
  3780. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3781. callback(-1);
  3782. }
  3783. };
  3784. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3785. var _this = this;
  3786. if (this.isSupported && !this.hasReachedQuota) {
  3787. try {
  3788. // Open a transaction to the database
  3789. var transaction = this.db.transaction(["versions"], "readwrite");
  3790. // the transaction could abort because of a QuotaExceededError error
  3791. transaction.onabort = function (event) {
  3792. try {
  3793. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3794. _this.hasReachedQuota = true;
  3795. }
  3796. }
  3797. catch (ex) { }
  3798. callback(-1);
  3799. };
  3800. transaction.oncomplete = function (event) {
  3801. callback(_this.manifestVersionFound);
  3802. };
  3803. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3804. // Put the scene into the database
  3805. var addRequest = transaction.objectStore("versions").put(newVersion);
  3806. addRequest.onsuccess = function (event) {
  3807. };
  3808. addRequest.onerror = function (event) {
  3809. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3810. };
  3811. }
  3812. catch (ex) {
  3813. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3814. callback(-1);
  3815. }
  3816. }
  3817. else {
  3818. callback(-1);
  3819. }
  3820. };
  3821. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3822. var _this = this;
  3823. var completeUrl = Database.ReturnFullUrlLocation(url);
  3824. var saveAndLoadFile = function (event) {
  3825. // the scene is not yet in the DB, let's try to save it
  3826. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3827. };
  3828. this._checkVersionFromDB(completeUrl, function (version) {
  3829. if (version !== -1) {
  3830. if (!_this.mustUpdateRessources) {
  3831. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3832. }
  3833. else {
  3834. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3835. }
  3836. }
  3837. else {
  3838. errorCallback();
  3839. }
  3840. });
  3841. };
  3842. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3843. if (this.isSupported) {
  3844. var targetStore;
  3845. if (url.indexOf(".babylon") !== -1) {
  3846. targetStore = "scenes";
  3847. }
  3848. else {
  3849. targetStore = "textures";
  3850. }
  3851. var file;
  3852. var transaction = this.db.transaction([targetStore]);
  3853. transaction.oncomplete = function (event) {
  3854. if (file) {
  3855. callback(file.data);
  3856. }
  3857. else {
  3858. notInDBCallback();
  3859. }
  3860. };
  3861. transaction.onabort = function (event) {
  3862. notInDBCallback();
  3863. };
  3864. var getRequest = transaction.objectStore(targetStore).get(url);
  3865. getRequest.onsuccess = function (event) {
  3866. file = (event.target).result;
  3867. };
  3868. getRequest.onerror = function (event) {
  3869. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3870. notInDBCallback();
  3871. };
  3872. }
  3873. else {
  3874. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3875. callback();
  3876. }
  3877. };
  3878. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3879. var _this = this;
  3880. if (this.isSupported) {
  3881. var targetStore;
  3882. if (url.indexOf(".babylon") !== -1) {
  3883. targetStore = "scenes";
  3884. }
  3885. else {
  3886. targetStore = "textures";
  3887. }
  3888. // Create XHR
  3889. var xhr = new XMLHttpRequest(), fileData;
  3890. xhr.open("GET", url, true);
  3891. if (useArrayBuffer) {
  3892. xhr.responseType = "arraybuffer";
  3893. }
  3894. xhr.onprogress = progressCallback;
  3895. xhr.addEventListener("load", function () {
  3896. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3897. // Blob as response (XHR2)
  3898. //fileData = xhr.responseText;
  3899. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3900. if (!_this.hasReachedQuota) {
  3901. // Open a transaction to the database
  3902. var transaction = _this.db.transaction([targetStore], "readwrite");
  3903. // the transaction could abort because of a QuotaExceededError error
  3904. transaction.onabort = function (event) {
  3905. try {
  3906. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3907. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3908. this.hasReachedQuota = true;
  3909. }
  3910. }
  3911. catch (ex) { }
  3912. callback(fileData);
  3913. };
  3914. transaction.oncomplete = function (event) {
  3915. callback(fileData);
  3916. };
  3917. var newFile;
  3918. if (targetStore === "scenes") {
  3919. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3920. }
  3921. else {
  3922. newFile = { textureUrl: url, data: fileData };
  3923. }
  3924. try {
  3925. // Put the scene into the database
  3926. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3927. addRequest.onsuccess = function (event) {
  3928. };
  3929. addRequest.onerror = function (event) {
  3930. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3931. };
  3932. }
  3933. catch (ex) {
  3934. callback(fileData);
  3935. }
  3936. }
  3937. else {
  3938. callback(fileData);
  3939. }
  3940. }
  3941. else {
  3942. callback();
  3943. }
  3944. }, false);
  3945. xhr.addEventListener("error", function (event) {
  3946. BABYLON.Tools.Error("error on XHR request.");
  3947. callback();
  3948. }, false);
  3949. xhr.send();
  3950. }
  3951. else {
  3952. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3953. callback();
  3954. }
  3955. };
  3956. Database.IsUASupportingBlobStorage = true;
  3957. Database.IDBStorageEnabled = true;
  3958. Database.parseURL = function (url) {
  3959. var a = document.createElement('a');
  3960. a.href = url;
  3961. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3962. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3963. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3964. return absLocation;
  3965. };
  3966. Database.ReturnFullUrlLocation = function (url) {
  3967. if (url.indexOf("http:/") === -1) {
  3968. return (Database.parseURL(window.location.href) + url);
  3969. }
  3970. else {
  3971. return url;
  3972. }
  3973. };
  3974. return Database;
  3975. })();
  3976. BABYLON.Database = Database;
  3977. })(BABYLON || (BABYLON = {}));
  3978. var BABYLON;
  3979. (function (BABYLON) {
  3980. var Internals;
  3981. (function (Internals) {
  3982. /*
  3983. * Based on jsTGALoader - Javascript loader for TGA file
  3984. * By Vincent Thibault
  3985. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3986. */
  3987. var TGATools = (function () {
  3988. function TGATools() {
  3989. }
  3990. TGATools.GetTGAHeader = function (data) {
  3991. var offset = 0;
  3992. var header = {
  3993. id_length: data[offset++],
  3994. colormap_type: data[offset++],
  3995. image_type: data[offset++],
  3996. colormap_index: data[offset++] | data[offset++] << 8,
  3997. colormap_length: data[offset++] | data[offset++] << 8,
  3998. colormap_size: data[offset++],
  3999. origin: [
  4000. data[offset++] | data[offset++] << 8,
  4001. data[offset++] | data[offset++] << 8
  4002. ],
  4003. width: data[offset++] | data[offset++] << 8,
  4004. height: data[offset++] | data[offset++] << 8,
  4005. pixel_size: data[offset++],
  4006. flags: data[offset++]
  4007. };
  4008. return header;
  4009. };
  4010. TGATools.UploadContent = function (gl, data) {
  4011. // Not enough data to contain header ?
  4012. if (data.length < 19) {
  4013. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4014. return;
  4015. }
  4016. // Read Header
  4017. var offset = 18;
  4018. var header = TGATools.GetTGAHeader(data);
  4019. // Assume it's a valid Targa file.
  4020. if (header.id_length + offset > data.length) {
  4021. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4022. return;
  4023. }
  4024. // Skip not needed data
  4025. offset += header.id_length;
  4026. var use_rle = false;
  4027. var use_pal = false;
  4028. var use_rgb = false;
  4029. var use_grey = false;
  4030. // Get some informations.
  4031. switch (header.image_type) {
  4032. case TGATools._TYPE_RLE_INDEXED:
  4033. use_rle = true;
  4034. case TGATools._TYPE_INDEXED:
  4035. use_pal = true;
  4036. break;
  4037. case TGATools._TYPE_RLE_RGB:
  4038. use_rle = true;
  4039. case TGATools._TYPE_RGB:
  4040. use_rgb = true;
  4041. break;
  4042. case TGATools._TYPE_RLE_GREY:
  4043. use_rle = true;
  4044. case TGATools._TYPE_GREY:
  4045. use_grey = true;
  4046. break;
  4047. }
  4048. var pixel_data;
  4049. var numAlphaBits = header.flags & 0xf;
  4050. var pixel_size = header.pixel_size >> 3;
  4051. var pixel_total = header.width * header.height * pixel_size;
  4052. // Read palettes
  4053. var palettes;
  4054. if (use_pal) {
  4055. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4056. }
  4057. // Read LRE
  4058. if (use_rle) {
  4059. pixel_data = new Uint8Array(pixel_total);
  4060. var c, count, i;
  4061. var localOffset = 0;
  4062. var pixels = new Uint8Array(pixel_size);
  4063. while (offset < pixel_total && localOffset < pixel_total) {
  4064. c = data[offset++];
  4065. count = (c & 0x7f) + 1;
  4066. // RLE pixels
  4067. if (c & 0x80) {
  4068. // Bind pixel tmp array
  4069. for (i = 0; i < pixel_size; ++i) {
  4070. pixels[i] = data[offset++];
  4071. }
  4072. // Copy pixel array
  4073. for (i = 0; i < count; ++i) {
  4074. pixel_data.set(pixels, localOffset + i * pixel_size);
  4075. }
  4076. localOffset += pixel_size * count;
  4077. }
  4078. else {
  4079. count *= pixel_size;
  4080. for (i = 0; i < count; ++i) {
  4081. pixel_data[localOffset + i] = data[offset++];
  4082. }
  4083. localOffset += count;
  4084. }
  4085. }
  4086. }
  4087. else {
  4088. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4089. }
  4090. // Load to texture
  4091. var x_start, y_start, x_step, y_step, y_end, x_end;
  4092. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4093. default:
  4094. case TGATools._ORIGIN_UL:
  4095. x_start = 0;
  4096. x_step = 1;
  4097. x_end = header.width;
  4098. y_start = 0;
  4099. y_step = 1;
  4100. y_end = header.height;
  4101. break;
  4102. case TGATools._ORIGIN_BL:
  4103. x_start = 0;
  4104. x_step = 1;
  4105. x_end = header.width;
  4106. y_start = header.height - 1;
  4107. y_step = -1;
  4108. y_end = -1;
  4109. break;
  4110. case TGATools._ORIGIN_UR:
  4111. x_start = header.width - 1;
  4112. x_step = -1;
  4113. x_end = -1;
  4114. y_start = 0;
  4115. y_step = 1;
  4116. y_end = header.height;
  4117. break;
  4118. case TGATools._ORIGIN_BR:
  4119. x_start = header.width - 1;
  4120. x_step = -1;
  4121. x_end = -1;
  4122. y_start = header.height - 1;
  4123. y_step = -1;
  4124. y_end = -1;
  4125. break;
  4126. }
  4127. // Load the specify method
  4128. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4129. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4130. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4131. };
  4132. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4133. var image = pixel_data, colormap = palettes;
  4134. var width = header.width, height = header.height;
  4135. var color, i = 0, x, y;
  4136. var imageData = new Uint8Array(width * height * 4);
  4137. for (y = y_start; y !== y_end; y += y_step) {
  4138. for (x = x_start; x !== x_end; x += x_step, i++) {
  4139. color = image[i];
  4140. imageData[(x + width * y) * 4 + 3] = 255;
  4141. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4142. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4143. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4144. }
  4145. }
  4146. return imageData;
  4147. };
  4148. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4149. var image = pixel_data;
  4150. var width = header.width, height = header.height;
  4151. var color, i = 0, x, y;
  4152. var imageData = new Uint8Array(width * height * 4);
  4153. for (y = y_start; y !== y_end; y += y_step) {
  4154. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4155. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4156. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4157. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4158. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4159. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4160. }
  4161. }
  4162. return imageData;
  4163. };
  4164. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4165. var image = pixel_data;
  4166. var width = header.width, height = header.height;
  4167. var i = 0, x, y;
  4168. var imageData = new Uint8Array(width * height * 4);
  4169. for (y = y_start; y !== y_end; y += y_step) {
  4170. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4171. imageData[(x + width * y) * 4 + 3] = 255;
  4172. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4173. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4174. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4175. }
  4176. }
  4177. return imageData;
  4178. };
  4179. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4180. var image = pixel_data;
  4181. var width = header.width, height = header.height;
  4182. var i = 0, x, y;
  4183. var imageData = new Uint8Array(width * height * 4);
  4184. for (y = y_start; y !== y_end; y += y_step) {
  4185. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4186. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4187. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4188. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4189. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4190. }
  4191. }
  4192. return imageData;
  4193. };
  4194. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4195. var image = pixel_data;
  4196. var width = header.width, height = header.height;
  4197. var color, i = 0, x, y;
  4198. var imageData = new Uint8Array(width * height * 4);
  4199. for (y = y_start; y !== y_end; y += y_step) {
  4200. for (x = x_start; x !== x_end; x += x_step, i++) {
  4201. color = image[i];
  4202. imageData[(x + width * y) * 4 + 0] = color;
  4203. imageData[(x + width * y) * 4 + 1] = color;
  4204. imageData[(x + width * y) * 4 + 2] = color;
  4205. imageData[(x + width * y) * 4 + 3] = 255;
  4206. }
  4207. }
  4208. return imageData;
  4209. };
  4210. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4211. var image = pixel_data;
  4212. var width = header.width, height = header.height;
  4213. var i = 0, x, y;
  4214. var imageData = new Uint8Array(width * height * 4);
  4215. for (y = y_start; y !== y_end; y += y_step) {
  4216. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4217. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4218. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4219. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4220. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4221. }
  4222. }
  4223. return imageData;
  4224. };
  4225. TGATools._TYPE_NO_DATA = 0;
  4226. TGATools._TYPE_INDEXED = 1;
  4227. TGATools._TYPE_RGB = 2;
  4228. TGATools._TYPE_GREY = 3;
  4229. TGATools._TYPE_RLE_INDEXED = 9;
  4230. TGATools._TYPE_RLE_RGB = 10;
  4231. TGATools._TYPE_RLE_GREY = 11;
  4232. TGATools._ORIGIN_MASK = 0x30;
  4233. TGATools._ORIGIN_SHIFT = 0x04;
  4234. TGATools._ORIGIN_BL = 0x00;
  4235. TGATools._ORIGIN_BR = 0x01;
  4236. TGATools._ORIGIN_UL = 0x02;
  4237. TGATools._ORIGIN_UR = 0x03;
  4238. return TGATools;
  4239. })();
  4240. Internals.TGATools = TGATools;
  4241. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4242. })(BABYLON || (BABYLON = {}));
  4243. var BABYLON;
  4244. (function (BABYLON) {
  4245. var SmartArray = (function () {
  4246. function SmartArray(capacity) {
  4247. this.length = 0;
  4248. this._duplicateId = 0;
  4249. this.data = new Array(capacity);
  4250. this._id = SmartArray._GlobalId++;
  4251. }
  4252. SmartArray.prototype.push = function (value) {
  4253. this.data[this.length++] = value;
  4254. if (this.length > this.data.length) {
  4255. this.data.length *= 2;
  4256. }
  4257. if (!value.__smartArrayFlags) {
  4258. value.__smartArrayFlags = {};
  4259. }
  4260. value.__smartArrayFlags[this._id] = this._duplicateId;
  4261. };
  4262. SmartArray.prototype.pushNoDuplicate = function (value) {
  4263. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4264. return false;
  4265. }
  4266. this.push(value);
  4267. return true;
  4268. };
  4269. SmartArray.prototype.sort = function (compareFn) {
  4270. this.data.sort(compareFn);
  4271. };
  4272. SmartArray.prototype.reset = function () {
  4273. this.length = 0;
  4274. this._duplicateId++;
  4275. };
  4276. SmartArray.prototype.concat = function (array) {
  4277. if (array.length === 0) {
  4278. return;
  4279. }
  4280. if (this.length + array.length > this.data.length) {
  4281. this.data.length = (this.length + array.length) * 2;
  4282. }
  4283. for (var index = 0; index < array.length; index++) {
  4284. this.data[this.length++] = (array.data || array)[index];
  4285. }
  4286. };
  4287. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4288. if (array.length === 0) {
  4289. return;
  4290. }
  4291. if (this.length + array.length > this.data.length) {
  4292. this.data.length = (this.length + array.length) * 2;
  4293. }
  4294. for (var index = 0; index < array.length; index++) {
  4295. var item = (array.data || array)[index];
  4296. this.pushNoDuplicate(item);
  4297. }
  4298. };
  4299. SmartArray.prototype.indexOf = function (value) {
  4300. var position = this.data.indexOf(value);
  4301. if (position >= this.length) {
  4302. return -1;
  4303. }
  4304. return position;
  4305. };
  4306. // Statics
  4307. SmartArray._GlobalId = 0;
  4308. return SmartArray;
  4309. })();
  4310. BABYLON.SmartArray = SmartArray;
  4311. })(BABYLON || (BABYLON = {}));
  4312. var BABYLON;
  4313. (function (BABYLON) {
  4314. /**
  4315. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4316. * The underlying implementation relies on an associative array to ensure the best performances.
  4317. * The value can be anything including 'null' but except 'undefined'
  4318. */
  4319. var StringDictionary = (function () {
  4320. function StringDictionary() {
  4321. this._count = 0;
  4322. this._data = {};
  4323. }
  4324. /**
  4325. * Get a value based from its key
  4326. * @param key the given key to get the matching value from
  4327. * @return the value if found, otherwise undefined is returned
  4328. */
  4329. StringDictionary.prototype.get = function (key) {
  4330. var val = this._data[key];
  4331. if (val !== undefined) {
  4332. return val;
  4333. }
  4334. return undefined;
  4335. };
  4336. /**
  4337. * Get a value from its key or add it if it doesn't exist.
  4338. * This method will ensure you that a given key/data will be present in the dictionary.
  4339. * @param key the given key to get the matching value from
  4340. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4341. * The factory will only be invoked if there's no data for the given key.
  4342. * @return the value corresponding to the key.
  4343. */
  4344. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4345. var val = this.get(key);
  4346. if (val !== undefined) {
  4347. return val;
  4348. }
  4349. val = factory(key);
  4350. if (val) {
  4351. this.add(key, val);
  4352. }
  4353. return val;
  4354. };
  4355. /**
  4356. * Get a value from its key if present in the dictionary otherwise add it
  4357. * @param key the key to get the value from
  4358. * @param val if there's no such key/value pair in the dictionary add it with this value
  4359. * @return the value corresponding to the key
  4360. */
  4361. StringDictionary.prototype.getOrAdd = function (key, val) {
  4362. var curVal = this.get(key);
  4363. if (curVal !== undefined) {
  4364. return curVal;
  4365. }
  4366. this.add(key, val);
  4367. return val;
  4368. };
  4369. /**
  4370. * Check if there's a given key in the dictionary
  4371. * @param key the key to check for
  4372. * @return true if the key is present, false otherwise
  4373. */
  4374. StringDictionary.prototype.contains = function (key) {
  4375. return this._data[key] !== undefined;
  4376. };
  4377. /**
  4378. * Add a new key and its corresponding value
  4379. * @param key the key to add
  4380. * @param value the value corresponding to the key
  4381. * @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
  4382. */
  4383. StringDictionary.prototype.add = function (key, value) {
  4384. if (this._data[key] !== undefined) {
  4385. return false;
  4386. }
  4387. this._data[key] = value;
  4388. ++this._count;
  4389. return true;
  4390. };
  4391. StringDictionary.prototype.set = function (key, value) {
  4392. if (this._data[key] === undefined) {
  4393. return false;
  4394. }
  4395. this._data[key] = value;
  4396. return true;
  4397. };
  4398. /**
  4399. * Remove a key/value from the dictionary.
  4400. * @param key the key to remove
  4401. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4402. */
  4403. StringDictionary.prototype.remove = function (key) {
  4404. if (this.contains(key)) {
  4405. delete this._data[key];
  4406. --this._count;
  4407. return true;
  4408. }
  4409. return false;
  4410. };
  4411. /**
  4412. * Clear the whole content of the dictionary
  4413. */
  4414. StringDictionary.prototype.clear = function () {
  4415. this._data = {};
  4416. this._count = 0;
  4417. };
  4418. Object.defineProperty(StringDictionary.prototype, "count", {
  4419. get: function () {
  4420. return this._count;
  4421. },
  4422. enumerable: true,
  4423. configurable: true
  4424. });
  4425. /**
  4426. * Execute a callback on each key/val of the dictionary.
  4427. * Note that you can remove any element in this dictionary in the callback implementation
  4428. * @param callback the callback to execute on a given key/value pair
  4429. */
  4430. StringDictionary.prototype.forEach = function (callback) {
  4431. for (var cur in this._data) {
  4432. var val = this._data[cur];
  4433. callback(cur, val);
  4434. }
  4435. };
  4436. /**
  4437. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4438. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4439. * Note that you can remove any element in this dictionary in the callback implementation
  4440. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4441. */
  4442. StringDictionary.prototype.first = function (callback) {
  4443. for (var cur in this._data) {
  4444. var val = this._data[cur];
  4445. var res = callback(cur, val);
  4446. if (res) {
  4447. return res;
  4448. }
  4449. }
  4450. return null;
  4451. };
  4452. return StringDictionary;
  4453. })();
  4454. BABYLON.StringDictionary = StringDictionary;
  4455. })(BABYLON || (BABYLON = {}));
  4456. var BABYLON;
  4457. (function (BABYLON) {
  4458. // Screenshots
  4459. var screenshotCanvas;
  4460. var cloneValue = function (source, destinationObject) {
  4461. if (!source)
  4462. return null;
  4463. if (source instanceof BABYLON.Mesh) {
  4464. return null;
  4465. }
  4466. if (source instanceof BABYLON.SubMesh) {
  4467. return source.clone(destinationObject);
  4468. }
  4469. else if (source.clone) {
  4470. return source.clone();
  4471. }
  4472. return null;
  4473. };
  4474. var Tools = (function () {
  4475. function Tools() {
  4476. }
  4477. Tools.Instantiate = function (className) {
  4478. var arr = className.split(".");
  4479. var fn = (window || this);
  4480. for (var i = 0, len = arr.length; i < len; i++) {
  4481. fn = fn[arr[i]];
  4482. }
  4483. if (typeof fn !== "function") {
  4484. return null;
  4485. }
  4486. return fn;
  4487. };
  4488. Tools.SetImmediate = function (action) {
  4489. if (window.setImmediate) {
  4490. window.setImmediate(action);
  4491. }
  4492. else {
  4493. setTimeout(action, 1);
  4494. }
  4495. };
  4496. Tools.IsExponentOfTwo = function (value) {
  4497. var count = 1;
  4498. do {
  4499. count *= 2;
  4500. } while (count < value);
  4501. return count === value;
  4502. };
  4503. Tools.GetExponentOfTwo = function (value, max) {
  4504. var count = 1;
  4505. do {
  4506. count *= 2;
  4507. } while (count < value);
  4508. if (count > max)
  4509. count = max;
  4510. return count;
  4511. };
  4512. Tools.GetFilename = function (path) {
  4513. var index = path.lastIndexOf("/");
  4514. if (index < 0)
  4515. return path;
  4516. return path.substring(index + 1);
  4517. };
  4518. Tools.GetDOMTextContent = function (element) {
  4519. var result = "";
  4520. var child = element.firstChild;
  4521. while (child) {
  4522. if (child.nodeType === 3) {
  4523. result += child.textContent;
  4524. }
  4525. child = child.nextSibling;
  4526. }
  4527. return result;
  4528. };
  4529. Tools.ToDegrees = function (angle) {
  4530. return angle * 180 / Math.PI;
  4531. };
  4532. Tools.ToRadians = function (angle) {
  4533. return angle * Math.PI / 180;
  4534. };
  4535. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4536. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4537. var output = "";
  4538. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4539. var i = 0;
  4540. var bytes = new Uint8Array(buffer);
  4541. while (i < bytes.length) {
  4542. chr1 = bytes[i++];
  4543. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4544. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4545. enc1 = chr1 >> 2;
  4546. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4547. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4548. enc4 = chr3 & 63;
  4549. if (isNaN(chr2)) {
  4550. enc3 = enc4 = 64;
  4551. }
  4552. else if (isNaN(chr3)) {
  4553. enc4 = 64;
  4554. }
  4555. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4556. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4557. }
  4558. return "data:image/png;base64," + output;
  4559. };
  4560. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4561. if (bias === void 0) { bias = null; }
  4562. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4563. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4564. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4565. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4566. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4567. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4568. }
  4569. if (bias) {
  4570. minimum.x -= minimum.x * bias.x + bias.y;
  4571. minimum.y -= minimum.y * bias.x + bias.y;
  4572. minimum.z -= minimum.z * bias.x + bias.y;
  4573. maximum.x += maximum.x * bias.x + bias.y;
  4574. maximum.y += maximum.y * bias.x + bias.y;
  4575. maximum.z += maximum.z * bias.x + bias.y;
  4576. }
  4577. return {
  4578. minimum: minimum,
  4579. maximum: maximum
  4580. };
  4581. };
  4582. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4583. if (bias === void 0) { bias = null; }
  4584. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4585. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4586. if (!stride) {
  4587. stride = 3;
  4588. }
  4589. for (var index = start; index < start + count; index++) {
  4590. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4591. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4592. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4593. }
  4594. if (bias) {
  4595. minimum.x -= minimum.x * bias.x + bias.y;
  4596. minimum.y -= minimum.y * bias.x + bias.y;
  4597. minimum.z -= minimum.z * bias.x + bias.y;
  4598. maximum.x += maximum.x * bias.x + bias.y;
  4599. maximum.y += maximum.y * bias.x + bias.y;
  4600. maximum.z += maximum.z * bias.x + bias.y;
  4601. }
  4602. return {
  4603. minimum: minimum,
  4604. maximum: maximum
  4605. };
  4606. };
  4607. Tools.Vector2ArrayFeeder = function (array) {
  4608. return function (index) {
  4609. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4610. var length = isFloatArray ? array.length / 2 : array.length;
  4611. if (index >= length) {
  4612. return null;
  4613. }
  4614. if (isFloatArray) {
  4615. var fa = array;
  4616. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4617. }
  4618. var a = array;
  4619. return a[index];
  4620. };
  4621. };
  4622. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4623. if (bias === void 0) { bias = null; }
  4624. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4625. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4626. var i = 0;
  4627. var cur = feeder(i++);
  4628. while (cur) {
  4629. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4630. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4631. cur = feeder(i++);
  4632. }
  4633. if (bias) {
  4634. minimum.x -= minimum.x * bias.x + bias.y;
  4635. minimum.y -= minimum.y * bias.x + bias.y;
  4636. maximum.x += maximum.x * bias.x + bias.y;
  4637. maximum.y += maximum.y * bias.x + bias.y;
  4638. }
  4639. return {
  4640. minimum: minimum,
  4641. maximum: maximum
  4642. };
  4643. };
  4644. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4645. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4646. return undefined;
  4647. return Array.isArray(obj) ? obj : [obj];
  4648. };
  4649. // Misc.
  4650. Tools.GetPointerPrefix = function () {
  4651. var eventPrefix = "pointer";
  4652. // Check if pointer events are supported
  4653. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4654. eventPrefix = "mouse";
  4655. }
  4656. return eventPrefix;
  4657. };
  4658. Tools.QueueNewFrame = function (func) {
  4659. if (window.requestAnimationFrame)
  4660. window.requestAnimationFrame(func);
  4661. else if (window.msRequestAnimationFrame)
  4662. window.msRequestAnimationFrame(func);
  4663. else if (window.webkitRequestAnimationFrame)
  4664. window.webkitRequestAnimationFrame(func);
  4665. else if (window.mozRequestAnimationFrame)
  4666. window.mozRequestAnimationFrame(func);
  4667. else if (window.oRequestAnimationFrame)
  4668. window.oRequestAnimationFrame(func);
  4669. else {
  4670. window.setTimeout(func, 16);
  4671. }
  4672. };
  4673. Tools.RequestFullscreen = function (element, options) {
  4674. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4675. if (!requestFunction)
  4676. return;
  4677. requestFunction.call(element, options);
  4678. };
  4679. Tools.ExitFullscreen = function () {
  4680. if (document.exitFullscreen) {
  4681. document.exitFullscreen();
  4682. }
  4683. else if (document.mozCancelFullScreen) {
  4684. document.mozCancelFullScreen();
  4685. }
  4686. else if (document.webkitCancelFullScreen) {
  4687. document.webkitCancelFullScreen();
  4688. }
  4689. else if (document.msCancelFullScreen) {
  4690. document.msCancelFullScreen();
  4691. }
  4692. };
  4693. Tools.SetCorsBehavior = function (url, img) {
  4694. if (Tools.CorsBehavior) {
  4695. switch (typeof (Tools.CorsBehavior)) {
  4696. case "function":
  4697. var result = Tools.CorsBehavior(url);
  4698. if (result) {
  4699. return result;
  4700. }
  4701. break;
  4702. case "string":
  4703. default:
  4704. img.crossOrigin = Tools.CorsBehavior;
  4705. break;
  4706. }
  4707. }
  4708. };
  4709. // External files
  4710. Tools.CleanUrl = function (url) {
  4711. url = url.replace(/#/mg, "%23");
  4712. return url;
  4713. };
  4714. Tools.LoadImage = function (url, onload, onerror, database) {
  4715. if (url instanceof ArrayBuffer) {
  4716. url = Tools.EncodeArrayBufferTobase64(url);
  4717. }
  4718. url = Tools.CleanUrl(url);
  4719. var img = new Image();
  4720. if (url.substr(0, 5) !== "data:") {
  4721. Tools.SetCorsBehavior(url, img);
  4722. }
  4723. img.onload = function () {
  4724. onload(img);
  4725. };
  4726. img.onerror = function (err) {
  4727. Tools.Error("Error while trying to load texture: " + url);
  4728. if (Tools.UseFallbackTexture) {
  4729. 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";
  4730. onload(img);
  4731. }
  4732. else {
  4733. onerror();
  4734. }
  4735. };
  4736. var noIndexedDB = function () {
  4737. img.src = url;
  4738. };
  4739. var loadFromIndexedDB = function () {
  4740. database.loadImageFromDB(url, img);
  4741. };
  4742. //ANY database to do!
  4743. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4744. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4745. }
  4746. else {
  4747. if (url.indexOf("file:") === -1) {
  4748. noIndexedDB();
  4749. }
  4750. else {
  4751. try {
  4752. var textureName = url.substring(5).toLowerCase();
  4753. var blobURL;
  4754. try {
  4755. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4756. }
  4757. catch (ex) {
  4758. // Chrome doesn't support oneTimeOnly parameter
  4759. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4760. }
  4761. img.src = blobURL;
  4762. }
  4763. catch (e) {
  4764. img.src = null;
  4765. }
  4766. }
  4767. }
  4768. return img;
  4769. };
  4770. //ANY
  4771. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4772. url = Tools.CleanUrl(url);
  4773. var noIndexedDB = function () {
  4774. var request = new XMLHttpRequest();
  4775. var loadUrl = Tools.BaseUrl + url;
  4776. request.open('GET', loadUrl, true);
  4777. if (useArrayBuffer) {
  4778. request.responseType = "arraybuffer";
  4779. }
  4780. request.onprogress = progressCallBack;
  4781. request.onreadystatechange = function () {
  4782. if (request.readyState === 4) {
  4783. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  4784. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  4785. callback(!useArrayBuffer ? request.responseText : request.response);
  4786. }
  4787. else {
  4788. if (onError) {
  4789. onError();
  4790. }
  4791. else {
  4792. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4793. }
  4794. }
  4795. }
  4796. };
  4797. request.send(null);
  4798. };
  4799. var loadFromIndexedDB = function () {
  4800. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4801. };
  4802. if (url.indexOf("file:") !== -1) {
  4803. var fileName = url.substring(5).toLowerCase();
  4804. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4805. }
  4806. else {
  4807. // Caching all files
  4808. if (database && database.enableSceneOffline) {
  4809. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4810. }
  4811. else {
  4812. noIndexedDB();
  4813. }
  4814. }
  4815. };
  4816. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4817. var reader = new FileReader();
  4818. reader.onload = function (e) {
  4819. //target doesn't have result from ts 1.3
  4820. callback(e.target['result']);
  4821. };
  4822. reader.onprogress = progressCallback;
  4823. reader.readAsDataURL(fileToLoad);
  4824. };
  4825. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4826. var reader = new FileReader();
  4827. reader.onerror = function (e) {
  4828. Tools.Log("Error while reading file: " + fileToLoad.name);
  4829. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4830. };
  4831. reader.onload = function (e) {
  4832. //target doesn't have result from ts 1.3
  4833. callback(e.target['result']);
  4834. };
  4835. reader.onprogress = progressCallBack;
  4836. if (!useArrayBuffer) {
  4837. // Asynchronous read
  4838. reader.readAsText(fileToLoad);
  4839. }
  4840. else {
  4841. reader.readAsArrayBuffer(fileToLoad);
  4842. }
  4843. };
  4844. //returns a downloadable url to a file content.
  4845. Tools.FileAsURL = function (content) {
  4846. var fileBlob = new Blob([content]);
  4847. var url = window.URL || window.webkitURL;
  4848. var link = url.createObjectURL(fileBlob);
  4849. return link;
  4850. };
  4851. // Misc.
  4852. Tools.Format = function (value, decimals) {
  4853. if (decimals === void 0) { decimals = 2; }
  4854. return value.toFixed(decimals);
  4855. };
  4856. Tools.CheckExtends = function (v, min, max) {
  4857. if (v.x < min.x)
  4858. min.x = v.x;
  4859. if (v.y < min.y)
  4860. min.y = v.y;
  4861. if (v.z < min.z)
  4862. min.z = v.z;
  4863. if (v.x > max.x)
  4864. max.x = v.x;
  4865. if (v.y > max.y)
  4866. max.y = v.y;
  4867. if (v.z > max.z)
  4868. max.z = v.z;
  4869. };
  4870. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4871. for (var prop in source) {
  4872. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4873. continue;
  4874. }
  4875. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4876. continue;
  4877. }
  4878. var sourceValue = source[prop];
  4879. var typeOfSourceValue = typeof sourceValue;
  4880. if (typeOfSourceValue === "function") {
  4881. continue;
  4882. }
  4883. if (typeOfSourceValue === "object") {
  4884. if (sourceValue instanceof Array) {
  4885. destination[prop] = [];
  4886. if (sourceValue.length > 0) {
  4887. if (typeof sourceValue[0] == "object") {
  4888. for (var index = 0; index < sourceValue.length; index++) {
  4889. var clonedValue = cloneValue(sourceValue[index], destination);
  4890. if (destination[prop].indexOf(clonedValue) === -1) {
  4891. destination[prop].push(clonedValue);
  4892. }
  4893. }
  4894. }
  4895. else {
  4896. destination[prop] = sourceValue.slice(0);
  4897. }
  4898. }
  4899. }
  4900. else {
  4901. destination[prop] = cloneValue(sourceValue, destination);
  4902. }
  4903. }
  4904. else {
  4905. destination[prop] = sourceValue;
  4906. }
  4907. }
  4908. };
  4909. Tools.IsEmpty = function (obj) {
  4910. for (var i in obj) {
  4911. return false;
  4912. }
  4913. return true;
  4914. };
  4915. Tools.RegisterTopRootEvents = function (events) {
  4916. for (var index = 0; index < events.length; index++) {
  4917. var event = events[index];
  4918. window.addEventListener(event.name, event.handler, false);
  4919. try {
  4920. if (window.parent) {
  4921. window.parent.addEventListener(event.name, event.handler, false);
  4922. }
  4923. }
  4924. catch (e) {
  4925. }
  4926. }
  4927. };
  4928. Tools.UnregisterTopRootEvents = function (events) {
  4929. for (var index = 0; index < events.length; index++) {
  4930. var event = events[index];
  4931. window.removeEventListener(event.name, event.handler);
  4932. try {
  4933. if (window.parent) {
  4934. window.parent.removeEventListener(event.name, event.handler);
  4935. }
  4936. }
  4937. catch (e) {
  4938. }
  4939. }
  4940. };
  4941. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  4942. if (mimeType === void 0) { mimeType = "image/png"; }
  4943. // Read the contents of the framebuffer
  4944. var numberOfChannelsByLine = width * 4;
  4945. var halfHeight = height / 2;
  4946. //Reading datas from WebGL
  4947. var data = engine.readPixels(0, 0, width, height);
  4948. //To flip image on Y axis.
  4949. for (var i = 0; i < halfHeight; i++) {
  4950. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4951. var currentCell = j + i * numberOfChannelsByLine;
  4952. var targetLine = height - i - 1;
  4953. var targetCell = j + targetLine * numberOfChannelsByLine;
  4954. var temp = data[currentCell];
  4955. data[currentCell] = data[targetCell];
  4956. data[targetCell] = temp;
  4957. }
  4958. }
  4959. // Create a 2D canvas to store the result
  4960. if (!screenshotCanvas) {
  4961. screenshotCanvas = document.createElement('canvas');
  4962. }
  4963. screenshotCanvas.width = width;
  4964. screenshotCanvas.height = height;
  4965. var context = screenshotCanvas.getContext('2d');
  4966. // Copy the pixels to a 2D canvas
  4967. var imageData = context.createImageData(width, height);
  4968. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4969. var castData = imageData.data;
  4970. castData.set(data);
  4971. context.putImageData(imageData, 0, 0);
  4972. var base64Image = screenshotCanvas.toDataURL(mimeType);
  4973. if (successCallback) {
  4974. successCallback(base64Image);
  4975. }
  4976. else {
  4977. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4978. if (("download" in document.createElement("a"))) {
  4979. var a = window.document.createElement("a");
  4980. a.href = base64Image;
  4981. var date = new Date();
  4982. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4983. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4984. window.document.body.appendChild(a);
  4985. a.addEventListener("click", function () {
  4986. a.parentElement.removeChild(a);
  4987. });
  4988. a.click();
  4989. }
  4990. else {
  4991. var newWindow = window.open("");
  4992. var img = newWindow.document.createElement("img");
  4993. img.src = base64Image;
  4994. newWindow.document.body.appendChild(img);
  4995. }
  4996. }
  4997. };
  4998. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  4999. if (mimeType === void 0) { mimeType = "image/png"; }
  5000. var width;
  5001. var height;
  5002. //If a precision value is specified
  5003. if (size.precision) {
  5004. width = Math.round(engine.getRenderWidth() * size.precision);
  5005. height = Math.round(width / engine.getAspectRatio(camera));
  5006. size = { width: width, height: height };
  5007. }
  5008. else if (size.width && size.height) {
  5009. width = size.width;
  5010. height = size.height;
  5011. }
  5012. else if (size.width && !size.height) {
  5013. width = size.width;
  5014. height = Math.round(width / engine.getAspectRatio(camera));
  5015. size = { width: width, height: height };
  5016. }
  5017. else if (size.height && !size.width) {
  5018. height = size.height;
  5019. width = Math.round(height * engine.getAspectRatio(camera));
  5020. size = { width: width, height: height };
  5021. }
  5022. else if (!isNaN(size)) {
  5023. height = size;
  5024. width = size;
  5025. }
  5026. else {
  5027. Tools.Error("Invalid 'size' parameter !");
  5028. return;
  5029. }
  5030. var scene = camera.getScene();
  5031. var previousCamera = null;
  5032. if (scene.activeCamera !== camera) {
  5033. previousCamera = scene.activeCamera;
  5034. scene.activeCamera = camera;
  5035. }
  5036. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5037. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  5038. texture.renderList = scene.meshes;
  5039. texture.onAfterRenderObservable.add(function () {
  5040. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5041. });
  5042. scene.incrementRenderId();
  5043. scene.resetCachedMaterial();
  5044. texture.render(true);
  5045. texture.dispose();
  5046. if (previousCamera) {
  5047. scene.activeCamera = previousCamera;
  5048. }
  5049. camera.getProjectionMatrix(true); // Force cache refresh;
  5050. };
  5051. // XHR response validator for local file scenario
  5052. Tools.ValidateXHRData = function (xhr, dataType) {
  5053. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5054. if (dataType === void 0) { dataType = 7; }
  5055. try {
  5056. if (dataType & 1) {
  5057. if (xhr.responseText && xhr.responseText.length > 0) {
  5058. return true;
  5059. }
  5060. else if (dataType === 1) {
  5061. return false;
  5062. }
  5063. }
  5064. if (dataType & 2) {
  5065. // Check header width and height since there is no "TGA" magic number
  5066. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5067. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5068. return true;
  5069. }
  5070. else if (dataType === 2) {
  5071. return false;
  5072. }
  5073. }
  5074. if (dataType & 4) {
  5075. // Check for the "DDS" magic number
  5076. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5077. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5078. return true;
  5079. }
  5080. else {
  5081. return false;
  5082. }
  5083. }
  5084. }
  5085. catch (e) {
  5086. }
  5087. return false;
  5088. };
  5089. Object.defineProperty(Tools, "NoneLogLevel", {
  5090. get: function () {
  5091. return Tools._NoneLogLevel;
  5092. },
  5093. enumerable: true,
  5094. configurable: true
  5095. });
  5096. Object.defineProperty(Tools, "MessageLogLevel", {
  5097. get: function () {
  5098. return Tools._MessageLogLevel;
  5099. },
  5100. enumerable: true,
  5101. configurable: true
  5102. });
  5103. Object.defineProperty(Tools, "WarningLogLevel", {
  5104. get: function () {
  5105. return Tools._WarningLogLevel;
  5106. },
  5107. enumerable: true,
  5108. configurable: true
  5109. });
  5110. Object.defineProperty(Tools, "ErrorLogLevel", {
  5111. get: function () {
  5112. return Tools._ErrorLogLevel;
  5113. },
  5114. enumerable: true,
  5115. configurable: true
  5116. });
  5117. Object.defineProperty(Tools, "AllLogLevel", {
  5118. get: function () {
  5119. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5120. },
  5121. enumerable: true,
  5122. configurable: true
  5123. });
  5124. Tools._AddLogEntry = function (entry) {
  5125. Tools._LogCache = entry + Tools._LogCache;
  5126. if (Tools.OnNewCacheEntry) {
  5127. Tools.OnNewCacheEntry(entry);
  5128. }
  5129. };
  5130. Tools._FormatMessage = function (message) {
  5131. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5132. var date = new Date();
  5133. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5134. };
  5135. Tools._LogDisabled = function (message) {
  5136. // nothing to do
  5137. };
  5138. Tools._LogEnabled = function (message) {
  5139. var formattedMessage = Tools._FormatMessage(message);
  5140. console.log("BJS - " + formattedMessage);
  5141. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5142. Tools._AddLogEntry(entry);
  5143. };
  5144. Tools._WarnDisabled = function (message) {
  5145. // nothing to do
  5146. };
  5147. Tools._WarnEnabled = function (message) {
  5148. var formattedMessage = Tools._FormatMessage(message);
  5149. console.warn("BJS - " + formattedMessage);
  5150. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5151. Tools._AddLogEntry(entry);
  5152. };
  5153. Tools._ErrorDisabled = function (message) {
  5154. // nothing to do
  5155. };
  5156. Tools._ErrorEnabled = function (message) {
  5157. Tools.errorsCount++;
  5158. var formattedMessage = Tools._FormatMessage(message);
  5159. console.error("BJS - " + formattedMessage);
  5160. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5161. Tools._AddLogEntry(entry);
  5162. };
  5163. Object.defineProperty(Tools, "LogCache", {
  5164. get: function () {
  5165. return Tools._LogCache;
  5166. },
  5167. enumerable: true,
  5168. configurable: true
  5169. });
  5170. Tools.ClearLogCache = function () {
  5171. Tools._LogCache = "";
  5172. Tools.errorsCount = 0;
  5173. };
  5174. Object.defineProperty(Tools, "LogLevels", {
  5175. set: function (level) {
  5176. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5177. Tools.Log = Tools._LogEnabled;
  5178. }
  5179. else {
  5180. Tools.Log = Tools._LogDisabled;
  5181. }
  5182. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5183. Tools.Warn = Tools._WarnEnabled;
  5184. }
  5185. else {
  5186. Tools.Warn = Tools._WarnDisabled;
  5187. }
  5188. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5189. Tools.Error = Tools._ErrorEnabled;
  5190. }
  5191. else {
  5192. Tools.Error = Tools._ErrorDisabled;
  5193. }
  5194. },
  5195. enumerable: true,
  5196. configurable: true
  5197. });
  5198. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5199. get: function () {
  5200. return Tools._PerformanceNoneLogLevel;
  5201. },
  5202. enumerable: true,
  5203. configurable: true
  5204. });
  5205. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5206. get: function () {
  5207. return Tools._PerformanceUserMarkLogLevel;
  5208. },
  5209. enumerable: true,
  5210. configurable: true
  5211. });
  5212. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5213. get: function () {
  5214. return Tools._PerformanceConsoleLogLevel;
  5215. },
  5216. enumerable: true,
  5217. configurable: true
  5218. });
  5219. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5220. set: function (level) {
  5221. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5222. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5223. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5224. return;
  5225. }
  5226. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5227. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5228. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5229. return;
  5230. }
  5231. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5232. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5233. },
  5234. enumerable: true,
  5235. configurable: true
  5236. });
  5237. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5238. };
  5239. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5240. };
  5241. Tools._StartUserMark = function (counterName, condition) {
  5242. if (condition === void 0) { condition = true; }
  5243. if (!condition || !Tools._performance.mark) {
  5244. return;
  5245. }
  5246. Tools._performance.mark(counterName + "-Begin");
  5247. };
  5248. Tools._EndUserMark = function (counterName, condition) {
  5249. if (condition === void 0) { condition = true; }
  5250. if (!condition || !Tools._performance.mark) {
  5251. return;
  5252. }
  5253. Tools._performance.mark(counterName + "-End");
  5254. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5255. };
  5256. Tools._StartPerformanceConsole = function (counterName, condition) {
  5257. if (condition === void 0) { condition = true; }
  5258. if (!condition) {
  5259. return;
  5260. }
  5261. Tools._StartUserMark(counterName, condition);
  5262. if (console.time) {
  5263. console.time(counterName);
  5264. }
  5265. };
  5266. Tools._EndPerformanceConsole = function (counterName, condition) {
  5267. if (condition === void 0) { condition = true; }
  5268. if (!condition) {
  5269. return;
  5270. }
  5271. Tools._EndUserMark(counterName, condition);
  5272. if (console.time) {
  5273. console.timeEnd(counterName);
  5274. }
  5275. };
  5276. Object.defineProperty(Tools, "Now", {
  5277. get: function () {
  5278. if (window.performance && window.performance.now) {
  5279. return window.performance.now();
  5280. }
  5281. return new Date().getTime();
  5282. },
  5283. enumerable: true,
  5284. configurable: true
  5285. });
  5286. /**
  5287. * This method will return the name of the class used to create the instance of the given object.
  5288. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5289. * @param object the object to get the class name from
  5290. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5291. */
  5292. Tools.getClassName = function (object, isType) {
  5293. if (isType === void 0) { isType = false; }
  5294. var name = null;
  5295. if (!isType && object.getClassName) {
  5296. name = object.getClassName();
  5297. }
  5298. else {
  5299. if (object instanceof Object) {
  5300. var classObj = isType ? object : Object.getPrototypeOf(object);
  5301. name = classObj.constructor["__bjsclassName__"];
  5302. }
  5303. if (!name) {
  5304. name = typeof object;
  5305. }
  5306. }
  5307. return name;
  5308. };
  5309. Tools.first = function (array, predicate) {
  5310. for (var _i = 0; _i < array.length; _i++) {
  5311. var el = array[_i];
  5312. if (predicate(el)) {
  5313. return el;
  5314. }
  5315. }
  5316. };
  5317. /**
  5318. * 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.
  5319. * @param array
  5320. */
  5321. Tools.arrayOrStringFeeder = function (array) {
  5322. return function (index) {
  5323. if (index >= array.length) {
  5324. return null;
  5325. }
  5326. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5327. if (val && val.getHashCode) {
  5328. val = val.getHashCode();
  5329. }
  5330. if (typeof val === "string") {
  5331. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5332. }
  5333. return val;
  5334. };
  5335. };
  5336. /**
  5337. * Compute the hashCode of a stream of number
  5338. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5339. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5340. * @return the hash code computed
  5341. */
  5342. Tools.hashCodeFromStream = function (feeder) {
  5343. // Based from here: http://stackoverflow.com/a/7616484/802124
  5344. var hash = 0;
  5345. var index = 0;
  5346. var chr = feeder(index++);
  5347. while (chr != null) {
  5348. hash = ((hash << 5) - hash) + chr;
  5349. hash |= 0; // Convert to 32bit integer
  5350. chr = feeder(index++);
  5351. }
  5352. return hash;
  5353. };
  5354. Tools.BaseUrl = "";
  5355. Tools.CorsBehavior = "anonymous";
  5356. Tools.UseFallbackTexture = true;
  5357. // Logs
  5358. Tools._NoneLogLevel = 0;
  5359. Tools._MessageLogLevel = 1;
  5360. Tools._WarningLogLevel = 2;
  5361. Tools._ErrorLogLevel = 4;
  5362. Tools._LogCache = "";
  5363. Tools.errorsCount = 0;
  5364. Tools.Log = Tools._LogEnabled;
  5365. Tools.Warn = Tools._WarnEnabled;
  5366. Tools.Error = Tools._ErrorEnabled;
  5367. // Performances
  5368. Tools._PerformanceNoneLogLevel = 0;
  5369. Tools._PerformanceUserMarkLogLevel = 1;
  5370. Tools._PerformanceConsoleLogLevel = 2;
  5371. Tools._performance = window.performance;
  5372. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5373. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5374. return Tools;
  5375. })();
  5376. BABYLON.Tools = Tools;
  5377. /**
  5378. * This class is used to track a performance counter which is number based.
  5379. * The user has access to many properties which give statistics of different nature
  5380. *
  5381. * The implementer can track two kinds of Performance Counter: time and count
  5382. * 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.
  5383. * 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.
  5384. */
  5385. var PerfCounter = (function () {
  5386. function PerfCounter() {
  5387. this._startMonitoringTime = 0;
  5388. this._min = 0;
  5389. this._max = 0;
  5390. this._average = 0;
  5391. this._lastSecAverage = 0;
  5392. this._current = 0;
  5393. this._totalValueCount = 0;
  5394. this._totalAccumulated = 0;
  5395. this._lastSecAccumulated = 0;
  5396. this._lastSecTime = 0;
  5397. this._lastSecValueCount = 0;
  5398. }
  5399. Object.defineProperty(PerfCounter.prototype, "min", {
  5400. /**
  5401. * Returns the smallest value ever
  5402. */
  5403. get: function () {
  5404. return this._min;
  5405. },
  5406. enumerable: true,
  5407. configurable: true
  5408. });
  5409. Object.defineProperty(PerfCounter.prototype, "max", {
  5410. /**
  5411. * Returns the biggest value ever
  5412. */
  5413. get: function () {
  5414. return this._max;
  5415. },
  5416. enumerable: true,
  5417. configurable: true
  5418. });
  5419. Object.defineProperty(PerfCounter.prototype, "average", {
  5420. /**
  5421. * Returns the average value since the performance counter is running
  5422. */
  5423. get: function () {
  5424. return this._average;
  5425. },
  5426. enumerable: true,
  5427. configurable: true
  5428. });
  5429. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5430. /**
  5431. * Returns the average value of the last second the counter was monitored
  5432. */
  5433. get: function () {
  5434. return this._lastSecAverage;
  5435. },
  5436. enumerable: true,
  5437. configurable: true
  5438. });
  5439. Object.defineProperty(PerfCounter.prototype, "current", {
  5440. /**
  5441. * Returns the current value
  5442. */
  5443. get: function () {
  5444. return this._current;
  5445. },
  5446. enumerable: true,
  5447. configurable: true
  5448. });
  5449. Object.defineProperty(PerfCounter.prototype, "total", {
  5450. get: function () {
  5451. return this._totalAccumulated;
  5452. },
  5453. enumerable: true,
  5454. configurable: true
  5455. });
  5456. /**
  5457. * Call this method to start monitoring a new frame.
  5458. * 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.
  5459. */
  5460. PerfCounter.prototype.fetchNewFrame = function () {
  5461. this._totalValueCount++;
  5462. this._current = 0;
  5463. this._lastSecValueCount++;
  5464. };
  5465. /**
  5466. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5467. * @param newCount the count value to add to the monitored count
  5468. * @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.
  5469. */
  5470. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5471. this._current += newCount;
  5472. if (fetchResult) {
  5473. this._fetchResult();
  5474. }
  5475. };
  5476. /**
  5477. * Start monitoring this performance counter
  5478. */
  5479. PerfCounter.prototype.beginMonitoring = function () {
  5480. this._startMonitoringTime = Tools.Now;
  5481. };
  5482. /**
  5483. * Compute the time lapsed since the previous beginMonitoring() call.
  5484. * @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
  5485. */
  5486. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5487. if (newFrame === void 0) { newFrame = true; }
  5488. if (newFrame) {
  5489. this.fetchNewFrame();
  5490. }
  5491. var currentTime = Tools.Now;
  5492. this._current = currentTime - this._startMonitoringTime;
  5493. if (newFrame) {
  5494. this._fetchResult();
  5495. }
  5496. };
  5497. PerfCounter.prototype._fetchResult = function () {
  5498. this._totalAccumulated += this._current;
  5499. this._lastSecAccumulated += this._current;
  5500. // Min/Max update
  5501. this._min = Math.min(this._min, this._current);
  5502. this._max = Math.max(this._max, this._current);
  5503. this._average = this._totalAccumulated / this._totalValueCount;
  5504. // Reset last sec?
  5505. var now = Tools.Now;
  5506. if ((now - this._lastSecTime) > 1000) {
  5507. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5508. this._lastSecTime = now;
  5509. this._lastSecAccumulated = 0;
  5510. this._lastSecValueCount = 0;
  5511. }
  5512. };
  5513. return PerfCounter;
  5514. })();
  5515. BABYLON.PerfCounter = PerfCounter;
  5516. /**
  5517. * Use this className as a decorator on a given class definition to add it a name.
  5518. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5519. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5520. * @param name
  5521. */
  5522. function className(name) {
  5523. return function (target) {
  5524. target["__bjsclassName__"] = name;
  5525. };
  5526. }
  5527. BABYLON.className = className;
  5528. /**
  5529. * An implementation of a loop for asynchronous functions.
  5530. */
  5531. var AsyncLoop = (function () {
  5532. /**
  5533. * Constroctor.
  5534. * @param iterations the number of iterations.
  5535. * @param _fn the function to run each iteration
  5536. * @param _successCallback the callback that will be called upon succesful execution
  5537. * @param offset starting offset.
  5538. */
  5539. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5540. if (offset === void 0) { offset = 0; }
  5541. this.iterations = iterations;
  5542. this._fn = _fn;
  5543. this._successCallback = _successCallback;
  5544. this.index = offset - 1;
  5545. this._done = false;
  5546. }
  5547. /**
  5548. * Execute the next iteration. Must be called after the last iteration was finished.
  5549. */
  5550. AsyncLoop.prototype.executeNext = function () {
  5551. if (!this._done) {
  5552. if (this.index + 1 < this.iterations) {
  5553. ++this.index;
  5554. this._fn(this);
  5555. }
  5556. else {
  5557. this.breakLoop();
  5558. }
  5559. }
  5560. };
  5561. /**
  5562. * Break the loop and run the success callback.
  5563. */
  5564. AsyncLoop.prototype.breakLoop = function () {
  5565. this._done = true;
  5566. this._successCallback();
  5567. };
  5568. /**
  5569. * Helper function
  5570. */
  5571. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5572. if (offset === void 0) { offset = 0; }
  5573. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5574. loop.executeNext();
  5575. return loop;
  5576. };
  5577. /**
  5578. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5579. * @param iterations total number of iterations
  5580. * @param syncedIterations number of synchronous iterations in each async iteration.
  5581. * @param fn the function to call each iteration.
  5582. * @param callback a success call back that will be called when iterating stops.
  5583. * @param breakFunction a break condition (optional)
  5584. * @param timeout timeout settings for the setTimeout function. default - 0.
  5585. * @constructor
  5586. */
  5587. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5588. if (timeout === void 0) { timeout = 0; }
  5589. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5590. if (breakFunction && breakFunction())
  5591. loop.breakLoop();
  5592. else {
  5593. setTimeout(function () {
  5594. for (var i = 0; i < syncedIterations; ++i) {
  5595. var iteration = (loop.index * syncedIterations) + i;
  5596. if (iteration >= iterations)
  5597. break;
  5598. fn(iteration);
  5599. if (breakFunction && breakFunction()) {
  5600. loop.breakLoop();
  5601. break;
  5602. }
  5603. }
  5604. loop.executeNext();
  5605. }, timeout);
  5606. }
  5607. }, callback);
  5608. };
  5609. return AsyncLoop;
  5610. })();
  5611. BABYLON.AsyncLoop = AsyncLoop;
  5612. })(BABYLON || (BABYLON = {}));
  5613. var BABYLON;
  5614. (function (BABYLON) {
  5615. var Internals;
  5616. (function (Internals) {
  5617. var _AlphaState = (function () {
  5618. function _AlphaState() {
  5619. this._isAlphaBlendDirty = false;
  5620. this._isBlendFunctionParametersDirty = false;
  5621. this._alphaBlend = false;
  5622. this._blendFunctionParameters = new Array(4);
  5623. }
  5624. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5625. get: function () {
  5626. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5627. },
  5628. enumerable: true,
  5629. configurable: true
  5630. });
  5631. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5632. get: function () {
  5633. return this._alphaBlend;
  5634. },
  5635. set: function (value) {
  5636. if (this._alphaBlend === value) {
  5637. return;
  5638. }
  5639. this._alphaBlend = value;
  5640. this._isAlphaBlendDirty = true;
  5641. },
  5642. enumerable: true,
  5643. configurable: true
  5644. });
  5645. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5646. if (this._blendFunctionParameters[0] === value0 &&
  5647. this._blendFunctionParameters[1] === value1 &&
  5648. this._blendFunctionParameters[2] === value2 &&
  5649. this._blendFunctionParameters[3] === value3) {
  5650. return;
  5651. }
  5652. this._blendFunctionParameters[0] = value0;
  5653. this._blendFunctionParameters[1] = value1;
  5654. this._blendFunctionParameters[2] = value2;
  5655. this._blendFunctionParameters[3] = value3;
  5656. this._isBlendFunctionParametersDirty = true;
  5657. };
  5658. _AlphaState.prototype.reset = function () {
  5659. this._alphaBlend = false;
  5660. this._blendFunctionParameters[0] = null;
  5661. this._blendFunctionParameters[1] = null;
  5662. this._blendFunctionParameters[2] = null;
  5663. this._blendFunctionParameters[3] = null;
  5664. this._isAlphaBlendDirty = true;
  5665. this._isBlendFunctionParametersDirty = false;
  5666. };
  5667. _AlphaState.prototype.apply = function (gl) {
  5668. if (!this.isDirty) {
  5669. return;
  5670. }
  5671. // Alpha blend
  5672. if (this._isAlphaBlendDirty) {
  5673. if (this._alphaBlend) {
  5674. gl.enable(gl.BLEND);
  5675. }
  5676. else {
  5677. gl.disable(gl.BLEND);
  5678. }
  5679. this._isAlphaBlendDirty = false;
  5680. }
  5681. // Alpha function
  5682. if (this._isBlendFunctionParametersDirty) {
  5683. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5684. this._isBlendFunctionParametersDirty = false;
  5685. }
  5686. };
  5687. return _AlphaState;
  5688. })();
  5689. Internals._AlphaState = _AlphaState;
  5690. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5691. })(BABYLON || (BABYLON = {}));
  5692. var BABYLON;
  5693. (function (BABYLON) {
  5694. var Internals;
  5695. (function (Internals) {
  5696. var _DepthCullingState = (function () {
  5697. function _DepthCullingState() {
  5698. this._isDepthTestDirty = false;
  5699. this._isDepthMaskDirty = false;
  5700. this._isDepthFuncDirty = false;
  5701. this._isCullFaceDirty = false;
  5702. this._isCullDirty = false;
  5703. this._isZOffsetDirty = false;
  5704. }
  5705. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5706. get: function () {
  5707. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5708. },
  5709. enumerable: true,
  5710. configurable: true
  5711. });
  5712. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5713. get: function () {
  5714. return this._zOffset;
  5715. },
  5716. set: function (value) {
  5717. if (this._zOffset === value) {
  5718. return;
  5719. }
  5720. this._zOffset = value;
  5721. this._isZOffsetDirty = true;
  5722. },
  5723. enumerable: true,
  5724. configurable: true
  5725. });
  5726. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5727. get: function () {
  5728. return this._cullFace;
  5729. },
  5730. set: function (value) {
  5731. if (this._cullFace === value) {
  5732. return;
  5733. }
  5734. this._cullFace = value;
  5735. this._isCullFaceDirty = true;
  5736. },
  5737. enumerable: true,
  5738. configurable: true
  5739. });
  5740. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5741. get: function () {
  5742. return this._cull;
  5743. },
  5744. set: function (value) {
  5745. if (this._cull === value) {
  5746. return;
  5747. }
  5748. this._cull = value;
  5749. this._isCullDirty = true;
  5750. },
  5751. enumerable: true,
  5752. configurable: true
  5753. });
  5754. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5755. get: function () {
  5756. return this._depthFunc;
  5757. },
  5758. set: function (value) {
  5759. if (this._depthFunc === value) {
  5760. return;
  5761. }
  5762. this._depthFunc = value;
  5763. this._isDepthFuncDirty = true;
  5764. },
  5765. enumerable: true,
  5766. configurable: true
  5767. });
  5768. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5769. get: function () {
  5770. return this._depthMask;
  5771. },
  5772. set: function (value) {
  5773. if (this._depthMask === value) {
  5774. return;
  5775. }
  5776. this._depthMask = value;
  5777. this._isDepthMaskDirty = true;
  5778. },
  5779. enumerable: true,
  5780. configurable: true
  5781. });
  5782. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5783. get: function () {
  5784. return this._depthTest;
  5785. },
  5786. set: function (value) {
  5787. if (this._depthTest === value) {
  5788. return;
  5789. }
  5790. this._depthTest = value;
  5791. this._isDepthTestDirty = true;
  5792. },
  5793. enumerable: true,
  5794. configurable: true
  5795. });
  5796. _DepthCullingState.prototype.reset = function () {
  5797. this._depthMask = true;
  5798. this._depthTest = true;
  5799. this._depthFunc = null;
  5800. this._cullFace = null;
  5801. this._cull = null;
  5802. this._zOffset = 0;
  5803. this._isDepthTestDirty = true;
  5804. this._isDepthMaskDirty = true;
  5805. this._isDepthFuncDirty = false;
  5806. this._isCullFaceDirty = false;
  5807. this._isCullDirty = false;
  5808. this._isZOffsetDirty = false;
  5809. };
  5810. _DepthCullingState.prototype.apply = function (gl) {
  5811. if (!this.isDirty) {
  5812. return;
  5813. }
  5814. // Cull
  5815. if (this._isCullDirty) {
  5816. if (this.cull) {
  5817. gl.enable(gl.CULL_FACE);
  5818. }
  5819. else {
  5820. gl.disable(gl.CULL_FACE);
  5821. }
  5822. this._isCullDirty = false;
  5823. }
  5824. // Cull face
  5825. if (this._isCullFaceDirty) {
  5826. gl.cullFace(this.cullFace);
  5827. this._isCullFaceDirty = false;
  5828. }
  5829. // Depth mask
  5830. if (this._isDepthMaskDirty) {
  5831. gl.depthMask(this.depthMask);
  5832. this._isDepthMaskDirty = false;
  5833. }
  5834. // Depth test
  5835. if (this._isDepthTestDirty) {
  5836. if (this.depthTest) {
  5837. gl.enable(gl.DEPTH_TEST);
  5838. }
  5839. else {
  5840. gl.disable(gl.DEPTH_TEST);
  5841. }
  5842. this._isDepthTestDirty = false;
  5843. }
  5844. // Depth func
  5845. if (this._isDepthFuncDirty) {
  5846. gl.depthFunc(this.depthFunc);
  5847. this._isDepthFuncDirty = false;
  5848. }
  5849. // zOffset
  5850. if (this._isZOffsetDirty) {
  5851. if (this.zOffset) {
  5852. gl.enable(gl.POLYGON_OFFSET_FILL);
  5853. gl.polygonOffset(this.zOffset, 0);
  5854. }
  5855. else {
  5856. gl.disable(gl.POLYGON_OFFSET_FILL);
  5857. }
  5858. this._isZOffsetDirty = false;
  5859. }
  5860. };
  5861. return _DepthCullingState;
  5862. })();
  5863. Internals._DepthCullingState = _DepthCullingState;
  5864. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5865. })(BABYLON || (BABYLON = {}));
  5866. var BABYLON;
  5867. (function (BABYLON) {
  5868. var Internals;
  5869. (function (Internals) {
  5870. var _StencilState = (function () {
  5871. function _StencilState() {
  5872. this._isStencilTestDirty = false;
  5873. this._isStencilMaskDirty = false;
  5874. this._isStencilFuncDirty = false;
  5875. this._isStencilOpDirty = false;
  5876. this.reset();
  5877. }
  5878. Object.defineProperty(_StencilState.prototype, "isDirty", {
  5879. get: function () {
  5880. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  5881. },
  5882. enumerable: true,
  5883. configurable: true
  5884. });
  5885. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  5886. get: function () {
  5887. return this._stencilFunc;
  5888. },
  5889. set: function (value) {
  5890. if (this._stencilFunc === value) {
  5891. return;
  5892. }
  5893. this._stencilFunc = value;
  5894. this._isStencilFuncDirty = true;
  5895. },
  5896. enumerable: true,
  5897. configurable: true
  5898. });
  5899. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  5900. get: function () {
  5901. return this._stencilFuncRef;
  5902. },
  5903. set: function (value) {
  5904. if (this._stencilFuncRef === value) {
  5905. return;
  5906. }
  5907. this._stencilFuncRef = value;
  5908. this._isStencilFuncDirty = true;
  5909. },
  5910. enumerable: true,
  5911. configurable: true
  5912. });
  5913. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  5914. get: function () {
  5915. return this._stencilFuncMask;
  5916. },
  5917. set: function (value) {
  5918. if (this._stencilFuncMask === value) {
  5919. return;
  5920. }
  5921. this._stencilFuncMask = value;
  5922. this._isStencilFuncDirty = true;
  5923. },
  5924. enumerable: true,
  5925. configurable: true
  5926. });
  5927. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  5928. get: function () {
  5929. return this._stencilOpStencilFail;
  5930. },
  5931. set: function (value) {
  5932. if (this._stencilOpStencilFail === value) {
  5933. return;
  5934. }
  5935. this._stencilOpStencilFail = value;
  5936. this._isStencilOpDirty = true;
  5937. },
  5938. enumerable: true,
  5939. configurable: true
  5940. });
  5941. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  5942. get: function () {
  5943. return this._stencilOpDepthFail;
  5944. },
  5945. set: function (value) {
  5946. if (this._stencilOpDepthFail === value) {
  5947. return;
  5948. }
  5949. this._stencilOpDepthFail = value;
  5950. this._isStencilOpDirty = true;
  5951. },
  5952. enumerable: true,
  5953. configurable: true
  5954. });
  5955. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  5956. get: function () {
  5957. return this._stencilOpStencilDepthPass;
  5958. },
  5959. set: function (value) {
  5960. if (this._stencilOpStencilDepthPass === value) {
  5961. return;
  5962. }
  5963. this._stencilOpStencilDepthPass = value;
  5964. this._isStencilOpDirty = true;
  5965. },
  5966. enumerable: true,
  5967. configurable: true
  5968. });
  5969. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  5970. get: function () {
  5971. return this._stencilMask;
  5972. },
  5973. set: function (value) {
  5974. if (this._stencilMask === value) {
  5975. return;
  5976. }
  5977. this._stencilMask = value;
  5978. this._isStencilMaskDirty = true;
  5979. },
  5980. enumerable: true,
  5981. configurable: true
  5982. });
  5983. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  5984. get: function () {
  5985. return this._stencilTest;
  5986. },
  5987. set: function (value) {
  5988. if (this._stencilTest === value) {
  5989. return;
  5990. }
  5991. this._stencilTest = value;
  5992. this._isStencilTestDirty = true;
  5993. },
  5994. enumerable: true,
  5995. configurable: true
  5996. });
  5997. _StencilState.prototype.reset = function () {
  5998. this._stencilTest = false;
  5999. this._stencilMask = 0xFF;
  6000. this._stencilFunc = WebGLRenderingContext.ALWAYS;
  6001. this._stencilFuncRef = 1;
  6002. this._stencilFuncMask = 0xFF;
  6003. this._stencilOpStencilFail = WebGLRenderingContext.KEEP;
  6004. this._stencilOpDepthFail = WebGLRenderingContext.KEEP;
  6005. this._stencilOpStencilDepthPass = WebGLRenderingContext.REPLACE;
  6006. this._isStencilTestDirty = true;
  6007. this._isStencilMaskDirty = true;
  6008. this._isStencilFuncDirty = true;
  6009. this._isStencilOpDirty = true;
  6010. };
  6011. _StencilState.prototype.apply = function (gl) {
  6012. if (!this.isDirty) {
  6013. return;
  6014. }
  6015. // Stencil test
  6016. if (this._isStencilTestDirty) {
  6017. if (this.stencilTest) {
  6018. gl.enable(gl.STENCIL_TEST);
  6019. }
  6020. else {
  6021. gl.disable(gl.STENCIL_TEST);
  6022. }
  6023. this._isStencilTestDirty = false;
  6024. }
  6025. // Stencil mask
  6026. if (this._isStencilMaskDirty) {
  6027. gl.stencilMask(this.stencilMask);
  6028. this._isStencilMaskDirty = false;
  6029. }
  6030. // Stencil func
  6031. if (this._isStencilFuncDirty) {
  6032. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6033. this._isStencilFuncDirty = false;
  6034. }
  6035. // Stencil op
  6036. if (this._isStencilOpDirty) {
  6037. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6038. this._isStencilOpDirty = false;
  6039. }
  6040. };
  6041. return _StencilState;
  6042. })();
  6043. Internals._StencilState = _StencilState;
  6044. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6045. })(BABYLON || (BABYLON = {}));
  6046. var BABYLON;
  6047. (function (BABYLON) {
  6048. var compileShader = function (gl, source, type, defines) {
  6049. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6050. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  6051. gl.compileShader(shader);
  6052. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6053. throw new Error(gl.getShaderInfoLog(shader));
  6054. }
  6055. return shader;
  6056. };
  6057. var HALF_FLOAT_OES = 0x8D61;
  6058. var getWebGLTextureType = function (gl, type) {
  6059. if (type === Engine.TEXTURETYPE_FLOAT) {
  6060. return gl.FLOAT;
  6061. }
  6062. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  6063. // Add Half Float Constant.
  6064. return HALF_FLOAT_OES;
  6065. }
  6066. return gl.UNSIGNED_BYTE;
  6067. };
  6068. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6069. var magFilter = gl.NEAREST;
  6070. var minFilter = gl.NEAREST;
  6071. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6072. magFilter = gl.LINEAR;
  6073. if (generateMipMaps) {
  6074. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6075. }
  6076. else {
  6077. minFilter = gl.LINEAR;
  6078. }
  6079. }
  6080. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6081. magFilter = gl.LINEAR;
  6082. if (generateMipMaps) {
  6083. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6084. }
  6085. else {
  6086. minFilter = gl.LINEAR;
  6087. }
  6088. }
  6089. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6090. magFilter = gl.NEAREST;
  6091. if (generateMipMaps) {
  6092. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6093. }
  6094. else {
  6095. minFilter = gl.NEAREST;
  6096. }
  6097. }
  6098. return {
  6099. min: minFilter,
  6100. mag: magFilter
  6101. };
  6102. };
  6103. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  6104. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6105. var engine = scene.getEngine();
  6106. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6107. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6108. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6109. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6110. texture._baseWidth = width;
  6111. texture._baseHeight = height;
  6112. texture._width = potWidth;
  6113. texture._height = potHeight;
  6114. texture.isReady = true;
  6115. processFunction(potWidth, potHeight);
  6116. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6117. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6118. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6119. if (!noMipmap && !isCompressed) {
  6120. gl.generateMipmap(gl.TEXTURE_2D);
  6121. }
  6122. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6123. engine.resetTextureCache();
  6124. scene._removePendingData(texture);
  6125. if (onLoad) {
  6126. onLoad();
  6127. }
  6128. };
  6129. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  6130. var img;
  6131. var onload = function () {
  6132. loadedImages[index] = img;
  6133. loadedImages._internalCount++;
  6134. scene._removePendingData(img);
  6135. if (loadedImages._internalCount === 6) {
  6136. onfinish(loadedImages);
  6137. }
  6138. };
  6139. var onerror = function () {
  6140. scene._removePendingData(img);
  6141. };
  6142. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6143. scene._addPendingData(img);
  6144. };
  6145. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  6146. var loadedImages = [];
  6147. loadedImages._internalCount = 0;
  6148. for (var index = 0; index < 6; index++) {
  6149. partialLoad(files[index], index, loadedImages, scene, onfinish);
  6150. }
  6151. };
  6152. var InstancingAttributeInfo = (function () {
  6153. function InstancingAttributeInfo() {
  6154. }
  6155. return InstancingAttributeInfo;
  6156. })();
  6157. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6158. var EngineCapabilities = (function () {
  6159. function EngineCapabilities() {
  6160. }
  6161. return EngineCapabilities;
  6162. })();
  6163. BABYLON.EngineCapabilities = EngineCapabilities;
  6164. /**
  6165. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6166. */
  6167. var Engine = (function () {
  6168. /**
  6169. * @constructor
  6170. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6171. * @param {boolean} [antialias] - enable antialias
  6172. * @param options - further options to be sent to the getContext function
  6173. */
  6174. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6175. var _this = this;
  6176. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  6177. // Public members
  6178. this.isFullscreen = false;
  6179. this.isPointerLock = false;
  6180. this.cullBackFaces = true;
  6181. this.renderEvenInBackground = true;
  6182. // To enable/disable IDB support and avoid XHR on .manifest
  6183. this.enableOfflineSupport = true;
  6184. this.scenes = new Array();
  6185. this._windowIsBackground = false;
  6186. this._webGLVersion = "1.0";
  6187. this._drawCalls = new BABYLON.PerfCounter();
  6188. this._renderingQueueLaunched = false;
  6189. this._activeRenderLoops = [];
  6190. // FPS
  6191. this.fpsRange = 60;
  6192. this.previousFramesDuration = [];
  6193. this.fps = 60;
  6194. this.deltaTime = 0;
  6195. // States
  6196. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  6197. this._stencilState = new BABYLON.Internals._StencilState();
  6198. this._alphaState = new BABYLON.Internals._AlphaState();
  6199. this._alphaMode = Engine.ALPHA_DISABLE;
  6200. // Cache
  6201. this._loadedTexturesCache = new Array();
  6202. this._maxTextureChannels = 16;
  6203. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6204. this._compiledEffects = {};
  6205. this._vertexAttribArraysEnabled = [];
  6206. this._uintIndicesCurrentlySet = false;
  6207. this._currentBoundBuffer = new Array();
  6208. this._currentBufferPointers = [];
  6209. this._currentInstanceLocations = new Array();
  6210. this._currentInstanceBuffers = new Array();
  6211. this._renderingCanvas = canvas;
  6212. this._externalData = new BABYLON.StringDictionary();
  6213. options = options || {};
  6214. if (antialias != null) {
  6215. options.antialias = antialias;
  6216. }
  6217. if (options.preserveDrawingBuffer === undefined) {
  6218. options.preserveDrawingBuffer = false;
  6219. }
  6220. // Checks if some of the format renders first to allow the use of webgl inspector.
  6221. var renderToFullFloat = this._canRenderToFloatTexture();
  6222. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  6223. // GL
  6224. //try {
  6225. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6226. // if (this._gl) {
  6227. // this._webGLVersion = "2.0";
  6228. // }
  6229. //} catch (e) {
  6230. // // Do nothing
  6231. //}
  6232. if (!this._gl) {
  6233. try {
  6234. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6235. }
  6236. catch (e) {
  6237. throw new Error("WebGL not supported");
  6238. }
  6239. }
  6240. if (!this._gl) {
  6241. throw new Error("WebGL not supported");
  6242. }
  6243. this._onBlur = function () {
  6244. _this._windowIsBackground = true;
  6245. };
  6246. this._onFocus = function () {
  6247. _this._windowIsBackground = false;
  6248. };
  6249. window.addEventListener("blur", this._onBlur);
  6250. window.addEventListener("focus", this._onFocus);
  6251. // Viewport
  6252. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6253. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6254. this.resize();
  6255. // Caps
  6256. this._isStencilEnable = options.stencil;
  6257. this._caps = new EngineCapabilities();
  6258. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6259. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6260. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6261. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6262. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  6263. // Infos
  6264. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6265. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6266. if (rendererInfo != null) {
  6267. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6268. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6269. }
  6270. if (!this._glVendor) {
  6271. this._glVendor = "Unknown vendor";
  6272. }
  6273. if (!this._glRenderer) {
  6274. this._glRenderer = "Unknown renderer";
  6275. }
  6276. // Extensions
  6277. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6278. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6279. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6280. 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');
  6281. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6282. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6283. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6284. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6285. this._caps.highPrecisionShaderSupported = true;
  6286. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6287. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6288. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6289. this._caps.textureFloatRender = renderToFullFloat;
  6290. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  6291. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  6292. this._caps.textureHalfFloatRender = renderToHalfFloat;
  6293. if (this._gl.getShaderPrecisionFormat) {
  6294. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6295. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6296. }
  6297. // Depth buffer
  6298. this.setDepthBuffer(true);
  6299. this.setDepthFunctionToLessOrEqual();
  6300. this.setDepthWrite(true);
  6301. // Fullscreen
  6302. this._onFullscreenChange = function () {
  6303. if (document.fullscreen !== undefined) {
  6304. _this.isFullscreen = document.fullscreen;
  6305. }
  6306. else if (document.mozFullScreen !== undefined) {
  6307. _this.isFullscreen = document.mozFullScreen;
  6308. }
  6309. else if (document.webkitIsFullScreen !== undefined) {
  6310. _this.isFullscreen = document.webkitIsFullScreen;
  6311. }
  6312. else if (document.msIsFullScreen !== undefined) {
  6313. _this.isFullscreen = document.msIsFullScreen;
  6314. }
  6315. // Pointer lock
  6316. if (_this.isFullscreen && _this._pointerLockRequested) {
  6317. canvas.requestPointerLock = canvas.requestPointerLock ||
  6318. canvas.msRequestPointerLock ||
  6319. canvas.mozRequestPointerLock ||
  6320. canvas.webkitRequestPointerLock;
  6321. if (canvas.requestPointerLock) {
  6322. canvas.requestPointerLock();
  6323. }
  6324. }
  6325. };
  6326. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6327. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6328. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6329. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6330. // Pointer lock
  6331. this._onPointerLockChange = function () {
  6332. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6333. document.webkitPointerLockElement === canvas ||
  6334. document.msPointerLockElement === canvas ||
  6335. document.pointerLockElement === canvas);
  6336. };
  6337. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6338. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6339. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6340. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6341. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6342. Engine.audioEngine = new BABYLON.AudioEngine();
  6343. }
  6344. //default loading screen
  6345. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6346. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6347. }
  6348. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6349. get: function () {
  6350. return Engine._ALPHA_DISABLE;
  6351. },
  6352. enumerable: true,
  6353. configurable: true
  6354. });
  6355. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6356. get: function () {
  6357. return Engine._ALPHA_ONEONE;
  6358. },
  6359. enumerable: true,
  6360. configurable: true
  6361. });
  6362. Object.defineProperty(Engine, "ALPHA_ADD", {
  6363. get: function () {
  6364. return Engine._ALPHA_ADD;
  6365. },
  6366. enumerable: true,
  6367. configurable: true
  6368. });
  6369. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6370. get: function () {
  6371. return Engine._ALPHA_COMBINE;
  6372. },
  6373. enumerable: true,
  6374. configurable: true
  6375. });
  6376. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6377. get: function () {
  6378. return Engine._ALPHA_SUBTRACT;
  6379. },
  6380. enumerable: true,
  6381. configurable: true
  6382. });
  6383. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6384. get: function () {
  6385. return Engine._ALPHA_MULTIPLY;
  6386. },
  6387. enumerable: true,
  6388. configurable: true
  6389. });
  6390. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6391. get: function () {
  6392. return Engine._ALPHA_MAXIMIZED;
  6393. },
  6394. enumerable: true,
  6395. configurable: true
  6396. });
  6397. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6398. get: function () {
  6399. return Engine._DELAYLOADSTATE_NONE;
  6400. },
  6401. enumerable: true,
  6402. configurable: true
  6403. });
  6404. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6405. get: function () {
  6406. return Engine._DELAYLOADSTATE_LOADED;
  6407. },
  6408. enumerable: true,
  6409. configurable: true
  6410. });
  6411. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6412. get: function () {
  6413. return Engine._DELAYLOADSTATE_LOADING;
  6414. },
  6415. enumerable: true,
  6416. configurable: true
  6417. });
  6418. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6419. get: function () {
  6420. return Engine._DELAYLOADSTATE_NOTLOADED;
  6421. },
  6422. enumerable: true,
  6423. configurable: true
  6424. });
  6425. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6426. get: function () {
  6427. return Engine._TEXTUREFORMAT_ALPHA;
  6428. },
  6429. enumerable: true,
  6430. configurable: true
  6431. });
  6432. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6433. get: function () {
  6434. return Engine._TEXTUREFORMAT_LUMINANCE;
  6435. },
  6436. enumerable: true,
  6437. configurable: true
  6438. });
  6439. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6440. get: function () {
  6441. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6442. },
  6443. enumerable: true,
  6444. configurable: true
  6445. });
  6446. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6447. get: function () {
  6448. return Engine._TEXTUREFORMAT_RGB;
  6449. },
  6450. enumerable: true,
  6451. configurable: true
  6452. });
  6453. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6454. get: function () {
  6455. return Engine._TEXTUREFORMAT_RGBA;
  6456. },
  6457. enumerable: true,
  6458. configurable: true
  6459. });
  6460. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6461. get: function () {
  6462. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6463. },
  6464. enumerable: true,
  6465. configurable: true
  6466. });
  6467. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6468. get: function () {
  6469. return Engine._TEXTURETYPE_FLOAT;
  6470. },
  6471. enumerable: true,
  6472. configurable: true
  6473. });
  6474. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  6475. get: function () {
  6476. return Engine._TEXTURETYPE_HALF_FLOAT;
  6477. },
  6478. enumerable: true,
  6479. configurable: true
  6480. });
  6481. Object.defineProperty(Engine, "Version", {
  6482. get: function () {
  6483. return "2.5-alpha";
  6484. },
  6485. enumerable: true,
  6486. configurable: true
  6487. });
  6488. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6489. get: function () {
  6490. return this._webGLVersion;
  6491. },
  6492. enumerable: true,
  6493. configurable: true
  6494. });
  6495. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  6496. /**
  6497. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  6498. */
  6499. get: function () {
  6500. return this._isStencilEnable;
  6501. },
  6502. enumerable: true,
  6503. configurable: true
  6504. });
  6505. Engine.prototype._prepareWorkingCanvas = function () {
  6506. if (this._workingCanvas) {
  6507. return;
  6508. }
  6509. this._workingCanvas = document.createElement("canvas");
  6510. this._workingContext = this._workingCanvas.getContext("2d");
  6511. };
  6512. Engine.prototype.resetTextureCache = function () {
  6513. for (var index = 0; index < this._maxTextureChannels; index++) {
  6514. this._activeTexturesCache[index] = null;
  6515. }
  6516. };
  6517. Engine.prototype.getGlInfo = function () {
  6518. return {
  6519. vendor: this._glVendor,
  6520. renderer: this._glRenderer,
  6521. version: this._glVersion
  6522. };
  6523. };
  6524. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  6525. if (useScreen === void 0) { useScreen = false; }
  6526. var viewport = camera.viewport;
  6527. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  6528. };
  6529. Engine.prototype.getRenderWidth = function (useScreen) {
  6530. if (useScreen === void 0) { useScreen = false; }
  6531. if (!useScreen && this._currentRenderTarget) {
  6532. return this._currentRenderTarget._width;
  6533. }
  6534. return this._renderingCanvas.width;
  6535. };
  6536. Engine.prototype.getRenderHeight = function (useScreen) {
  6537. if (useScreen === void 0) { useScreen = false; }
  6538. if (!useScreen && this._currentRenderTarget) {
  6539. return this._currentRenderTarget._height;
  6540. }
  6541. return this._renderingCanvas.height;
  6542. };
  6543. Engine.prototype.getRenderingCanvas = function () {
  6544. return this._renderingCanvas;
  6545. };
  6546. Engine.prototype.getRenderingCanvasClientRect = function () {
  6547. return this._renderingCanvas.getBoundingClientRect();
  6548. };
  6549. Engine.prototype.setHardwareScalingLevel = function (level) {
  6550. this._hardwareScalingLevel = level;
  6551. this.resize();
  6552. };
  6553. Engine.prototype.getHardwareScalingLevel = function () {
  6554. return this._hardwareScalingLevel;
  6555. };
  6556. Engine.prototype.getLoadedTexturesCache = function () {
  6557. return this._loadedTexturesCache;
  6558. };
  6559. Engine.prototype.getCaps = function () {
  6560. return this._caps;
  6561. };
  6562. Object.defineProperty(Engine.prototype, "drawCalls", {
  6563. get: function () {
  6564. return this._drawCalls.current;
  6565. },
  6566. enumerable: true,
  6567. configurable: true
  6568. });
  6569. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  6570. get: function () {
  6571. return this._drawCalls;
  6572. },
  6573. enumerable: true,
  6574. configurable: true
  6575. });
  6576. Engine.prototype.getDepthFunction = function () {
  6577. return this._depthCullingState.depthFunc;
  6578. };
  6579. Engine.prototype.setDepthFunction = function (depthFunc) {
  6580. this._depthCullingState.depthFunc = depthFunc;
  6581. };
  6582. Engine.prototype.setDepthFunctionToGreater = function () {
  6583. this._depthCullingState.depthFunc = this._gl.GREATER;
  6584. };
  6585. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  6586. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  6587. };
  6588. Engine.prototype.setDepthFunctionToLess = function () {
  6589. this._depthCullingState.depthFunc = this._gl.LESS;
  6590. };
  6591. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  6592. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  6593. };
  6594. Engine.prototype.getStencilBuffer = function () {
  6595. return this._stencilState.stencilTest;
  6596. };
  6597. Engine.prototype.setStencilBuffer = function (enable) {
  6598. this._stencilState.stencilTest = enable;
  6599. };
  6600. Engine.prototype.getStencilMask = function () {
  6601. return this._stencilState.stencilMask;
  6602. };
  6603. Engine.prototype.setStencilMask = function (mask) {
  6604. this._stencilState.stencilMask = mask;
  6605. };
  6606. Engine.prototype.getStencilFunction = function () {
  6607. return this._stencilState.stencilFunc;
  6608. };
  6609. Engine.prototype.getStencilFunctionReference = function () {
  6610. return this._stencilState.stencilFuncRef;
  6611. };
  6612. Engine.prototype.getStencilFunctionMask = function () {
  6613. return this._stencilState.stencilFuncMask;
  6614. };
  6615. Engine.prototype.setStencilFunction = function (stencilFunc) {
  6616. this._stencilState.stencilFunc = stencilFunc;
  6617. };
  6618. Engine.prototype.setStencilFunctionReference = function (reference) {
  6619. this._stencilState.stencilFuncRef = reference;
  6620. };
  6621. Engine.prototype.setStencilFunctionMask = function (mask) {
  6622. this._stencilState.stencilFuncMask = mask;
  6623. };
  6624. Engine.prototype.getStencilOperationFail = function () {
  6625. return this._stencilState.stencilOpStencilFail;
  6626. };
  6627. Engine.prototype.getStencilOperationDepthFail = function () {
  6628. return this._stencilState.stencilOpDepthFail;
  6629. };
  6630. Engine.prototype.getStencilOperationPass = function () {
  6631. return this._stencilState.stencilOpStencilDepthPass;
  6632. };
  6633. Engine.prototype.setStencilOperationFail = function (operation) {
  6634. this._stencilState.stencilOpStencilFail = operation;
  6635. };
  6636. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  6637. this._stencilState.stencilOpDepthFail = operation;
  6638. };
  6639. Engine.prototype.setStencilOperationPass = function (operation) {
  6640. this._stencilState.stencilOpStencilDepthPass = operation;
  6641. };
  6642. /**
  6643. * stop executing a render loop function and remove it from the execution array
  6644. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  6645. */
  6646. Engine.prototype.stopRenderLoop = function (renderFunction) {
  6647. if (!renderFunction) {
  6648. this._activeRenderLoops = [];
  6649. return;
  6650. }
  6651. var index = this._activeRenderLoops.indexOf(renderFunction);
  6652. if (index >= 0) {
  6653. this._activeRenderLoops.splice(index, 1);
  6654. }
  6655. };
  6656. Engine.prototype._renderLoop = function () {
  6657. var shouldRender = true;
  6658. if (!this.renderEvenInBackground && this._windowIsBackground) {
  6659. shouldRender = false;
  6660. }
  6661. if (shouldRender) {
  6662. // Start new frame
  6663. this.beginFrame();
  6664. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  6665. var renderFunction = this._activeRenderLoops[index];
  6666. renderFunction();
  6667. }
  6668. // Present
  6669. this.endFrame();
  6670. }
  6671. if (this._activeRenderLoops.length > 0) {
  6672. // Register new frame
  6673. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6674. }
  6675. else {
  6676. this._renderingQueueLaunched = false;
  6677. }
  6678. };
  6679. /**
  6680. * Register and execute a render loop. The engine can have more than one render function.
  6681. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  6682. * @example
  6683. * engine.runRenderLoop(function () {
  6684. * scene.render()
  6685. * })
  6686. */
  6687. Engine.prototype.runRenderLoop = function (renderFunction) {
  6688. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  6689. return;
  6690. }
  6691. this._activeRenderLoops.push(renderFunction);
  6692. if (!this._renderingQueueLaunched) {
  6693. this._renderingQueueLaunched = true;
  6694. this._bindedRenderFunction = this._renderLoop.bind(this);
  6695. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6696. }
  6697. };
  6698. /**
  6699. * Toggle full screen mode.
  6700. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  6701. * @param {any} options - an options object to be sent to the requestFullscreen function
  6702. */
  6703. Engine.prototype.switchFullscreen = function (requestPointerLock, options) {
  6704. if (this.isFullscreen) {
  6705. BABYLON.Tools.ExitFullscreen();
  6706. }
  6707. else {
  6708. this._pointerLockRequested = requestPointerLock;
  6709. BABYLON.Tools.RequestFullscreen(this._renderingCanvas, options);
  6710. }
  6711. };
  6712. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  6713. if (stencil === void 0) { stencil = false; }
  6714. this.applyStates();
  6715. var mode = 0;
  6716. if (backBuffer) {
  6717. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  6718. mode |= this._gl.COLOR_BUFFER_BIT;
  6719. }
  6720. if (depth) {
  6721. this._gl.clearDepth(1.0);
  6722. mode |= this._gl.DEPTH_BUFFER_BIT;
  6723. }
  6724. if (stencil) {
  6725. this._gl.clearStencil(0);
  6726. mode |= this._gl.STENCIL_BUFFER_BIT;
  6727. }
  6728. this._gl.clear(mode);
  6729. };
  6730. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  6731. var gl = this._gl;
  6732. // Save state
  6733. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  6734. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  6735. // Change state
  6736. gl.enable(gl.SCISSOR_TEST);
  6737. gl.scissor(x, y, width, height);
  6738. // Clear
  6739. this.clear(clearColor, true, true, true);
  6740. // Restore state
  6741. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  6742. if (curScissor === true) {
  6743. gl.enable(gl.SCISSOR_TEST);
  6744. }
  6745. else {
  6746. gl.disable(gl.SCISSOR_TEST);
  6747. }
  6748. };
  6749. /**
  6750. * Set the WebGL's viewport
  6751. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  6752. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  6753. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  6754. */
  6755. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  6756. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  6757. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  6758. var x = viewport.x || 0;
  6759. var y = viewport.y || 0;
  6760. this._cachedViewport = viewport;
  6761. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  6762. };
  6763. /**
  6764. * Directly set the WebGL Viewport
  6765. * The x, y, width & height are directly passed to the WebGL call
  6766. * @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.
  6767. */
  6768. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  6769. var currentViewport = this._cachedViewport;
  6770. this._cachedViewport = null;
  6771. this._gl.viewport(x, y, width, height);
  6772. return currentViewport;
  6773. };
  6774. Engine.prototype.beginFrame = function () {
  6775. this._measureFps();
  6776. };
  6777. Engine.prototype.endFrame = function () {
  6778. //this.flushFramebuffer();
  6779. };
  6780. /**
  6781. * resize the view according to the canvas' size.
  6782. * @example
  6783. * window.addEventListener("resize", function () {
  6784. * engine.resize();
  6785. * });
  6786. */
  6787. Engine.prototype.resize = function () {
  6788. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  6789. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  6790. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  6791. for (var index = 0; index < this.scenes.length; index++) {
  6792. var scene = this.scenes[index];
  6793. if (BABYLON.DebugLayer && scene.debugLayer.isVisible()) {
  6794. scene.debugLayer._syncPositions();
  6795. }
  6796. }
  6797. };
  6798. /**
  6799. * force a specific size of the canvas
  6800. * @param {number} width - the new canvas' width
  6801. * @param {number} height - the new canvas' height
  6802. */
  6803. Engine.prototype.setSize = function (width, height) {
  6804. this._renderingCanvas.width = width;
  6805. this._renderingCanvas.height = height;
  6806. for (var index = 0; index < this.scenes.length; index++) {
  6807. var scene = this.scenes[index];
  6808. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  6809. var cam = scene.cameras[camIndex];
  6810. cam._currentRenderId = 0;
  6811. }
  6812. }
  6813. };
  6814. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  6815. this._currentRenderTarget = texture;
  6816. this.bindUnboundFramebuffer(texture._framebuffer);
  6817. var gl = this._gl;
  6818. if (texture.isCube) {
  6819. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  6820. }
  6821. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  6822. this.wipeCaches();
  6823. };
  6824. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  6825. if (this._currentFramebuffer !== framebuffer) {
  6826. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  6827. this._currentFramebuffer = framebuffer;
  6828. }
  6829. };
  6830. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  6831. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  6832. this._currentRenderTarget = null;
  6833. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  6834. var gl = this._gl;
  6835. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6836. gl.generateMipmap(gl.TEXTURE_2D);
  6837. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  6838. }
  6839. this.bindUnboundFramebuffer(null);
  6840. };
  6841. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  6842. if (texture.generateMipMaps) {
  6843. var gl = this._gl;
  6844. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  6845. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6846. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  6847. }
  6848. };
  6849. Engine.prototype.flushFramebuffer = function () {
  6850. this._gl.flush();
  6851. };
  6852. Engine.prototype.restoreDefaultFramebuffer = function () {
  6853. this._currentRenderTarget = null;
  6854. this.bindUnboundFramebuffer(null);
  6855. this.setViewport(this._cachedViewport);
  6856. this.wipeCaches();
  6857. };
  6858. // VBOs
  6859. Engine.prototype._resetVertexBufferBinding = function () {
  6860. this.bindArrayBuffer(null);
  6861. this._cachedVertexBuffers = null;
  6862. };
  6863. Engine.prototype.createVertexBuffer = function (vertices) {
  6864. var vbo = this._gl.createBuffer();
  6865. this.bindArrayBuffer(vbo);
  6866. if (vertices instanceof Float32Array) {
  6867. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  6868. }
  6869. else {
  6870. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  6871. }
  6872. this._resetVertexBufferBinding();
  6873. vbo.references = 1;
  6874. return vbo;
  6875. };
  6876. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  6877. var vbo = this._gl.createBuffer();
  6878. this.bindArrayBuffer(vbo);
  6879. if (vertices instanceof Float32Array) {
  6880. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  6881. }
  6882. else {
  6883. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  6884. }
  6885. this._resetVertexBufferBinding();
  6886. vbo.references = 1;
  6887. return vbo;
  6888. };
  6889. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  6890. this.bindArrayBuffer(vertexBuffer);
  6891. if (offset === undefined) {
  6892. offset = 0;
  6893. }
  6894. if (count === undefined) {
  6895. if (vertices instanceof Float32Array) {
  6896. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6897. }
  6898. else {
  6899. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6900. }
  6901. }
  6902. else {
  6903. if (vertices instanceof Float32Array) {
  6904. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  6905. }
  6906. else {
  6907. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  6908. }
  6909. }
  6910. this._resetVertexBufferBinding();
  6911. };
  6912. Engine.prototype._resetIndexBufferBinding = function () {
  6913. this.bindIndexBuffer(null);
  6914. this._cachedIndexBuffer = null;
  6915. };
  6916. Engine.prototype.createIndexBuffer = function (indices) {
  6917. var vbo = this._gl.createBuffer();
  6918. this.bindIndexBuffer(vbo);
  6919. // Check for 32 bits indices
  6920. var arrayBuffer;
  6921. var need32Bits = false;
  6922. if (this._caps.uintIndices) {
  6923. for (var index = 0; index < indices.length; index++) {
  6924. if (indices[index] > 65535) {
  6925. need32Bits = true;
  6926. break;
  6927. }
  6928. }
  6929. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6930. }
  6931. else {
  6932. arrayBuffer = new Uint16Array(indices);
  6933. }
  6934. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6935. this._resetIndexBufferBinding();
  6936. vbo.references = 1;
  6937. vbo.is32Bits = need32Bits;
  6938. return vbo;
  6939. };
  6940. Engine.prototype.bindArrayBuffer = function (buffer) {
  6941. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  6942. };
  6943. Engine.prototype.bindIndexBuffer = function (buffer) {
  6944. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  6945. };
  6946. Engine.prototype.bindBuffer = function (buffer, target) {
  6947. if (this._currentBoundBuffer[target] !== buffer) {
  6948. this._gl.bindBuffer(target, buffer);
  6949. this._currentBoundBuffer[target] = buffer;
  6950. }
  6951. };
  6952. Engine.prototype.updateArrayBuffer = function (data) {
  6953. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6954. };
  6955. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  6956. var pointer = this._currentBufferPointers[indx];
  6957. var changed = false;
  6958. if (!pointer) {
  6959. changed = true;
  6960. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  6961. }
  6962. else {
  6963. if (pointer.buffer !== buffer) {
  6964. pointer.buffer = buffer;
  6965. changed = true;
  6966. }
  6967. if (pointer.size !== size) {
  6968. pointer.size = size;
  6969. changed = true;
  6970. }
  6971. if (pointer.type !== type) {
  6972. pointer.type = type;
  6973. changed = true;
  6974. }
  6975. if (pointer.normalized !== normalized) {
  6976. pointer.normalized = normalized;
  6977. changed = true;
  6978. }
  6979. if (pointer.stride !== stride) {
  6980. pointer.stride = stride;
  6981. changed = true;
  6982. }
  6983. if (pointer.offset !== offset) {
  6984. pointer.offset = offset;
  6985. changed = true;
  6986. }
  6987. }
  6988. if (changed) {
  6989. this.bindArrayBuffer(buffer);
  6990. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  6991. }
  6992. };
  6993. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6994. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6995. this._cachedVertexBuffers = vertexBuffer;
  6996. this._cachedEffectForVertexBuffers = effect;
  6997. var attributesCount = effect.getAttributesCount();
  6998. var offset = 0;
  6999. for (var index = 0; index < attributesCount; index++) {
  7000. if (index < vertexDeclaration.length) {
  7001. var order = effect.getAttributeLocation(index);
  7002. if (order >= 0) {
  7003. if (!this._vertexAttribArraysEnabled[order]) {
  7004. this._gl.enableVertexAttribArray(order);
  7005. this._vertexAttribArraysEnabled[order] = true;
  7006. }
  7007. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7008. }
  7009. offset += vertexDeclaration[index] * 4;
  7010. }
  7011. else {
  7012. //disable effect attributes that have no data
  7013. var order = effect.getAttributeLocation(index);
  7014. if (this._vertexAttribArraysEnabled[order]) {
  7015. this._gl.disableVertexAttribArray(order);
  7016. this._vertexAttribArraysEnabled[order] = false;
  7017. }
  7018. }
  7019. }
  7020. }
  7021. if (this._cachedIndexBuffer !== indexBuffer) {
  7022. this._cachedIndexBuffer = indexBuffer;
  7023. this.bindIndexBuffer(indexBuffer);
  7024. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7025. }
  7026. };
  7027. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7028. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7029. this._cachedVertexBuffers = vertexBuffers;
  7030. this._cachedEffectForVertexBuffers = effect;
  7031. var attributes = effect.getAttributesNames();
  7032. for (var index = 0; index < attributes.length; index++) {
  7033. var order = effect.getAttributeLocation(index);
  7034. if (order >= 0) {
  7035. var vertexBuffer = vertexBuffers[attributes[index]];
  7036. if (!vertexBuffer) {
  7037. if (this._vertexAttribArraysEnabled[order]) {
  7038. this._gl.disableVertexAttribArray(order);
  7039. this._vertexAttribArraysEnabled[order] = false;
  7040. }
  7041. continue;
  7042. }
  7043. if (!this._vertexAttribArraysEnabled[order]) {
  7044. this._gl.enableVertexAttribArray(order);
  7045. this._vertexAttribArraysEnabled[order] = true;
  7046. }
  7047. var buffer = vertexBuffer.getBuffer();
  7048. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7049. if (vertexBuffer.getIsInstanced()) {
  7050. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  7051. this._currentInstanceLocations.push(order);
  7052. this._currentInstanceBuffers.push(buffer);
  7053. }
  7054. }
  7055. }
  7056. }
  7057. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  7058. this._cachedIndexBuffer = indexBuffer;
  7059. this.bindIndexBuffer(indexBuffer);
  7060. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7061. }
  7062. };
  7063. Engine.prototype.unbindInstanceAttributes = function () {
  7064. var boundBuffer;
  7065. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7066. var instancesBuffer = this._currentInstanceBuffers[i];
  7067. if (boundBuffer != instancesBuffer) {
  7068. boundBuffer = instancesBuffer;
  7069. this.bindArrayBuffer(instancesBuffer);
  7070. }
  7071. var offsetLocation = this._currentInstanceLocations[i];
  7072. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  7073. }
  7074. this._currentInstanceBuffers.length = 0;
  7075. this._currentInstanceLocations.length = 0;
  7076. };
  7077. Engine.prototype._releaseBuffer = function (buffer) {
  7078. buffer.references--;
  7079. if (buffer.references === 0) {
  7080. this._gl.deleteBuffer(buffer);
  7081. return true;
  7082. }
  7083. return false;
  7084. };
  7085. Engine.prototype.createInstancesBuffer = function (capacity) {
  7086. var buffer = this._gl.createBuffer();
  7087. buffer.capacity = capacity;
  7088. this.bindArrayBuffer(buffer);
  7089. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7090. return buffer;
  7091. };
  7092. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7093. this._gl.deleteBuffer(buffer);
  7094. };
  7095. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7096. this.bindArrayBuffer(instancesBuffer);
  7097. if (data) {
  7098. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7099. }
  7100. if (offsetLocations[0].index !== undefined) {
  7101. var stride = 0;
  7102. for (var i = 0; i < offsetLocations.length; i++) {
  7103. var ai = offsetLocations[i];
  7104. stride += ai.attributeSize * 4;
  7105. }
  7106. for (var i = 0; i < offsetLocations.length; i++) {
  7107. var ai = offsetLocations[i];
  7108. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7109. this._gl.enableVertexAttribArray(ai.index);
  7110. this._vertexAttribArraysEnabled[ai.index] = true;
  7111. }
  7112. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7113. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  7114. this._currentInstanceLocations.push(ai.index);
  7115. this._currentInstanceBuffers.push(instancesBuffer);
  7116. }
  7117. }
  7118. else {
  7119. for (var index = 0; index < 4; index++) {
  7120. var offsetLocation = offsetLocations[index];
  7121. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7122. this._gl.enableVertexAttribArray(offsetLocation);
  7123. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7124. }
  7125. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7126. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  7127. this._currentInstanceLocations.push(offsetLocation);
  7128. this._currentInstanceBuffers.push(instancesBuffer);
  7129. }
  7130. }
  7131. };
  7132. Engine.prototype.applyStates = function () {
  7133. this._depthCullingState.apply(this._gl);
  7134. this._stencilState.apply(this._gl);
  7135. this._alphaState.apply(this._gl);
  7136. };
  7137. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7138. // Apply states
  7139. this.applyStates();
  7140. this._drawCalls.addCount(1, false);
  7141. // Render
  7142. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7143. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7144. if (instancesCount) {
  7145. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7146. return;
  7147. }
  7148. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7149. };
  7150. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7151. // Apply states
  7152. this.applyStates();
  7153. this._drawCalls.addCount(1, false);
  7154. if (instancesCount) {
  7155. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7156. return;
  7157. }
  7158. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7159. };
  7160. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7161. // Apply states
  7162. this.applyStates();
  7163. this._drawCalls.addCount(1, false);
  7164. if (instancesCount) {
  7165. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7166. return;
  7167. }
  7168. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7169. };
  7170. // Shaders
  7171. Engine.prototype._releaseEffect = function (effect) {
  7172. if (this._compiledEffects[effect._key]) {
  7173. delete this._compiledEffects[effect._key];
  7174. if (effect.getProgram()) {
  7175. this._gl.deleteProgram(effect.getProgram());
  7176. }
  7177. }
  7178. };
  7179. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7180. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7181. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7182. var name = vertex + "+" + fragment + "@" + defines;
  7183. if (this._compiledEffects[name]) {
  7184. return this._compiledEffects[name];
  7185. }
  7186. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7187. effect._key = name;
  7188. this._compiledEffects[name] = effect;
  7189. return effect;
  7190. };
  7191. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7192. if (uniformsNames === void 0) { uniformsNames = []; }
  7193. if (samplers === void 0) { samplers = []; }
  7194. if (defines === void 0) { defines = ""; }
  7195. return this.createEffect({
  7196. vertex: "particles",
  7197. fragmentElement: fragmentName
  7198. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7199. };
  7200. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7201. context = context || this._gl;
  7202. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  7203. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  7204. var shaderProgram = context.createProgram();
  7205. context.attachShader(shaderProgram, vertexShader);
  7206. context.attachShader(shaderProgram, fragmentShader);
  7207. context.linkProgram(shaderProgram);
  7208. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7209. if (!linked) {
  7210. var error = context.getProgramInfoLog(shaderProgram);
  7211. if (error) {
  7212. throw new Error(error);
  7213. }
  7214. }
  7215. context.deleteShader(vertexShader);
  7216. context.deleteShader(fragmentShader);
  7217. return shaderProgram;
  7218. };
  7219. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7220. var results = [];
  7221. for (var index = 0; index < uniformsNames.length; index++) {
  7222. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7223. }
  7224. return results;
  7225. };
  7226. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7227. var results = [];
  7228. for (var index = 0; index < attributesNames.length; index++) {
  7229. try {
  7230. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7231. }
  7232. catch (e) {
  7233. results.push(-1);
  7234. }
  7235. }
  7236. return results;
  7237. };
  7238. Engine.prototype.enableEffect = function (effect) {
  7239. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  7240. if (effect && effect.onBind) {
  7241. effect.onBind(effect);
  7242. }
  7243. return;
  7244. }
  7245. // Use program
  7246. this.setProgram(effect.getProgram());
  7247. this._currentEffect = effect;
  7248. if (effect.onBind) {
  7249. effect.onBind(effect);
  7250. }
  7251. };
  7252. Engine.prototype.setIntArray = function (uniform, array) {
  7253. if (!uniform)
  7254. return;
  7255. this._gl.uniform1iv(uniform, array);
  7256. };
  7257. Engine.prototype.setIntArray2 = function (uniform, array) {
  7258. if (!uniform || array.length % 2 !== 0)
  7259. return;
  7260. this._gl.uniform2iv(uniform, array);
  7261. };
  7262. Engine.prototype.setIntArray3 = function (uniform, array) {
  7263. if (!uniform || array.length % 3 !== 0)
  7264. return;
  7265. this._gl.uniform3iv(uniform, array);
  7266. };
  7267. Engine.prototype.setIntArray4 = function (uniform, array) {
  7268. if (!uniform || array.length % 4 !== 0)
  7269. return;
  7270. this._gl.uniform4iv(uniform, array);
  7271. };
  7272. Engine.prototype.setFloatArray = function (uniform, array) {
  7273. if (!uniform)
  7274. return;
  7275. this._gl.uniform1fv(uniform, array);
  7276. };
  7277. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7278. if (!uniform || array.length % 2 !== 0)
  7279. return;
  7280. this._gl.uniform2fv(uniform, array);
  7281. };
  7282. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7283. if (!uniform || array.length % 3 !== 0)
  7284. return;
  7285. this._gl.uniform3fv(uniform, array);
  7286. };
  7287. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7288. if (!uniform || array.length % 4 !== 0)
  7289. return;
  7290. this._gl.uniform4fv(uniform, array);
  7291. };
  7292. Engine.prototype.setArray = function (uniform, array) {
  7293. if (!uniform)
  7294. return;
  7295. this._gl.uniform1fv(uniform, array);
  7296. };
  7297. Engine.prototype.setArray2 = function (uniform, array) {
  7298. if (!uniform || array.length % 2 !== 0)
  7299. return;
  7300. this._gl.uniform2fv(uniform, array);
  7301. };
  7302. Engine.prototype.setArray3 = function (uniform, array) {
  7303. if (!uniform || array.length % 3 !== 0)
  7304. return;
  7305. this._gl.uniform3fv(uniform, array);
  7306. };
  7307. Engine.prototype.setArray4 = function (uniform, array) {
  7308. if (!uniform || array.length % 4 !== 0)
  7309. return;
  7310. this._gl.uniform4fv(uniform, array);
  7311. };
  7312. Engine.prototype.setMatrices = function (uniform, matrices) {
  7313. if (!uniform)
  7314. return;
  7315. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7316. };
  7317. Engine.prototype.setMatrix = function (uniform, matrix) {
  7318. if (!uniform)
  7319. return;
  7320. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7321. };
  7322. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7323. if (!uniform)
  7324. return;
  7325. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7326. };
  7327. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7328. if (!uniform)
  7329. return;
  7330. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7331. };
  7332. Engine.prototype.setFloat = function (uniform, value) {
  7333. if (!uniform)
  7334. return;
  7335. this._gl.uniform1f(uniform, value);
  7336. };
  7337. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7338. if (!uniform)
  7339. return;
  7340. this._gl.uniform2f(uniform, x, y);
  7341. };
  7342. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7343. if (!uniform)
  7344. return;
  7345. this._gl.uniform3f(uniform, x, y, z);
  7346. };
  7347. Engine.prototype.setBool = function (uniform, bool) {
  7348. if (!uniform)
  7349. return;
  7350. this._gl.uniform1i(uniform, bool);
  7351. };
  7352. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7353. if (!uniform)
  7354. return;
  7355. this._gl.uniform4f(uniform, x, y, z, w);
  7356. };
  7357. Engine.prototype.setColor3 = function (uniform, color3) {
  7358. if (!uniform)
  7359. return;
  7360. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7361. };
  7362. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7363. if (!uniform)
  7364. return;
  7365. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7366. };
  7367. // States
  7368. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7369. if (zOffset === void 0) { zOffset = 0; }
  7370. if (reverseSide === void 0) { reverseSide = false; }
  7371. // Culling
  7372. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7373. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7374. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7375. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7376. if (culling) {
  7377. this._depthCullingState.cullFace = cullFace;
  7378. this._depthCullingState.cull = true;
  7379. }
  7380. else {
  7381. this._depthCullingState.cull = false;
  7382. }
  7383. }
  7384. // Z offset
  7385. this._depthCullingState.zOffset = zOffset;
  7386. };
  7387. Engine.prototype.setDepthBuffer = function (enable) {
  7388. this._depthCullingState.depthTest = enable;
  7389. };
  7390. Engine.prototype.getDepthWrite = function () {
  7391. return this._depthCullingState.depthMask;
  7392. };
  7393. Engine.prototype.setDepthWrite = function (enable) {
  7394. this._depthCullingState.depthMask = enable;
  7395. };
  7396. Engine.prototype.setColorWrite = function (enable) {
  7397. this._gl.colorMask(enable, enable, enable, enable);
  7398. };
  7399. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7400. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7401. if (this._alphaMode === mode) {
  7402. return;
  7403. }
  7404. switch (mode) {
  7405. case Engine.ALPHA_DISABLE:
  7406. this._alphaState.alphaBlend = false;
  7407. break;
  7408. case Engine.ALPHA_COMBINE:
  7409. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7410. this._alphaState.alphaBlend = true;
  7411. break;
  7412. case Engine.ALPHA_ONEONE:
  7413. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7414. this._alphaState.alphaBlend = true;
  7415. break;
  7416. case Engine.ALPHA_ADD:
  7417. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7418. this._alphaState.alphaBlend = true;
  7419. break;
  7420. case Engine.ALPHA_SUBTRACT:
  7421. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7422. this._alphaState.alphaBlend = true;
  7423. break;
  7424. case Engine.ALPHA_MULTIPLY:
  7425. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7426. this._alphaState.alphaBlend = true;
  7427. break;
  7428. case Engine.ALPHA_MAXIMIZED:
  7429. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7430. this._alphaState.alphaBlend = true;
  7431. break;
  7432. }
  7433. if (!noDepthWriteChange) {
  7434. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7435. }
  7436. this._alphaMode = mode;
  7437. };
  7438. Engine.prototype.getAlphaMode = function () {
  7439. return this._alphaMode;
  7440. };
  7441. Engine.prototype.setAlphaTesting = function (enable) {
  7442. this._alphaTest = enable;
  7443. };
  7444. Engine.prototype.getAlphaTesting = function () {
  7445. return this._alphaTest;
  7446. };
  7447. // Textures
  7448. Engine.prototype.wipeCaches = function () {
  7449. this.resetTextureCache();
  7450. this._currentEffect = null;
  7451. this._stencilState.reset();
  7452. this._depthCullingState.reset();
  7453. this.setDepthFunctionToLessOrEqual();
  7454. this._alphaState.reset();
  7455. this._cachedVertexBuffers = null;
  7456. this._cachedIndexBuffer = null;
  7457. this._cachedEffectForVertexBuffers = null;
  7458. };
  7459. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7460. var gl = this._gl;
  7461. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7462. var magFilter = gl.NEAREST;
  7463. var minFilter = gl.NEAREST;
  7464. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7465. magFilter = gl.LINEAR;
  7466. minFilter = gl.LINEAR;
  7467. }
  7468. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7469. magFilter = gl.LINEAR;
  7470. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7471. }
  7472. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  7473. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  7474. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7475. texture.samplingMode = samplingMode;
  7476. };
  7477. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  7478. var _this = this;
  7479. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7480. if (onLoad === void 0) { onLoad = null; }
  7481. if (onError === void 0) { onError = null; }
  7482. if (buffer === void 0) { buffer = null; }
  7483. var texture = this._gl.createTexture();
  7484. var extension;
  7485. var fromData = false;
  7486. if (url.substr(0, 5) === "data:") {
  7487. fromData = true;
  7488. }
  7489. if (!fromData)
  7490. extension = url.substr(url.length - 4, 4).toLowerCase();
  7491. else {
  7492. var oldUrl = url;
  7493. fromData = oldUrl.split(':');
  7494. url = oldUrl;
  7495. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  7496. }
  7497. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7498. var isTGA = (extension === ".tga");
  7499. scene._addPendingData(texture);
  7500. texture.url = url;
  7501. texture.noMipmap = noMipmap;
  7502. texture.references = 1;
  7503. texture.samplingMode = samplingMode;
  7504. this._loadedTexturesCache.push(texture);
  7505. var onerror = function () {
  7506. scene._removePendingData(texture);
  7507. if (onError) {
  7508. onError();
  7509. }
  7510. };
  7511. var callback;
  7512. if (isTGA) {
  7513. callback = function (arrayBuffer) {
  7514. var data = new Uint8Array(arrayBuffer);
  7515. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  7516. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  7517. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  7518. }, onLoad, samplingMode);
  7519. };
  7520. if (!(fromData instanceof Array))
  7521. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  7522. callback(arrayBuffer);
  7523. }, onerror, scene.database, true);
  7524. else
  7525. callback(buffer);
  7526. }
  7527. else if (isDDS) {
  7528. callback = function (data) {
  7529. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7530. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  7531. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  7532. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  7533. }, onLoad, samplingMode);
  7534. };
  7535. if (!(fromData instanceof Array))
  7536. BABYLON.Tools.LoadFile(url, function (data) {
  7537. callback(data);
  7538. }, onerror, scene.database, true);
  7539. else
  7540. callback(buffer);
  7541. }
  7542. else {
  7543. var onload = function (img) {
  7544. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  7545. var isPot = (img.width === potWidth && img.height === potHeight);
  7546. if (!isPot) {
  7547. _this._prepareWorkingCanvas();
  7548. _this._workingCanvas.width = potWidth;
  7549. _this._workingCanvas.height = potHeight;
  7550. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7551. _this._workingContext.imageSmoothingEnabled = false;
  7552. _this._workingContext.mozImageSmoothingEnabled = false;
  7553. _this._workingContext.oImageSmoothingEnabled = false;
  7554. _this._workingContext.webkitImageSmoothingEnabled = false;
  7555. _this._workingContext.msImageSmoothingEnabled = false;
  7556. }
  7557. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  7558. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7559. _this._workingContext.imageSmoothingEnabled = true;
  7560. _this._workingContext.mozImageSmoothingEnabled = true;
  7561. _this._workingContext.oImageSmoothingEnabled = true;
  7562. _this._workingContext.webkitImageSmoothingEnabled = true;
  7563. _this._workingContext.msImageSmoothingEnabled = true;
  7564. }
  7565. }
  7566. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  7567. }, onLoad, samplingMode);
  7568. };
  7569. if (!(fromData instanceof Array))
  7570. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7571. else
  7572. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  7573. }
  7574. return texture;
  7575. };
  7576. Engine.prototype._getInternalFormat = function (format) {
  7577. var internalFormat = this._gl.RGBA;
  7578. switch (format) {
  7579. case Engine.TEXTUREFORMAT_ALPHA:
  7580. internalFormat = this._gl.ALPHA;
  7581. break;
  7582. case Engine.TEXTUREFORMAT_LUMINANCE:
  7583. internalFormat = this._gl.LUMINANCE;
  7584. break;
  7585. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  7586. internalFormat = this._gl.LUMINANCE_ALPHA;
  7587. break;
  7588. case Engine.TEXTUREFORMAT_RGB:
  7589. internalFormat = this._gl.RGB;
  7590. break;
  7591. case Engine.TEXTUREFORMAT_RGBA:
  7592. internalFormat = this._gl.RGBA;
  7593. break;
  7594. }
  7595. return internalFormat;
  7596. };
  7597. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  7598. if (compression === void 0) { compression = null; }
  7599. var internalFormat = this._getInternalFormat(format);
  7600. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7601. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7602. if (texture._width % 4 !== 0) {
  7603. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  7604. }
  7605. if (compression) {
  7606. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  7607. }
  7608. else {
  7609. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  7610. }
  7611. if (texture.generateMipMaps) {
  7612. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7613. }
  7614. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7615. this.resetTextureCache();
  7616. texture.isReady = true;
  7617. };
  7618. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  7619. if (compression === void 0) { compression = null; }
  7620. var texture = this._gl.createTexture();
  7621. texture._baseWidth = width;
  7622. texture._baseHeight = height;
  7623. texture._width = width;
  7624. texture._height = height;
  7625. texture.references = 1;
  7626. this.updateRawTexture(texture, data, format, invertY, compression);
  7627. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7628. // Filters
  7629. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  7630. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7631. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7632. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7633. texture.samplingMode = samplingMode;
  7634. this._loadedTexturesCache.push(texture);
  7635. return texture;
  7636. };
  7637. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  7638. var texture = this._gl.createTexture();
  7639. texture._baseWidth = width;
  7640. texture._baseHeight = height;
  7641. if (generateMipMaps) {
  7642. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  7643. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  7644. }
  7645. this.resetTextureCache();
  7646. texture._width = width;
  7647. texture._height = height;
  7648. texture.isReady = false;
  7649. texture.generateMipMaps = generateMipMaps;
  7650. texture.references = 1;
  7651. texture.samplingMode = samplingMode;
  7652. this.updateTextureSamplingMode(samplingMode, texture);
  7653. this._loadedTexturesCache.push(texture);
  7654. return texture;
  7655. };
  7656. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  7657. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  7658. if (texture.isCube) {
  7659. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  7660. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7661. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7662. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7663. }
  7664. else {
  7665. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7666. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7667. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7668. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7669. }
  7670. };
  7671. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  7672. if (premulAlpha === void 0) { premulAlpha = false; }
  7673. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7674. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  7675. if (premulAlpha) {
  7676. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  7677. }
  7678. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  7679. if (texture.generateMipMaps) {
  7680. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7681. }
  7682. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7683. this.resetTextureCache();
  7684. texture.isReady = true;
  7685. };
  7686. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  7687. if (texture._isDisabled) {
  7688. return;
  7689. }
  7690. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7691. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  7692. try {
  7693. // Testing video texture support
  7694. if (this._videoTextureSupported === undefined) {
  7695. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7696. if (this._gl.getError() !== 0) {
  7697. this._videoTextureSupported = false;
  7698. }
  7699. else {
  7700. this._videoTextureSupported = true;
  7701. }
  7702. }
  7703. // Copy video through the current working canvas if video texture is not supported
  7704. if (!this._videoTextureSupported) {
  7705. if (!texture._workingCanvas) {
  7706. texture._workingCanvas = document.createElement("canvas");
  7707. texture._workingContext = texture._workingCanvas.getContext("2d");
  7708. texture._workingCanvas.width = texture._width;
  7709. texture._workingCanvas.height = texture._height;
  7710. }
  7711. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  7712. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  7713. }
  7714. else {
  7715. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7716. }
  7717. if (texture.generateMipMaps) {
  7718. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7719. }
  7720. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7721. this.resetTextureCache();
  7722. texture.isReady = true;
  7723. }
  7724. catch (ex) {
  7725. // Something unexpected
  7726. // Let's disable the texture
  7727. texture._isDisabled = true;
  7728. }
  7729. };
  7730. Engine.prototype.createRenderTargetTexture = function (size, options) {
  7731. // old version had a "generateMipMaps" arg instead of options.
  7732. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  7733. // in the same way, generateDepthBuffer is defaulted to true
  7734. var generateMipMaps = false;
  7735. var generateDepthBuffer = true;
  7736. var generateStencilBuffer = false;
  7737. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7738. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7739. if (options !== undefined) {
  7740. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7741. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  7742. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  7743. type = options.type === undefined ? type : options.type;
  7744. if (options.samplingMode !== undefined) {
  7745. samplingMode = options.samplingMode;
  7746. }
  7747. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  7748. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  7749. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7750. }
  7751. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  7752. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  7753. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7754. }
  7755. }
  7756. var gl = this._gl;
  7757. var texture = gl.createTexture();
  7758. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7759. var width = size.width || size;
  7760. var height = size.height || size;
  7761. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7762. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  7763. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7764. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  7765. }
  7766. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7767. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7768. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7769. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7770. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  7771. var depthStencilBuffer;
  7772. // Create the depth/stencil buffer
  7773. if (generateStencilBuffer) {
  7774. depthStencilBuffer = gl.createRenderbuffer();
  7775. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  7776. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  7777. }
  7778. else if (generateDepthBuffer) {
  7779. depthStencilBuffer = gl.createRenderbuffer();
  7780. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  7781. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  7782. }
  7783. // Create the framebuffer
  7784. var framebuffer = gl.createFramebuffer();
  7785. this.bindUnboundFramebuffer(framebuffer);
  7786. // Manage attachments
  7787. if (generateStencilBuffer) {
  7788. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  7789. }
  7790. else if (generateDepthBuffer) {
  7791. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  7792. }
  7793. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  7794. if (generateMipMaps) {
  7795. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7796. }
  7797. // Unbind
  7798. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7799. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7800. this.bindUnboundFramebuffer(null);
  7801. texture._framebuffer = framebuffer;
  7802. if (generateDepthBuffer) {
  7803. texture._depthBuffer = depthStencilBuffer;
  7804. }
  7805. texture._baseWidth = width;
  7806. texture._baseHeight = height;
  7807. texture._width = width;
  7808. texture._height = height;
  7809. texture.isReady = true;
  7810. texture.generateMipMaps = generateMipMaps;
  7811. texture.references = 1;
  7812. texture.samplingMode = samplingMode;
  7813. texture.type = type;
  7814. this.resetTextureCache();
  7815. this._loadedTexturesCache.push(texture);
  7816. return texture;
  7817. };
  7818. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  7819. var gl = this._gl;
  7820. var texture = gl.createTexture();
  7821. var generateMipMaps = true;
  7822. var generateDepthBuffer = true;
  7823. var generateStencilBuffer = false;
  7824. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7825. if (options !== undefined) {
  7826. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7827. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  7828. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  7829. if (options.samplingMode !== undefined) {
  7830. samplingMode = options.samplingMode;
  7831. }
  7832. }
  7833. texture.isCube = true;
  7834. texture.references = 1;
  7835. texture.generateMipMaps = generateMipMaps;
  7836. texture.references = 1;
  7837. texture.samplingMode = samplingMode;
  7838. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7839. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7840. for (var face = 0; face < 6; face++) {
  7841. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  7842. }
  7843. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  7844. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  7845. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7846. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7847. // Create the depth buffer
  7848. var depthStencilBuffer;
  7849. // Create the depth/stencil buffer
  7850. if (generateStencilBuffer) {
  7851. depthStencilBuffer = gl.createRenderbuffer();
  7852. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  7853. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  7854. }
  7855. else if (generateDepthBuffer) {
  7856. depthStencilBuffer = gl.createRenderbuffer();
  7857. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  7858. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  7859. }
  7860. // Create the framebuffer
  7861. var framebuffer = gl.createFramebuffer();
  7862. this.bindUnboundFramebuffer(framebuffer);
  7863. // Manage attachments
  7864. if (generateStencilBuffer) {
  7865. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  7866. }
  7867. else if (generateDepthBuffer) {
  7868. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  7869. }
  7870. // Mipmaps
  7871. if (texture.generateMipMaps) {
  7872. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7873. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7874. }
  7875. // Unbind
  7876. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7877. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7878. this.bindUnboundFramebuffer(null);
  7879. texture._framebuffer = framebuffer;
  7880. if (generateDepthBuffer) {
  7881. texture._depthBuffer = depthStencilBuffer;
  7882. }
  7883. texture._width = size;
  7884. texture._height = size;
  7885. texture.isReady = true;
  7886. this.resetTextureCache();
  7887. this._loadedTexturesCache.push(texture);
  7888. return texture;
  7889. };
  7890. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  7891. var _this = this;
  7892. var gl = this._gl;
  7893. var texture = gl.createTexture();
  7894. texture.isCube = true;
  7895. texture.url = rootUrl;
  7896. texture.references = 1;
  7897. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  7898. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7899. if (isDDS) {
  7900. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  7901. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7902. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  7903. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7904. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  7905. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  7906. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  7907. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7908. }
  7909. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7910. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  7911. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7912. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7913. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7914. _this.resetTextureCache();
  7915. texture._width = info.width;
  7916. texture._height = info.height;
  7917. texture.isReady = true;
  7918. }, null, null, true);
  7919. }
  7920. else {
  7921. cascadeLoad(rootUrl, scene, function (imgs) {
  7922. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  7923. var height = width;
  7924. _this._prepareWorkingCanvas();
  7925. _this._workingCanvas.width = width;
  7926. _this._workingCanvas.height = height;
  7927. var faces = [
  7928. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7929. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7930. ];
  7931. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7932. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7933. for (var index = 0; index < faces.length; index++) {
  7934. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  7935. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  7936. }
  7937. if (!noMipmap) {
  7938. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7939. }
  7940. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7941. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7942. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7943. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7944. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7945. _this.resetTextureCache();
  7946. texture._width = width;
  7947. texture._height = height;
  7948. texture.isReady = true;
  7949. }, files);
  7950. }
  7951. return texture;
  7952. };
  7953. Engine.prototype.updateTextureSize = function (texture, width, height) {
  7954. texture._width = width;
  7955. texture._height = height;
  7956. texture._size = width * height;
  7957. texture._baseWidth = width;
  7958. texture._baseHeight = height;
  7959. };
  7960. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  7961. var _this = this;
  7962. var gl = this._gl;
  7963. var texture = gl.createTexture();
  7964. scene._addPendingData(texture);
  7965. texture.isCube = true;
  7966. texture.references = 1;
  7967. texture.url = url;
  7968. var internalFormat = this._getInternalFormat(format);
  7969. var textureType = gl.UNSIGNED_BYTE;
  7970. if (type === Engine.TEXTURETYPE_FLOAT) {
  7971. textureType = gl.FLOAT;
  7972. }
  7973. var width = size;
  7974. var height = width;
  7975. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7976. texture._width = width;
  7977. texture._height = height;
  7978. var onerror = function () {
  7979. scene._removePendingData(texture);
  7980. };
  7981. var internalCallback = function (data) {
  7982. var rgbeDataArrays = callback(data);
  7983. var facesIndex = [
  7984. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7985. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7986. ];
  7987. width = texture._width;
  7988. height = texture._height;
  7989. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7990. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7991. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7992. if (!noMipmap && isPot) {
  7993. if (mipmmapGenerator) {
  7994. var arrayTemp = [];
  7995. // Data are known to be in +X +Y +Z -X -Y -Z
  7996. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  7997. arrayTemp.push(rgbeDataArrays[0]); // +X
  7998. arrayTemp.push(rgbeDataArrays[3]); // -X
  7999. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8000. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8001. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8002. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8003. var mipData = mipmmapGenerator(arrayTemp);
  8004. for (var level = 0; level < mipData.length; level++) {
  8005. var mipSize = width >> level;
  8006. // mipData is order in +X -X +Y -Y +Z -Z
  8007. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  8008. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  8009. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  8010. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  8011. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  8012. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  8013. }
  8014. }
  8015. else {
  8016. // Data are known to be in +X +Y +Z -X -Y -Z
  8017. for (var index = 0; index < facesIndex.length; index++) {
  8018. var faceData = rgbeDataArrays[index];
  8019. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  8020. }
  8021. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8022. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  8023. // By following the webgl standard changes from Revision 7, 2014/11/24
  8024. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  8025. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  8026. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  8027. // Data are known to be in +X +Y +Z -X -Y -Z
  8028. for (var index = 0; index < facesIndex.length; index++) {
  8029. var faceData = rgbeDataArrays[index];
  8030. // Create a new RGBA Face.
  8031. var newFaceData = new Float32Array(width * height * 4);
  8032. for (var x = 0; x < width; x++) {
  8033. for (var y = 0; y < height; y++) {
  8034. var index_1 = (y * width + x) * 3;
  8035. var newIndex = (y * width + x) * 4;
  8036. // Map Old Value to new value.
  8037. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  8038. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  8039. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  8040. // Add fully opaque alpha channel.
  8041. newFaceData[newIndex + 3] = 1;
  8042. }
  8043. }
  8044. // Reupload the face.
  8045. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  8046. }
  8047. // Try to generate mipmap again.
  8048. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8049. }
  8050. }
  8051. }
  8052. else {
  8053. noMipmap = true;
  8054. }
  8055. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8056. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8057. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8058. }
  8059. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8060. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8061. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8062. }
  8063. else {
  8064. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8065. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8066. }
  8067. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8068. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8069. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8070. texture.isReady = true;
  8071. _this.resetTextureCache();
  8072. scene._removePendingData(texture);
  8073. };
  8074. BABYLON.Tools.LoadFile(url, function (data) {
  8075. internalCallback(data);
  8076. }, onerror, scene.database, true);
  8077. return texture;
  8078. };
  8079. ;
  8080. Engine.prototype._releaseTexture = function (texture) {
  8081. var gl = this._gl;
  8082. if (texture._framebuffer) {
  8083. gl.deleteFramebuffer(texture._framebuffer);
  8084. }
  8085. if (texture._depthBuffer) {
  8086. gl.deleteRenderbuffer(texture._depthBuffer);
  8087. }
  8088. gl.deleteTexture(texture);
  8089. // Unbind channels
  8090. this.unbindAllTextures();
  8091. var index = this._loadedTexturesCache.indexOf(texture);
  8092. if (index !== -1) {
  8093. this._loadedTexturesCache.splice(index, 1);
  8094. }
  8095. };
  8096. Engine.prototype.setProgram = function (program) {
  8097. if (this._currentProgram !== program) {
  8098. this._gl.useProgram(program);
  8099. this._currentProgram = program;
  8100. }
  8101. };
  8102. Engine.prototype.bindSamplers = function (effect) {
  8103. this.setProgram(effect.getProgram());
  8104. var samplers = effect.getSamplers();
  8105. for (var index = 0; index < samplers.length; index++) {
  8106. var uniform = effect.getUniform(samplers[index]);
  8107. this._gl.uniform1i(uniform, index);
  8108. }
  8109. this._currentEffect = null;
  8110. };
  8111. Engine.prototype.activateTexture = function (texture) {
  8112. if (this._activeTexture !== texture) {
  8113. this._gl.activeTexture(texture);
  8114. this._activeTexture = texture;
  8115. }
  8116. };
  8117. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8118. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8119. this._gl.bindTexture(target, texture);
  8120. this._activeTexturesCache[this._activeTexture] = texture;
  8121. }
  8122. };
  8123. Engine.prototype._bindTexture = function (channel, texture) {
  8124. if (channel < 0) {
  8125. return;
  8126. }
  8127. this.activateTexture(this._gl["TEXTURE" + channel]);
  8128. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8129. };
  8130. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8131. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8132. };
  8133. Engine.prototype.unbindAllTextures = function () {
  8134. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8135. this.activateTexture(this._gl["TEXTURE" + channel]);
  8136. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8137. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8138. }
  8139. };
  8140. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8141. if (channel < 0) {
  8142. return;
  8143. }
  8144. this._gl.uniform1i(uniform, channel);
  8145. this._setTexture(channel, texture);
  8146. };
  8147. Engine.prototype._setTexture = function (channel, texture) {
  8148. // Not ready?
  8149. if (!texture || !texture.isReady()) {
  8150. if (this._activeTexturesCache[channel] != null) {
  8151. this.activateTexture(this._gl["TEXTURE" + channel]);
  8152. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8153. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8154. }
  8155. return;
  8156. }
  8157. // Video
  8158. var alreadyActivated = false;
  8159. if (texture instanceof BABYLON.VideoTexture) {
  8160. this.activateTexture(this._gl["TEXTURE" + channel]);
  8161. alreadyActivated = true;
  8162. texture.update();
  8163. }
  8164. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8165. texture.delayLoad();
  8166. return;
  8167. }
  8168. var internalTexture = texture.getInternalTexture();
  8169. if (this._activeTexturesCache[channel] === internalTexture) {
  8170. return;
  8171. }
  8172. if (!alreadyActivated) {
  8173. this.activateTexture(this._gl["TEXTURE" + channel]);
  8174. }
  8175. if (internalTexture.isCube) {
  8176. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8177. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8178. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8179. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8180. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8181. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8182. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8183. }
  8184. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8185. }
  8186. else {
  8187. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8188. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8189. internalTexture._cachedWrapU = texture.wrapU;
  8190. switch (texture.wrapU) {
  8191. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8192. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8193. break;
  8194. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8195. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8196. break;
  8197. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8198. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8199. break;
  8200. }
  8201. }
  8202. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8203. internalTexture._cachedWrapV = texture.wrapV;
  8204. switch (texture.wrapV) {
  8205. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8206. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8207. break;
  8208. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8209. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8210. break;
  8211. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8212. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8213. break;
  8214. }
  8215. }
  8216. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8217. }
  8218. };
  8219. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8220. if (channel < 0) {
  8221. return;
  8222. }
  8223. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8224. this._textureUnits = new Int32Array(textures.length);
  8225. }
  8226. for (var i = 0; i < textures.length; i++) {
  8227. this._textureUnits[i] = channel + i;
  8228. }
  8229. this._gl.uniform1iv(uniform, this._textureUnits);
  8230. for (var index = 0; index < textures.length; index++) {
  8231. this._setTexture(channel + index, textures[index]);
  8232. }
  8233. };
  8234. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8235. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8236. var value = texture.anisotropicFilteringLevel;
  8237. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8238. value = 1;
  8239. }
  8240. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8241. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8242. texture._cachedAnisotropicFilteringLevel = value;
  8243. }
  8244. };
  8245. Engine.prototype.readPixels = function (x, y, width, height) {
  8246. var data = new Uint8Array(height * width * 4);
  8247. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8248. return data;
  8249. };
  8250. /**
  8251. * Add an externaly attached data from its key.
  8252. * This method call will fail and return false, if such key already exists.
  8253. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8254. * @param key the unique key that identifies the data
  8255. * @param data the data object to associate to the key for this Engine instance
  8256. * @return true if no such key were already present and the data was added successfully, false otherwise
  8257. */
  8258. Engine.prototype.addExternalData = function (key, data) {
  8259. return this._externalData.add(key, data);
  8260. };
  8261. /**
  8262. * Get an externaly attached data from its key
  8263. * @param key the unique key that identifies the data
  8264. * @return the associated data, if present (can be null), or undefined if not present
  8265. */
  8266. Engine.prototype.getExternalData = function (key) {
  8267. return this._externalData.get(key);
  8268. };
  8269. /**
  8270. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8271. * @param key the unique key that identifies the data
  8272. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8273. * @return the associated data, can be null if the factory returned null.
  8274. */
  8275. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8276. return this._externalData.getOrAddWithFactory(key, factory);
  8277. };
  8278. /**
  8279. * Remove an externaly attached data from the Engine instance
  8280. * @param key the unique key that identifies the data
  8281. * @return true if the data was successfully removed, false if it doesn't exist
  8282. */
  8283. Engine.prototype.removeExternalData = function (key) {
  8284. return this._externalData.remove(key);
  8285. };
  8286. Engine.prototype.releaseInternalTexture = function (texture) {
  8287. if (!texture) {
  8288. return;
  8289. }
  8290. texture.references--;
  8291. // Final reference ?
  8292. if (texture.references === 0) {
  8293. var texturesCache = this.getLoadedTexturesCache();
  8294. var index = texturesCache.indexOf(texture);
  8295. if (index > -1) {
  8296. texturesCache.splice(index, 1);
  8297. }
  8298. this._releaseTexture(texture);
  8299. }
  8300. };
  8301. // Dispose
  8302. Engine.prototype.dispose = function () {
  8303. this.hideLoadingUI();
  8304. this.stopRenderLoop();
  8305. // Release scenes
  8306. while (this.scenes.length) {
  8307. this.scenes[0].dispose();
  8308. }
  8309. // Release audio engine
  8310. Engine.audioEngine.dispose();
  8311. // Release effects
  8312. for (var name in this._compiledEffects) {
  8313. this._gl.deleteProgram(this._compiledEffects[name]._program);
  8314. }
  8315. // Unbind
  8316. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  8317. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  8318. continue;
  8319. }
  8320. this._gl.disableVertexAttribArray(i);
  8321. }
  8322. this._gl = null;
  8323. // Events
  8324. window.removeEventListener("blur", this._onBlur);
  8325. window.removeEventListener("focus", this._onFocus);
  8326. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  8327. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  8328. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  8329. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  8330. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  8331. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  8332. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  8333. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  8334. };
  8335. // Loading screen
  8336. Engine.prototype.displayLoadingUI = function () {
  8337. this._loadingScreen.displayLoadingUI();
  8338. };
  8339. Engine.prototype.hideLoadingUI = function () {
  8340. this._loadingScreen.hideLoadingUI();
  8341. };
  8342. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8343. get: function () {
  8344. return this._loadingScreen;
  8345. },
  8346. set: function (loadingScreen) {
  8347. this._loadingScreen = loadingScreen;
  8348. },
  8349. enumerable: true,
  8350. configurable: true
  8351. });
  8352. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8353. set: function (text) {
  8354. this._loadingScreen.loadingUIText = text;
  8355. },
  8356. enumerable: true,
  8357. configurable: true
  8358. });
  8359. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  8360. set: function (color) {
  8361. this._loadingScreen.loadingUIBackgroundColor = color;
  8362. },
  8363. enumerable: true,
  8364. configurable: true
  8365. });
  8366. Engine.prototype.attachContextLostEvent = function (callback) {
  8367. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  8368. };
  8369. Engine.prototype.attachContextRestoredEvent = function (callback) {
  8370. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  8371. };
  8372. // FPS
  8373. Engine.prototype.getFps = function () {
  8374. return this.fps;
  8375. };
  8376. Engine.prototype.getDeltaTime = function () {
  8377. return this.deltaTime;
  8378. };
  8379. Engine.prototype._measureFps = function () {
  8380. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8381. var length = this.previousFramesDuration.length;
  8382. if (length >= 2) {
  8383. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8384. }
  8385. if (length >= this.fpsRange) {
  8386. if (length > this.fpsRange) {
  8387. this.previousFramesDuration.splice(0, 1);
  8388. length = this.previousFramesDuration.length;
  8389. }
  8390. var sum = 0;
  8391. for (var id = 0; id < length - 1; id++) {
  8392. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8393. }
  8394. this.fps = 1000.0 / (sum / (length - 1));
  8395. }
  8396. };
  8397. Engine.prototype._canRenderToFloatTexture = function () {
  8398. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  8399. };
  8400. Engine.prototype._canRenderToHalfFloatTexture = function () {
  8401. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  8402. };
  8403. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  8404. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  8405. var tempcanvas = document.createElement("canvas");
  8406. tempcanvas.height = 16;
  8407. tempcanvas.width = 16;
  8408. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  8409. // extension.
  8410. var ext = gl.getExtension(extension);
  8411. if (!ext) {
  8412. return false;
  8413. }
  8414. // setup GLSL program
  8415. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  8416. 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 }";
  8417. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  8418. gl.useProgram(program);
  8419. // look up where the vertex data needs to go.
  8420. var positionLocation = gl.getAttribLocation(program, "a_position");
  8421. var colorLoc = gl.getUniformLocation(program, "u_color");
  8422. // provide texture coordinates for the rectangle.
  8423. var positionBuffer = gl.createBuffer();
  8424. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  8425. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  8426. -1.0, -1.0,
  8427. 1.0, -1.0,
  8428. -1.0, 1.0,
  8429. -1.0, 1.0,
  8430. 1.0, -1.0,
  8431. 1.0, 1.0]), gl.STATIC_DRAW);
  8432. gl.enableVertexAttribArray(positionLocation);
  8433. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  8434. var whiteTex = gl.createTexture();
  8435. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8436. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  8437. var tex = gl.createTexture();
  8438. gl.bindTexture(gl.TEXTURE_2D, tex);
  8439. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  8440. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8441. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8442. var fb = gl.createFramebuffer();
  8443. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  8444. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  8445. var cleanup = function () {
  8446. gl.deleteProgram(program);
  8447. gl.disableVertexAttribArray(positionLocation);
  8448. gl.deleteBuffer(positionBuffer);
  8449. gl.deleteFramebuffer(fb);
  8450. gl.deleteTexture(whiteTex);
  8451. gl.deleteTexture(tex);
  8452. };
  8453. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  8454. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  8455. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  8456. cleanup();
  8457. return false;
  8458. }
  8459. // Draw the rectangle.
  8460. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8461. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  8462. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8463. gl.bindTexture(gl.TEXTURE_2D, tex);
  8464. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  8465. gl.clearColor(1, 0, 0, 1);
  8466. gl.clear(gl.COLOR_BUFFER_BIT);
  8467. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  8468. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8469. var pixel = new Uint8Array(4);
  8470. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  8471. if (pixel[0] !== 0 ||
  8472. pixel[1] < 248 ||
  8473. pixel[2] < 248 ||
  8474. pixel[3] < 254) {
  8475. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  8476. cleanup();
  8477. return false;
  8478. }
  8479. // Succesfully rendered to "format" texture.
  8480. cleanup();
  8481. return true;
  8482. };
  8483. // Statics
  8484. Engine.isSupported = function () {
  8485. try {
  8486. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  8487. if (navigator.isCocoonJS) {
  8488. return true;
  8489. }
  8490. var tempcanvas = document.createElement("canvas");
  8491. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  8492. return gl != null && !!window.WebGLRenderingContext;
  8493. }
  8494. catch (e) {
  8495. return false;
  8496. }
  8497. };
  8498. // Const statics
  8499. Engine._ALPHA_DISABLE = 0;
  8500. Engine._ALPHA_ADD = 1;
  8501. Engine._ALPHA_COMBINE = 2;
  8502. Engine._ALPHA_SUBTRACT = 3;
  8503. Engine._ALPHA_MULTIPLY = 4;
  8504. Engine._ALPHA_MAXIMIZED = 5;
  8505. Engine._ALPHA_ONEONE = 6;
  8506. Engine._DELAYLOADSTATE_NONE = 0;
  8507. Engine._DELAYLOADSTATE_LOADED = 1;
  8508. Engine._DELAYLOADSTATE_LOADING = 2;
  8509. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  8510. Engine._TEXTUREFORMAT_ALPHA = 0;
  8511. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  8512. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  8513. Engine._TEXTUREFORMAT_RGB = 4;
  8514. Engine._TEXTUREFORMAT_RGBA = 5;
  8515. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  8516. Engine._TEXTURETYPE_FLOAT = 1;
  8517. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  8518. // Updatable statics so stick with vars here
  8519. Engine.CollisionsEpsilon = 0.001;
  8520. Engine.CodeRepository = "src/";
  8521. Engine.ShadersRepository = "src/Shaders/";
  8522. return Engine;
  8523. })();
  8524. BABYLON.Engine = Engine;
  8525. })(BABYLON || (BABYLON = {}));
  8526. var BABYLON;
  8527. (function (BABYLON) {
  8528. /**
  8529. * Node is the basic class for all scene objects (Mesh, Light Camera).
  8530. */
  8531. var Node = (function () {
  8532. /**
  8533. * @constructor
  8534. * @param {string} name - the name and id to be given to this node
  8535. * @param {BABYLON.Scene} the scene this node will be added to
  8536. */
  8537. function Node(name, scene) {
  8538. this.state = "";
  8539. this.animations = new Array();
  8540. this._ranges = {};
  8541. this._childrenFlag = -1;
  8542. this._isEnabled = true;
  8543. this._isReady = true;
  8544. this._currentRenderId = -1;
  8545. this._parentRenderId = -1;
  8546. this.name = name;
  8547. this.id = name;
  8548. this._scene = scene;
  8549. this._initCache();
  8550. }
  8551. Object.defineProperty(Node.prototype, "parent", {
  8552. get: function () {
  8553. return this._parentNode;
  8554. },
  8555. set: function (parent) {
  8556. if (this._parentNode === parent) {
  8557. return;
  8558. }
  8559. if (this._parentNode) {
  8560. var index = this._parentNode._children.indexOf(this);
  8561. if (index !== -1) {
  8562. this._parentNode._children.splice(index, 1);
  8563. }
  8564. }
  8565. this._parentNode = parent;
  8566. if (this._parentNode) {
  8567. if (!this._parentNode._children) {
  8568. this._parentNode._children = new Array();
  8569. }
  8570. this._parentNode._children.push(this);
  8571. }
  8572. },
  8573. enumerable: true,
  8574. configurable: true
  8575. });
  8576. Node.prototype.getScene = function () {
  8577. return this._scene;
  8578. };
  8579. Node.prototype.getEngine = function () {
  8580. return this._scene.getEngine();
  8581. };
  8582. // override it in derived class
  8583. Node.prototype.getWorldMatrix = function () {
  8584. return BABYLON.Matrix.Identity();
  8585. };
  8586. // override it in derived class if you add new variables to the cache
  8587. // and call the parent class method
  8588. Node.prototype._initCache = function () {
  8589. this._cache = {};
  8590. this._cache.parent = undefined;
  8591. };
  8592. Node.prototype.updateCache = function (force) {
  8593. if (!force && this.isSynchronized())
  8594. return;
  8595. this._cache.parent = this.parent;
  8596. this._updateCache();
  8597. };
  8598. // override it in derived class if you add new variables to the cache
  8599. // and call the parent class method if !ignoreParentClass
  8600. Node.prototype._updateCache = function (ignoreParentClass) {
  8601. };
  8602. // override it in derived class if you add new variables to the cache
  8603. Node.prototype._isSynchronized = function () {
  8604. return true;
  8605. };
  8606. Node.prototype._markSyncedWithParent = function () {
  8607. this._parentRenderId = this.parent._currentRenderId;
  8608. };
  8609. Node.prototype.isSynchronizedWithParent = function () {
  8610. if (!this.parent) {
  8611. return true;
  8612. }
  8613. if (this._parentRenderId !== this.parent._currentRenderId) {
  8614. return false;
  8615. }
  8616. return this.parent.isSynchronized();
  8617. };
  8618. Node.prototype.isSynchronized = function (updateCache) {
  8619. var check = this.hasNewParent();
  8620. check = check || !this.isSynchronizedWithParent();
  8621. check = check || !this._isSynchronized();
  8622. if (updateCache)
  8623. this.updateCache(true);
  8624. return !check;
  8625. };
  8626. Node.prototype.hasNewParent = function (update) {
  8627. if (this._cache.parent === this.parent)
  8628. return false;
  8629. if (update)
  8630. this._cache.parent = this.parent;
  8631. return true;
  8632. };
  8633. /**
  8634. * Is this node ready to be used/rendered
  8635. * @return {boolean} is it ready
  8636. */
  8637. Node.prototype.isReady = function () {
  8638. return this._isReady;
  8639. };
  8640. /**
  8641. * Is this node enabled.
  8642. * If the node has a parent and is enabled, the parent will be inspected as well.
  8643. * @return {boolean} whether this node (and its parent) is enabled.
  8644. * @see setEnabled
  8645. */
  8646. Node.prototype.isEnabled = function () {
  8647. if (!this._isEnabled) {
  8648. return false;
  8649. }
  8650. if (this.parent) {
  8651. return this.parent.isEnabled();
  8652. }
  8653. return true;
  8654. };
  8655. /**
  8656. * Set the enabled state of this node.
  8657. * @param {boolean} value - the new enabled state
  8658. * @see isEnabled
  8659. */
  8660. Node.prototype.setEnabled = function (value) {
  8661. this._isEnabled = value;
  8662. };
  8663. /**
  8664. * Is this node a descendant of the given node.
  8665. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  8666. * @param {BABYLON.Node} ancestor - The parent node to inspect
  8667. * @see parent
  8668. */
  8669. Node.prototype.isDescendantOf = function (ancestor) {
  8670. if (this.parent) {
  8671. if (this.parent === ancestor) {
  8672. return true;
  8673. }
  8674. return this.parent.isDescendantOf(ancestor);
  8675. }
  8676. return false;
  8677. };
  8678. /**
  8679. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  8680. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  8681. * @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.
  8682. * @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.
  8683. */
  8684. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  8685. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  8686. if (!this._children) {
  8687. return;
  8688. }
  8689. for (var index = 0; index < this._children.length; index++) {
  8690. var item = this._children[index];
  8691. if (!predicate || predicate(item)) {
  8692. results.push(item);
  8693. }
  8694. if (!directDescendantsOnly) {
  8695. item._getDescendants(results, false, predicate);
  8696. }
  8697. }
  8698. };
  8699. /**
  8700. * Will return all nodes that have this node as ascendant.
  8701. * @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.
  8702. * @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.
  8703. * @return {BABYLON.Node[]} all children nodes of all types.
  8704. */
  8705. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  8706. var results = [];
  8707. this._getDescendants(results, directDescendantsOnly, predicate);
  8708. return results;
  8709. };
  8710. /**
  8711. * @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.
  8712. * @Deprecated, legacy support.
  8713. * use getDecendants instead.
  8714. */
  8715. Node.prototype.getChildren = function (predicate) {
  8716. return this.getDescendants(true, predicate);
  8717. };
  8718. /**
  8719. * Get all child-meshes of this node.
  8720. */
  8721. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  8722. var results = [];
  8723. this._getDescendants(results, directDecendantsOnly, function (node) {
  8724. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  8725. });
  8726. return results;
  8727. };
  8728. Node.prototype._setReady = function (state) {
  8729. if (state === this._isReady) {
  8730. return;
  8731. }
  8732. if (!state) {
  8733. this._isReady = false;
  8734. return;
  8735. }
  8736. this._isReady = true;
  8737. if (this.onReady) {
  8738. this.onReady(this);
  8739. }
  8740. };
  8741. Node.prototype.getAnimationByName = function (name) {
  8742. for (var i = 0; i < this.animations.length; i++) {
  8743. var animation = this.animations[i];
  8744. if (animation.name === name) {
  8745. return animation;
  8746. }
  8747. }
  8748. return null;
  8749. };
  8750. Node.prototype.createAnimationRange = function (name, from, to) {
  8751. // check name not already in use
  8752. if (!this._ranges[name]) {
  8753. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  8754. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8755. if (this.animations[i]) {
  8756. this.animations[i].createRange(name, from, to);
  8757. }
  8758. }
  8759. }
  8760. };
  8761. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  8762. if (deleteFrames === void 0) { deleteFrames = true; }
  8763. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8764. if (this.animations[i]) {
  8765. this.animations[i].deleteRange(name, deleteFrames);
  8766. }
  8767. }
  8768. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  8769. };
  8770. Node.prototype.getAnimationRange = function (name) {
  8771. return this._ranges[name];
  8772. };
  8773. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  8774. var range = this.getAnimationRange(name);
  8775. if (!range) {
  8776. return null;
  8777. }
  8778. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  8779. };
  8780. Node.prototype.serializeAnimationRanges = function () {
  8781. var serializationRanges = [];
  8782. for (var name in this._ranges) {
  8783. var range = {};
  8784. range.name = name;
  8785. range.from = this._ranges[name].from;
  8786. range.to = this._ranges[name].to;
  8787. serializationRanges.push(range);
  8788. }
  8789. return serializationRanges;
  8790. };
  8791. Node.prototype.dispose = function () {
  8792. this.parent = null;
  8793. };
  8794. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  8795. if (parsedNode.ranges) {
  8796. for (var index = 0; index < parsedNode.ranges.length; index++) {
  8797. var data = parsedNode.ranges[index];
  8798. node.createAnimationRange(data.name, data.from, data.to);
  8799. }
  8800. }
  8801. };
  8802. __decorate([
  8803. BABYLON.serialize()
  8804. ], Node.prototype, "name", void 0);
  8805. __decorate([
  8806. BABYLON.serialize()
  8807. ], Node.prototype, "id", void 0);
  8808. __decorate([
  8809. BABYLON.serialize()
  8810. ], Node.prototype, "uniqueId", void 0);
  8811. __decorate([
  8812. BABYLON.serialize()
  8813. ], Node.prototype, "state", void 0);
  8814. return Node;
  8815. })();
  8816. BABYLON.Node = Node;
  8817. })(BABYLON || (BABYLON = {}));
  8818. var BABYLON;
  8819. (function (BABYLON) {
  8820. var FilesInput = (function () {
  8821. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  8822. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  8823. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  8824. this._engine = p_engine;
  8825. this._canvas = p_canvas;
  8826. this._currentScene = p_scene;
  8827. this._sceneLoadedCallback = p_sceneLoadedCallback;
  8828. this._progressCallback = p_progressCallback;
  8829. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  8830. this._textureLoadingCallback = p_textureLoadingCallback;
  8831. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  8832. }
  8833. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  8834. var _this = this;
  8835. if (p_elementToMonitor) {
  8836. this._elementToMonitor = p_elementToMonitor;
  8837. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  8838. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  8839. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  8840. }
  8841. };
  8842. FilesInput.prototype.renderFunction = function () {
  8843. if (this._additionnalRenderLoopLogicCallback) {
  8844. this._additionnalRenderLoopLogicCallback();
  8845. }
  8846. if (this._currentScene) {
  8847. if (this._textureLoadingCallback) {
  8848. var remaining = this._currentScene.getWaitingItemsCount();
  8849. if (remaining > 0) {
  8850. this._textureLoadingCallback(remaining);
  8851. }
  8852. }
  8853. this._currentScene.render();
  8854. }
  8855. };
  8856. FilesInput.prototype.drag = function (e) {
  8857. e.stopPropagation();
  8858. e.preventDefault();
  8859. };
  8860. FilesInput.prototype.drop = function (eventDrop) {
  8861. eventDrop.stopPropagation();
  8862. eventDrop.preventDefault();
  8863. this.loadFiles(eventDrop);
  8864. };
  8865. FilesInput.prototype.loadFiles = function (event) {
  8866. if (this._startingProcessingFilesCallback)
  8867. this._startingProcessingFilesCallback();
  8868. // Handling data transfer via drag'n'drop
  8869. if (event && event.dataTransfer && event.dataTransfer.files) {
  8870. this._filesToLoad = event.dataTransfer.files;
  8871. }
  8872. // Handling files from input files
  8873. if (event && event.target && event.target.files) {
  8874. this._filesToLoad = event.target.files;
  8875. }
  8876. if (this._filesToLoad && this._filesToLoad.length > 0) {
  8877. for (var i = 0; i < this._filesToLoad.length; i++) {
  8878. switch (this._filesToLoad[i].type) {
  8879. case "image/jpeg":
  8880. case "image/png":
  8881. case "image/bmp":
  8882. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8883. break;
  8884. case "image/targa":
  8885. case "image/vnd.ms-dds":
  8886. case "audio/wav":
  8887. case "audio/x-wav":
  8888. case "audio/mp3":
  8889. case "audio/mpeg":
  8890. case "audio/mpeg3":
  8891. case "audio/x-mpeg-3":
  8892. case "audio/ogg":
  8893. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8894. break;
  8895. default:
  8896. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  8897. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8898. }
  8899. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  8900. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  8901. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  8902. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  8903. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  8904. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  8905. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  8906. this._sceneFileToLoad = this._filesToLoad[i];
  8907. }
  8908. break;
  8909. }
  8910. }
  8911. this.reload();
  8912. }
  8913. };
  8914. FilesInput.prototype.reload = function () {
  8915. var _this = this;
  8916. var that = this;
  8917. // If a ".babylon" file has been provided
  8918. if (this._sceneFileToLoad) {
  8919. if (this._currentScene) {
  8920. if (BABYLON.Tools.errorsCount > 0) {
  8921. BABYLON.Tools.ClearLogCache();
  8922. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  8923. }
  8924. this._engine.stopRenderLoop();
  8925. this._currentScene.dispose();
  8926. }
  8927. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  8928. that._currentScene = newScene;
  8929. // Wait for textures and shaders to be ready
  8930. that._currentScene.executeWhenReady(function () {
  8931. // Attach camera to canvas inputs
  8932. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  8933. that._currentScene.createDefaultCameraOrLight();
  8934. }
  8935. that._currentScene.activeCamera.attachControl(that._canvas);
  8936. if (that._sceneLoadedCallback) {
  8937. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  8938. }
  8939. that._engine.runRenderLoop(function () { that.renderFunction(); });
  8940. });
  8941. }, function (progress) {
  8942. if (_this._progressCallback) {
  8943. _this._progressCallback(progress);
  8944. }
  8945. });
  8946. }
  8947. else {
  8948. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  8949. }
  8950. };
  8951. FilesInput.FilesTextures = new Array();
  8952. FilesInput.FilesToLoad = new Array();
  8953. return FilesInput;
  8954. })();
  8955. BABYLON.FilesInput = FilesInput;
  8956. })(BABYLON || (BABYLON = {}));
  8957. var BABYLON;
  8958. (function (BABYLON) {
  8959. var IntersectionInfo = (function () {
  8960. function IntersectionInfo(bu, bv, distance) {
  8961. this.bu = bu;
  8962. this.bv = bv;
  8963. this.distance = distance;
  8964. this.faceId = 0;
  8965. this.subMeshId = 0;
  8966. }
  8967. return IntersectionInfo;
  8968. })();
  8969. BABYLON.IntersectionInfo = IntersectionInfo;
  8970. var PickingInfo = (function () {
  8971. function PickingInfo() {
  8972. this.hit = false;
  8973. this.distance = 0;
  8974. this.pickedPoint = null;
  8975. this.pickedMesh = null;
  8976. this.bu = 0;
  8977. this.bv = 0;
  8978. this.faceId = -1;
  8979. this.subMeshId = 0;
  8980. this.pickedSprite = null;
  8981. }
  8982. // Methods
  8983. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  8984. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  8985. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  8986. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8987. return null;
  8988. }
  8989. var indices = this.pickedMesh.getIndices();
  8990. var result;
  8991. if (useVerticesNormals) {
  8992. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8993. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  8994. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  8995. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  8996. normal0 = normal0.scale(this.bu);
  8997. normal1 = normal1.scale(this.bv);
  8998. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  8999. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9000. }
  9001. else {
  9002. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9003. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9004. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9005. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9006. var p1p2 = vertex1.subtract(vertex2);
  9007. var p3p2 = vertex3.subtract(vertex2);
  9008. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9009. }
  9010. if (useWorldCoordinates) {
  9011. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9012. }
  9013. return BABYLON.Vector3.Normalize(result);
  9014. };
  9015. PickingInfo.prototype.getTextureCoordinates = function () {
  9016. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9017. return null;
  9018. }
  9019. var indices = this.pickedMesh.getIndices();
  9020. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9021. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9022. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9023. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9024. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9025. uv1 = uv1.scale(this.bu);
  9026. uv2 = uv2.scale(this.bv);
  9027. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9028. };
  9029. return PickingInfo;
  9030. })();
  9031. BABYLON.PickingInfo = PickingInfo;
  9032. })(BABYLON || (BABYLON = {}));
  9033. var BABYLON;
  9034. (function (BABYLON) {
  9035. var BoundingSphere = (function () {
  9036. function BoundingSphere(minimum, maximum) {
  9037. this.minimum = minimum;
  9038. this.maximum = maximum;
  9039. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9040. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9041. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9042. this.radius = distance * 0.5;
  9043. this.centerWorld = BABYLON.Vector3.Zero();
  9044. this._update(BABYLON.Matrix.Identity());
  9045. }
  9046. // Methods
  9047. BoundingSphere.prototype._update = function (world) {
  9048. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9049. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9050. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9051. };
  9052. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9053. for (var i = 0; i < 6; i++) {
  9054. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9055. return false;
  9056. }
  9057. return true;
  9058. };
  9059. BoundingSphere.prototype.intersectsPoint = function (point) {
  9060. var x = this.centerWorld.x - point.x;
  9061. var y = this.centerWorld.y - point.y;
  9062. var z = this.centerWorld.z - point.z;
  9063. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9064. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9065. return false;
  9066. return true;
  9067. };
  9068. // Statics
  9069. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9070. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9071. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9072. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9073. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9074. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9075. return false;
  9076. return true;
  9077. };
  9078. return BoundingSphere;
  9079. })();
  9080. BABYLON.BoundingSphere = BoundingSphere;
  9081. })(BABYLON || (BABYLON = {}));
  9082. var BABYLON;
  9083. (function (BABYLON) {
  9084. var BoundingBox = (function () {
  9085. function BoundingBox(minimum, maximum) {
  9086. this.minimum = minimum;
  9087. this.maximum = maximum;
  9088. this.vectors = new Array();
  9089. this.vectorsWorld = new Array();
  9090. // Bounding vectors
  9091. this.vectors.push(this.minimum.clone());
  9092. this.vectors.push(this.maximum.clone());
  9093. this.vectors.push(this.minimum.clone());
  9094. this.vectors[2].x = this.maximum.x;
  9095. this.vectors.push(this.minimum.clone());
  9096. this.vectors[3].y = this.maximum.y;
  9097. this.vectors.push(this.minimum.clone());
  9098. this.vectors[4].z = this.maximum.z;
  9099. this.vectors.push(this.maximum.clone());
  9100. this.vectors[5].z = this.minimum.z;
  9101. this.vectors.push(this.maximum.clone());
  9102. this.vectors[6].x = this.minimum.x;
  9103. this.vectors.push(this.maximum.clone());
  9104. this.vectors[7].y = this.minimum.y;
  9105. // OBB
  9106. this.center = this.maximum.add(this.minimum).scale(0.5);
  9107. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9108. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9109. // World
  9110. for (var index = 0; index < this.vectors.length; index++) {
  9111. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9112. }
  9113. this.minimumWorld = BABYLON.Vector3.Zero();
  9114. this.maximumWorld = BABYLON.Vector3.Zero();
  9115. this._update(BABYLON.Matrix.Identity());
  9116. }
  9117. // Methods
  9118. BoundingBox.prototype.getWorldMatrix = function () {
  9119. return this._worldMatrix;
  9120. };
  9121. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9122. this._worldMatrix.copyFrom(matrix);
  9123. return this;
  9124. };
  9125. BoundingBox.prototype._update = function (world) {
  9126. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9127. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9128. for (var index = 0; index < this.vectors.length; index++) {
  9129. var v = this.vectorsWorld[index];
  9130. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9131. if (v.x < this.minimumWorld.x)
  9132. this.minimumWorld.x = v.x;
  9133. if (v.y < this.minimumWorld.y)
  9134. this.minimumWorld.y = v.y;
  9135. if (v.z < this.minimumWorld.z)
  9136. this.minimumWorld.z = v.z;
  9137. if (v.x > this.maximumWorld.x)
  9138. this.maximumWorld.x = v.x;
  9139. if (v.y > this.maximumWorld.y)
  9140. this.maximumWorld.y = v.y;
  9141. if (v.z > this.maximumWorld.z)
  9142. this.maximumWorld.z = v.z;
  9143. }
  9144. // OBB
  9145. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9146. this.center.scaleInPlace(0.5);
  9147. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9148. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9149. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9150. this._worldMatrix = world;
  9151. };
  9152. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9153. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9154. };
  9155. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9156. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9157. };
  9158. BoundingBox.prototype.intersectsPoint = function (point) {
  9159. var delta = -BABYLON.Epsilon;
  9160. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9161. return false;
  9162. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9163. return false;
  9164. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9165. return false;
  9166. return true;
  9167. };
  9168. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9169. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9170. };
  9171. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9172. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9173. return false;
  9174. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9175. return false;
  9176. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9177. return false;
  9178. return true;
  9179. };
  9180. // Statics
  9181. BoundingBox.Intersects = function (box0, box1) {
  9182. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9183. return false;
  9184. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9185. return false;
  9186. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9187. return false;
  9188. return true;
  9189. };
  9190. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9191. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9192. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9193. return (num <= (sphereRadius * sphereRadius));
  9194. };
  9195. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9196. for (var p = 0; p < 6; p++) {
  9197. for (var i = 0; i < 8; i++) {
  9198. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9199. return false;
  9200. }
  9201. }
  9202. }
  9203. return true;
  9204. };
  9205. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9206. for (var p = 0; p < 6; p++) {
  9207. var inCount = 8;
  9208. for (var i = 0; i < 8; i++) {
  9209. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9210. --inCount;
  9211. }
  9212. else {
  9213. break;
  9214. }
  9215. }
  9216. if (inCount === 0)
  9217. return false;
  9218. }
  9219. return true;
  9220. };
  9221. return BoundingBox;
  9222. })();
  9223. BABYLON.BoundingBox = BoundingBox;
  9224. })(BABYLON || (BABYLON = {}));
  9225. var BABYLON;
  9226. (function (BABYLON) {
  9227. var computeBoxExtents = function (axis, box) {
  9228. var p = BABYLON.Vector3.Dot(box.center, axis);
  9229. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9230. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9231. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9232. var r = r0 + r1 + r2;
  9233. return {
  9234. min: p - r,
  9235. max: p + r
  9236. };
  9237. };
  9238. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  9239. var axisOverlap = function (axis, box0, box1) {
  9240. var result0 = computeBoxExtents(axis, box0);
  9241. var result1 = computeBoxExtents(axis, box1);
  9242. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  9243. };
  9244. var BoundingInfo = (function () {
  9245. function BoundingInfo(minimum, maximum) {
  9246. this.minimum = minimum;
  9247. this.maximum = maximum;
  9248. this._isLocked = false;
  9249. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  9250. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  9251. }
  9252. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  9253. get: function () {
  9254. return this._isLocked;
  9255. },
  9256. set: function (value) {
  9257. this._isLocked = value;
  9258. },
  9259. enumerable: true,
  9260. configurable: true
  9261. });
  9262. // Methods
  9263. BoundingInfo.prototype.update = function (world) {
  9264. if (this._isLocked) {
  9265. return;
  9266. }
  9267. this.boundingBox._update(world);
  9268. this.boundingSphere._update(world);
  9269. };
  9270. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  9271. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  9272. return false;
  9273. return this.boundingBox.isInFrustum(frustumPlanes);
  9274. };
  9275. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9276. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  9277. };
  9278. BoundingInfo.prototype._checkCollision = function (collider) {
  9279. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  9280. };
  9281. BoundingInfo.prototype.intersectsPoint = function (point) {
  9282. if (!this.boundingSphere.centerWorld) {
  9283. return false;
  9284. }
  9285. if (!this.boundingSphere.intersectsPoint(point)) {
  9286. return false;
  9287. }
  9288. if (!this.boundingBox.intersectsPoint(point)) {
  9289. return false;
  9290. }
  9291. return true;
  9292. };
  9293. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  9294. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  9295. return false;
  9296. }
  9297. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  9298. return false;
  9299. }
  9300. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  9301. return false;
  9302. }
  9303. if (!precise) {
  9304. return true;
  9305. }
  9306. var box0 = this.boundingBox;
  9307. var box1 = boundingInfo.boundingBox;
  9308. if (!axisOverlap(box0.directions[0], box0, box1))
  9309. return false;
  9310. if (!axisOverlap(box0.directions[1], box0, box1))
  9311. return false;
  9312. if (!axisOverlap(box0.directions[2], box0, box1))
  9313. return false;
  9314. if (!axisOverlap(box1.directions[0], box0, box1))
  9315. return false;
  9316. if (!axisOverlap(box1.directions[1], box0, box1))
  9317. return false;
  9318. if (!axisOverlap(box1.directions[2], box0, box1))
  9319. return false;
  9320. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  9321. return false;
  9322. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  9323. return false;
  9324. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  9325. return false;
  9326. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  9327. return false;
  9328. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  9329. return false;
  9330. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  9331. return false;
  9332. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  9333. return false;
  9334. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  9335. return false;
  9336. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  9337. return false;
  9338. return true;
  9339. };
  9340. return BoundingInfo;
  9341. })();
  9342. BABYLON.BoundingInfo = BoundingInfo;
  9343. })(BABYLON || (BABYLON = {}));
  9344. var BABYLON;
  9345. (function (BABYLON) {
  9346. var Ray = (function () {
  9347. function Ray(origin, direction, length) {
  9348. if (length === void 0) { length = Number.MAX_VALUE; }
  9349. this.origin = origin;
  9350. this.direction = direction;
  9351. this.length = length;
  9352. }
  9353. // Methods
  9354. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  9355. var d = 0.0;
  9356. var maxValue = Number.MAX_VALUE;
  9357. var inv;
  9358. var min;
  9359. var max;
  9360. var temp;
  9361. if (Math.abs(this.direction.x) < 0.0000001) {
  9362. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  9363. return false;
  9364. }
  9365. }
  9366. else {
  9367. inv = 1.0 / this.direction.x;
  9368. min = (minimum.x - this.origin.x) * inv;
  9369. max = (maximum.x - this.origin.x) * inv;
  9370. if (max === -Infinity) {
  9371. max = Infinity;
  9372. }
  9373. if (min > max) {
  9374. temp = min;
  9375. min = max;
  9376. max = temp;
  9377. }
  9378. d = Math.max(min, d);
  9379. maxValue = Math.min(max, maxValue);
  9380. if (d > maxValue) {
  9381. return false;
  9382. }
  9383. }
  9384. if (Math.abs(this.direction.y) < 0.0000001) {
  9385. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  9386. return false;
  9387. }
  9388. }
  9389. else {
  9390. inv = 1.0 / this.direction.y;
  9391. min = (minimum.y - this.origin.y) * inv;
  9392. max = (maximum.y - this.origin.y) * inv;
  9393. if (max === -Infinity) {
  9394. max = Infinity;
  9395. }
  9396. if (min > max) {
  9397. temp = min;
  9398. min = max;
  9399. max = temp;
  9400. }
  9401. d = Math.max(min, d);
  9402. maxValue = Math.min(max, maxValue);
  9403. if (d > maxValue) {
  9404. return false;
  9405. }
  9406. }
  9407. if (Math.abs(this.direction.z) < 0.0000001) {
  9408. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  9409. return false;
  9410. }
  9411. }
  9412. else {
  9413. inv = 1.0 / this.direction.z;
  9414. min = (minimum.z - this.origin.z) * inv;
  9415. max = (maximum.z - this.origin.z) * inv;
  9416. if (max === -Infinity) {
  9417. max = Infinity;
  9418. }
  9419. if (min > max) {
  9420. temp = min;
  9421. min = max;
  9422. max = temp;
  9423. }
  9424. d = Math.max(min, d);
  9425. maxValue = Math.min(max, maxValue);
  9426. if (d > maxValue) {
  9427. return false;
  9428. }
  9429. }
  9430. return true;
  9431. };
  9432. Ray.prototype.intersectsBox = function (box) {
  9433. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  9434. };
  9435. Ray.prototype.intersectsSphere = function (sphere) {
  9436. var x = sphere.center.x - this.origin.x;
  9437. var y = sphere.center.y - this.origin.y;
  9438. var z = sphere.center.z - this.origin.z;
  9439. var pyth = (x * x) + (y * y) + (z * z);
  9440. var rr = sphere.radius * sphere.radius;
  9441. if (pyth <= rr) {
  9442. return true;
  9443. }
  9444. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  9445. if (dot < 0.0) {
  9446. return false;
  9447. }
  9448. var temp = pyth - (dot * dot);
  9449. return temp <= rr;
  9450. };
  9451. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  9452. if (!this._edge1) {
  9453. this._edge1 = BABYLON.Vector3.Zero();
  9454. this._edge2 = BABYLON.Vector3.Zero();
  9455. this._pvec = BABYLON.Vector3.Zero();
  9456. this._tvec = BABYLON.Vector3.Zero();
  9457. this._qvec = BABYLON.Vector3.Zero();
  9458. }
  9459. vertex1.subtractToRef(vertex0, this._edge1);
  9460. vertex2.subtractToRef(vertex0, this._edge2);
  9461. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  9462. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  9463. if (det === 0) {
  9464. return null;
  9465. }
  9466. var invdet = 1 / det;
  9467. this.origin.subtractToRef(vertex0, this._tvec);
  9468. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  9469. if (bu < 0 || bu > 1.0) {
  9470. return null;
  9471. }
  9472. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  9473. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  9474. if (bv < 0 || bu + bv > 1.0) {
  9475. return null;
  9476. }
  9477. //check if the distance is longer than the predefined length.
  9478. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  9479. if (distance > this.length) {
  9480. return null;
  9481. }
  9482. return new BABYLON.IntersectionInfo(bu, bv, distance);
  9483. };
  9484. Ray.prototype.intersectsPlane = function (plane) {
  9485. var distance;
  9486. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  9487. if (Math.abs(result1) < 9.99999997475243E-07) {
  9488. return null;
  9489. }
  9490. else {
  9491. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  9492. distance = (-plane.d - result2) / result1;
  9493. if (distance < 0.0) {
  9494. if (distance < -9.99999997475243E-07) {
  9495. return null;
  9496. }
  9497. else {
  9498. return 0;
  9499. }
  9500. }
  9501. return distance;
  9502. }
  9503. };
  9504. /**
  9505. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  9506. * @param sega the first point of the segment to test the intersection against
  9507. * @param segb the second point of the segment to test the intersection against
  9508. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  9509. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  9510. */
  9511. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  9512. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  9513. var u = segb.subtract(sega);
  9514. var v = rsegb.subtract(this.origin);
  9515. var w = sega.subtract(this.origin);
  9516. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  9517. var b = BABYLON.Vector3.Dot(u, v);
  9518. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  9519. var d = BABYLON.Vector3.Dot(u, w);
  9520. var e = BABYLON.Vector3.Dot(v, w);
  9521. var D = a * c - b * b; // always >= 0
  9522. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  9523. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  9524. // compute the line parameters of the two closest points
  9525. if (D < Ray.smallnum) {
  9526. sN = 0.0; // force using point P0 on segment S1
  9527. sD = 1.0; // to prevent possible division by 0.0 later
  9528. tN = e;
  9529. tD = c;
  9530. }
  9531. else {
  9532. sN = (b * e - c * d);
  9533. tN = (a * e - b * d);
  9534. if (sN < 0.0) {
  9535. sN = 0.0;
  9536. tN = e;
  9537. tD = c;
  9538. }
  9539. else if (sN > sD) {
  9540. sN = sD;
  9541. tN = e + b;
  9542. tD = c;
  9543. }
  9544. }
  9545. if (tN < 0.0) {
  9546. tN = 0.0;
  9547. // recompute sc for this edge
  9548. if (-d < 0.0) {
  9549. sN = 0.0;
  9550. }
  9551. else if (-d > a)
  9552. sN = sD;
  9553. else {
  9554. sN = -d;
  9555. sD = a;
  9556. }
  9557. }
  9558. else if (tN > tD) {
  9559. tN = tD;
  9560. // recompute sc for this edge
  9561. if ((-d + b) < 0.0) {
  9562. sN = 0;
  9563. }
  9564. else if ((-d + b) > a) {
  9565. sN = sD;
  9566. }
  9567. else {
  9568. sN = (-d + b);
  9569. sD = a;
  9570. }
  9571. }
  9572. // finally do the division to get sc and tc
  9573. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  9574. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  9575. // get the difference of the two closest points
  9576. var qtc = v.multiplyByFloats(tc, tc, tc);
  9577. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  9578. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  9579. if (isIntersected) {
  9580. return qtc.length();
  9581. }
  9582. return -1;
  9583. };
  9584. // Statics
  9585. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  9586. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  9587. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  9588. var direction = end.subtract(start);
  9589. direction.normalize();
  9590. return new Ray(start, direction);
  9591. };
  9592. /**
  9593. * 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
  9594. * transformed to the given world matrix.
  9595. * @param origin The origin point
  9596. * @param end The end point
  9597. * @param world a matrix to transform the ray to. Default is the identity matrix.
  9598. */
  9599. Ray.CreateNewFromTo = function (origin, end, world) {
  9600. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  9601. var direction = end.subtract(origin);
  9602. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  9603. direction.normalize();
  9604. return Ray.Transform(new Ray(origin, direction, length), world);
  9605. };
  9606. Ray.Transform = function (ray, matrix) {
  9607. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  9608. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  9609. newDirection.normalize();
  9610. return new Ray(newOrigin, newDirection, ray.length);
  9611. };
  9612. Ray.smallnum = 0.00000001;
  9613. Ray.rayl = 10e8;
  9614. return Ray;
  9615. })();
  9616. BABYLON.Ray = Ray;
  9617. })(BABYLON || (BABYLON = {}));
  9618. var BABYLON;
  9619. (function (BABYLON) {
  9620. var AbstractMesh = (function (_super) {
  9621. __extends(AbstractMesh, _super);
  9622. // Constructor
  9623. function AbstractMesh(name, scene) {
  9624. var _this = this;
  9625. _super.call(this, name, scene);
  9626. // Events
  9627. /**
  9628. * An event triggered when the mesh is disposed.
  9629. * @type {BABYLON.Observable}
  9630. */
  9631. this.onDisposeObservable = new BABYLON.Observable();
  9632. /**
  9633. * An event triggered when this mesh collides with another one
  9634. * @type {BABYLON.Observable}
  9635. */
  9636. this.onCollideObservable = new BABYLON.Observable();
  9637. /**
  9638. * An event triggered when the collision's position changes
  9639. * @type {BABYLON.Observable}
  9640. */
  9641. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  9642. /**
  9643. * An event triggered after the world matrix is updated
  9644. * @type {BABYLON.Observable}
  9645. */
  9646. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  9647. // Properties
  9648. this.definedFacingForward = true; // orientation for POV movement & rotation
  9649. this.position = new BABYLON.Vector3(0, 0, 0);
  9650. this._rotation = new BABYLON.Vector3(0, 0, 0);
  9651. this._scaling = new BABYLON.Vector3(1, 1, 1);
  9652. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9653. this.visibility = 1.0;
  9654. this.alphaIndex = Number.MAX_VALUE;
  9655. this.infiniteDistance = false;
  9656. this.isVisible = true;
  9657. this.isPickable = true;
  9658. this.showBoundingBox = false;
  9659. this.showSubMeshesBoundingBox = false;
  9660. this.isBlocker = false;
  9661. this.renderingGroupId = 0;
  9662. this.receiveShadows = false;
  9663. this.renderOutline = false;
  9664. this.outlineColor = BABYLON.Color3.Red();
  9665. this.outlineWidth = 0.02;
  9666. this.renderOverlay = false;
  9667. this.overlayColor = BABYLON.Color3.Red();
  9668. this.overlayAlpha = 0.5;
  9669. this.hasVertexAlpha = false;
  9670. this.useVertexColors = true;
  9671. this.applyFog = true;
  9672. this.computeBonesUsingShaders = true;
  9673. this.scalingDeterminant = 1;
  9674. this.numBoneInfluencers = 4;
  9675. this.useOctreeForRenderingSelection = true;
  9676. this.useOctreeForPicking = true;
  9677. this.useOctreeForCollisions = true;
  9678. this.layerMask = 0x0FFFFFFF;
  9679. this.alwaysSelectAsActiveMesh = false;
  9680. // Collisions
  9681. this._checkCollisions = false;
  9682. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9683. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9684. this._collider = new BABYLON.Collider();
  9685. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9686. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9687. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9688. // Edges
  9689. this.edgesWidth = 1;
  9690. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  9691. // Cache
  9692. this._localWorld = BABYLON.Matrix.Zero();
  9693. this._worldMatrix = BABYLON.Matrix.Zero();
  9694. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9695. this._absolutePosition = BABYLON.Vector3.Zero();
  9696. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9697. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9698. this._isDirty = false;
  9699. this._pivotMatrix = BABYLON.Matrix.Identity();
  9700. this._isDisposed = false;
  9701. this._renderId = 0;
  9702. this._intersectionsInProgress = new Array();
  9703. this._isWorldMatrixFrozen = false;
  9704. this._unIndexed = false;
  9705. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  9706. if (collidedMesh === void 0) { collidedMesh = null; }
  9707. //TODO move this to the collision coordinator!
  9708. if (_this.getScene().workerCollisions)
  9709. newPosition.multiplyInPlace(_this._collider.radius);
  9710. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  9711. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9712. _this.position.addInPlace(_this._diffPositionForCollisions);
  9713. }
  9714. if (collidedMesh) {
  9715. _this.onCollideObservable.notifyObservers(collidedMesh);
  9716. }
  9717. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  9718. };
  9719. scene.addMesh(this);
  9720. }
  9721. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9722. get: function () {
  9723. return AbstractMesh._BILLBOARDMODE_NONE;
  9724. },
  9725. enumerable: true,
  9726. configurable: true
  9727. });
  9728. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9729. get: function () {
  9730. return AbstractMesh._BILLBOARDMODE_X;
  9731. },
  9732. enumerable: true,
  9733. configurable: true
  9734. });
  9735. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9736. get: function () {
  9737. return AbstractMesh._BILLBOARDMODE_Y;
  9738. },
  9739. enumerable: true,
  9740. configurable: true
  9741. });
  9742. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9743. get: function () {
  9744. return AbstractMesh._BILLBOARDMODE_Z;
  9745. },
  9746. enumerable: true,
  9747. configurable: true
  9748. });
  9749. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9750. get: function () {
  9751. return AbstractMesh._BILLBOARDMODE_ALL;
  9752. },
  9753. enumerable: true,
  9754. configurable: true
  9755. });
  9756. Object.defineProperty(AbstractMesh.prototype, "onDispose", {
  9757. set: function (callback) {
  9758. if (this._onDisposeObserver) {
  9759. this.onDisposeObservable.remove(this._onDisposeObserver);
  9760. }
  9761. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9762. },
  9763. enumerable: true,
  9764. configurable: true
  9765. });
  9766. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  9767. set: function (callback) {
  9768. if (this._onCollideObserver) {
  9769. this.onCollideObservable.remove(this._onCollideObserver);
  9770. }
  9771. this._onCollideObserver = this.onCollideObservable.add(callback);
  9772. },
  9773. enumerable: true,
  9774. configurable: true
  9775. });
  9776. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  9777. set: function (callback) {
  9778. if (this._onCollisionPositionChangeObserver) {
  9779. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  9780. }
  9781. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  9782. },
  9783. enumerable: true,
  9784. configurable: true
  9785. });
  9786. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  9787. get: function () {
  9788. return this._skeleton;
  9789. },
  9790. set: function (value) {
  9791. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  9792. this._skeleton._unregisterMeshWithPoseMatrix(this);
  9793. }
  9794. if (value && value.needInitialSkinMatrix) {
  9795. value._registerMeshWithPoseMatrix(this);
  9796. }
  9797. this._skeleton = value;
  9798. if (!this._skeleton) {
  9799. this._bonesTransformMatrices = null;
  9800. }
  9801. },
  9802. enumerable: true,
  9803. configurable: true
  9804. });
  9805. /**
  9806. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9807. */
  9808. AbstractMesh.prototype.toString = function (fullDetails) {
  9809. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  9810. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  9811. if (this._skeleton) {
  9812. ret += ", skeleton: " + this._skeleton.name;
  9813. }
  9814. if (fullDetails) {
  9815. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  9816. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  9817. }
  9818. return ret;
  9819. };
  9820. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  9821. /**
  9822. * Getting the rotation object.
  9823. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  9824. */
  9825. get: function () {
  9826. return this._rotation;
  9827. },
  9828. set: function (newRotation) {
  9829. this._rotation = newRotation;
  9830. },
  9831. enumerable: true,
  9832. configurable: true
  9833. });
  9834. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  9835. get: function () {
  9836. return this._scaling;
  9837. },
  9838. set: function (newScaling) {
  9839. this._scaling = newScaling;
  9840. if (this.physicsImpostor) {
  9841. this.physicsImpostor.forceUpdate();
  9842. }
  9843. },
  9844. enumerable: true,
  9845. configurable: true
  9846. });
  9847. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  9848. get: function () {
  9849. return this._rotationQuaternion;
  9850. },
  9851. set: function (quaternion) {
  9852. this._rotationQuaternion = quaternion;
  9853. //reset the rotation vector.
  9854. if (quaternion && this.rotation.length()) {
  9855. this.rotation.copyFromFloats(0, 0, 0);
  9856. }
  9857. },
  9858. enumerable: true,
  9859. configurable: true
  9860. });
  9861. // Methods
  9862. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  9863. this._poseMatrix.copyFrom(matrix);
  9864. };
  9865. AbstractMesh.prototype.getPoseMatrix = function () {
  9866. return this._poseMatrix;
  9867. };
  9868. AbstractMesh.prototype.disableEdgesRendering = function () {
  9869. if (this._edgesRenderer !== undefined) {
  9870. this._edgesRenderer.dispose();
  9871. this._edgesRenderer = undefined;
  9872. }
  9873. };
  9874. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  9875. if (epsilon === void 0) { epsilon = 0.95; }
  9876. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  9877. this.disableEdgesRendering();
  9878. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  9879. };
  9880. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9881. get: function () {
  9882. return false;
  9883. },
  9884. enumerable: true,
  9885. configurable: true
  9886. });
  9887. AbstractMesh.prototype.getLOD = function (camera) {
  9888. return this;
  9889. };
  9890. AbstractMesh.prototype.getTotalVertices = function () {
  9891. return 0;
  9892. };
  9893. AbstractMesh.prototype.getIndices = function () {
  9894. return null;
  9895. };
  9896. AbstractMesh.prototype.getVerticesData = function (kind) {
  9897. return null;
  9898. };
  9899. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9900. return false;
  9901. };
  9902. AbstractMesh.prototype.getBoundingInfo = function () {
  9903. if (this._masterMesh) {
  9904. return this._masterMesh.getBoundingInfo();
  9905. }
  9906. if (!this._boundingInfo) {
  9907. this._updateBoundingInfo();
  9908. }
  9909. return this._boundingInfo;
  9910. };
  9911. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  9912. this._boundingInfo = boundingInfo;
  9913. };
  9914. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9915. get: function () {
  9916. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9917. },
  9918. enumerable: true,
  9919. configurable: true
  9920. });
  9921. AbstractMesh.prototype._preActivate = function () {
  9922. };
  9923. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  9924. };
  9925. AbstractMesh.prototype._activate = function (renderId) {
  9926. this._renderId = renderId;
  9927. };
  9928. AbstractMesh.prototype.getWorldMatrix = function () {
  9929. if (this._masterMesh) {
  9930. return this._masterMesh.getWorldMatrix();
  9931. }
  9932. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9933. this.computeWorldMatrix();
  9934. }
  9935. return this._worldMatrix;
  9936. };
  9937. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9938. get: function () {
  9939. return this._worldMatrix;
  9940. },
  9941. enumerable: true,
  9942. configurable: true
  9943. });
  9944. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9945. get: function () {
  9946. return this._absolutePosition;
  9947. },
  9948. enumerable: true,
  9949. configurable: true
  9950. });
  9951. AbstractMesh.prototype.freezeWorldMatrix = function () {
  9952. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  9953. this.computeWorldMatrix(true);
  9954. this._isWorldMatrixFrozen = true;
  9955. };
  9956. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  9957. this._isWorldMatrixFrozen = false;
  9958. this.computeWorldMatrix(true);
  9959. };
  9960. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  9961. get: function () {
  9962. return this._isWorldMatrixFrozen;
  9963. },
  9964. enumerable: true,
  9965. configurable: true
  9966. });
  9967. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9968. axis.normalize();
  9969. if (!this.rotationQuaternion) {
  9970. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9971. this.rotation = BABYLON.Vector3.Zero();
  9972. }
  9973. var rotationQuaternion;
  9974. if (!space || space === BABYLON.Space.LOCAL) {
  9975. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  9976. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  9977. }
  9978. else {
  9979. if (this.parent) {
  9980. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9981. invertParentWorldMatrix.invert();
  9982. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9983. }
  9984. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  9985. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  9986. }
  9987. };
  9988. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9989. var displacementVector = axis.scale(distance);
  9990. if (!space || space === BABYLON.Space.LOCAL) {
  9991. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9992. this.setPositionWithLocalVector(tempV3);
  9993. }
  9994. else {
  9995. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9996. }
  9997. };
  9998. AbstractMesh.prototype.getAbsolutePosition = function () {
  9999. this.computeWorldMatrix();
  10000. return this._absolutePosition;
  10001. };
  10002. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10003. if (!absolutePosition) {
  10004. return;
  10005. }
  10006. var absolutePositionX;
  10007. var absolutePositionY;
  10008. var absolutePositionZ;
  10009. if (absolutePosition.x === undefined) {
  10010. if (arguments.length < 3) {
  10011. return;
  10012. }
  10013. absolutePositionX = arguments[0];
  10014. absolutePositionY = arguments[1];
  10015. absolutePositionZ = arguments[2];
  10016. }
  10017. else {
  10018. absolutePositionX = absolutePosition.x;
  10019. absolutePositionY = absolutePosition.y;
  10020. absolutePositionZ = absolutePosition.z;
  10021. }
  10022. if (this.parent) {
  10023. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10024. invertParentWorldMatrix.invert();
  10025. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10026. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10027. }
  10028. else {
  10029. this.position.x = absolutePositionX;
  10030. this.position.y = absolutePositionY;
  10031. this.position.z = absolutePositionZ;
  10032. }
  10033. };
  10034. // ================================== Point of View Movement =================================
  10035. /**
  10036. * Perform relative position change from the point of view of behind the front of the mesh.
  10037. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10038. * Supports definition of mesh facing forward or backward.
  10039. * @param {number} amountRight
  10040. * @param {number} amountUp
  10041. * @param {number} amountForward
  10042. */
  10043. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10044. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10045. };
  10046. /**
  10047. * Calculate relative position change from the point of view of behind the front of the mesh.
  10048. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10049. * Supports definition of mesh facing forward or backward.
  10050. * @param {number} amountRight
  10051. * @param {number} amountUp
  10052. * @param {number} amountForward
  10053. */
  10054. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10055. var rotMatrix = new BABYLON.Matrix();
  10056. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10057. rotQuaternion.toRotationMatrix(rotMatrix);
  10058. var translationDelta = BABYLON.Vector3.Zero();
  10059. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10060. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10061. return translationDelta;
  10062. };
  10063. // ================================== Point of View Rotation =================================
  10064. /**
  10065. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10066. * Supports definition of mesh facing forward or backward.
  10067. * @param {number} flipBack
  10068. * @param {number} twirlClockwise
  10069. * @param {number} tiltRight
  10070. */
  10071. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10072. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10073. };
  10074. /**
  10075. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10076. * Supports definition of mesh facing forward or backward.
  10077. * @param {number} flipBack
  10078. * @param {number} twirlClockwise
  10079. * @param {number} tiltRight
  10080. */
  10081. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10082. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10083. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10084. };
  10085. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10086. this._pivotMatrix = matrix;
  10087. this._cache.pivotMatrixUpdated = true;
  10088. };
  10089. AbstractMesh.prototype.getPivotMatrix = function () {
  10090. return this._pivotMatrix;
  10091. };
  10092. AbstractMesh.prototype._isSynchronized = function () {
  10093. if (this._isDirty) {
  10094. return false;
  10095. }
  10096. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10097. return false;
  10098. if (this._cache.pivotMatrixUpdated) {
  10099. return false;
  10100. }
  10101. if (this.infiniteDistance) {
  10102. return false;
  10103. }
  10104. if (!this._cache.position.equals(this.position))
  10105. return false;
  10106. if (this.rotationQuaternion) {
  10107. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10108. return false;
  10109. }
  10110. if (!this._cache.rotation.equals(this.rotation))
  10111. return false;
  10112. if (!this._cache.scaling.equals(this.scaling))
  10113. return false;
  10114. return true;
  10115. };
  10116. AbstractMesh.prototype._initCache = function () {
  10117. _super.prototype._initCache.call(this);
  10118. this._cache.localMatrixUpdated = false;
  10119. this._cache.position = BABYLON.Vector3.Zero();
  10120. this._cache.scaling = BABYLON.Vector3.Zero();
  10121. this._cache.rotation = BABYLON.Vector3.Zero();
  10122. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10123. this._cache.billboardMode = -1;
  10124. };
  10125. AbstractMesh.prototype.markAsDirty = function (property) {
  10126. if (property === "rotation") {
  10127. this.rotationQuaternion = null;
  10128. }
  10129. this._currentRenderId = Number.MAX_VALUE;
  10130. this._isDirty = true;
  10131. };
  10132. AbstractMesh.prototype._updateBoundingInfo = function () {
  10133. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10134. this._boundingInfo.update(this.worldMatrixFromCache);
  10135. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10136. };
  10137. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10138. if (!this.subMeshes) {
  10139. return;
  10140. }
  10141. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10142. var subMesh = this.subMeshes[subIndex];
  10143. if (!subMesh.IsGlobal) {
  10144. subMesh.updateBoundingInfo(matrix);
  10145. }
  10146. }
  10147. };
  10148. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10149. if (this._isWorldMatrixFrozen) {
  10150. return this._worldMatrix;
  10151. }
  10152. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10153. this._currentRenderId = this.getScene().getRenderId();
  10154. return this._worldMatrix;
  10155. }
  10156. this._cache.position.copyFrom(this.position);
  10157. this._cache.scaling.copyFrom(this.scaling);
  10158. this._cache.pivotMatrixUpdated = false;
  10159. this._cache.billboardMode = this.billboardMode;
  10160. this._currentRenderId = this.getScene().getRenderId();
  10161. this._isDirty = false;
  10162. // Scaling
  10163. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  10164. // Rotation
  10165. //rotate, if quaternion is set and rotation was used
  10166. if (this.rotationQuaternion) {
  10167. var len = this.rotation.length();
  10168. if (len) {
  10169. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  10170. this.rotation.copyFromFloats(0, 0, 0);
  10171. }
  10172. }
  10173. if (this.rotationQuaternion) {
  10174. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  10175. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10176. }
  10177. else {
  10178. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  10179. this._cache.rotation.copyFrom(this.rotation);
  10180. }
  10181. // Translation
  10182. if (this.infiniteDistance && !this.parent) {
  10183. var camera = this.getScene().activeCamera;
  10184. if (camera) {
  10185. var cameraWorldMatrix = camera.getWorldMatrix();
  10186. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10187. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  10188. }
  10189. }
  10190. else {
  10191. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  10192. }
  10193. // Composing transformations
  10194. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  10195. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  10196. // Billboarding
  10197. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10198. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  10199. var localPosition = BABYLON.Tmp.Vector3[0];
  10200. if (this.parent && this.parent.getWorldMatrix) {
  10201. this._markSyncedWithParent();
  10202. var parentMatrix;
  10203. if (this._meshToBoneReferal) {
  10204. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10205. parentMatrix = BABYLON.Tmp.Matrix[6];
  10206. }
  10207. else {
  10208. parentMatrix = this.parent.getWorldMatrix();
  10209. }
  10210. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  10211. localPosition = BABYLON.Tmp.Vector3[1];
  10212. }
  10213. var zero = this.getScene().activeCamera.globalPosition.clone();
  10214. if (this.parent && this.parent.position) {
  10215. localPosition.addInPlace(this.parent.position);
  10216. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  10217. }
  10218. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  10219. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10220. zero.x = localPosition.x + BABYLON.Epsilon;
  10221. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10222. zero.y = localPosition.y + BABYLON.Epsilon;
  10223. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10224. zero.z = localPosition.z + BABYLON.Epsilon;
  10225. }
  10226. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  10227. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  10228. BABYLON.Tmp.Matrix[3].invert();
  10229. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  10230. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  10231. }
  10232. // Local world
  10233. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  10234. // Parent
  10235. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10236. this._markSyncedWithParent();
  10237. if (this._meshToBoneReferal) {
  10238. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10239. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  10240. }
  10241. else {
  10242. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10243. }
  10244. }
  10245. else {
  10246. this._worldMatrix.copyFrom(this._localWorld);
  10247. }
  10248. // Bounding info
  10249. this._updateBoundingInfo();
  10250. // Absolute position
  10251. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10252. // Callbacks
  10253. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  10254. if (!this._poseMatrix) {
  10255. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  10256. }
  10257. return this._worldMatrix;
  10258. };
  10259. /**
  10260. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10261. * @param func: callback function to add
  10262. */
  10263. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10264. this.onAfterWorldMatrixUpdateObservable.add(func);
  10265. };
  10266. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10267. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  10268. };
  10269. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10270. this.computeWorldMatrix();
  10271. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10272. };
  10273. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10274. this.computeWorldMatrix();
  10275. var invLocalWorldMatrix = this._localWorld.clone();
  10276. invLocalWorldMatrix.invert();
  10277. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10278. };
  10279. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10280. this.computeWorldMatrix(true);
  10281. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10282. };
  10283. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  10284. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10285. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10286. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10287. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10288. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10289. /// <returns>Mesh oriented towards targetMesh</returns>
  10290. if (yawCor === void 0) { yawCor = 0; }
  10291. if (pitchCor === void 0) { pitchCor = 0; }
  10292. if (rollCor === void 0) { rollCor = 0; }
  10293. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  10294. var dv = AbstractMesh._lookAtVectorCache;
  10295. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  10296. targetPoint.subtractToRef(pos, dv);
  10297. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10298. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10299. var pitch = Math.atan2(dv.y, len);
  10300. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  10301. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  10302. };
  10303. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  10304. this._meshToBoneReferal = affectedMesh;
  10305. this.parent = bone;
  10306. if (bone.getWorldMatrix().determinant() < 0) {
  10307. this.scalingDeterminant *= -1;
  10308. }
  10309. };
  10310. AbstractMesh.prototype.detachFromBone = function () {
  10311. if (this.parent.getWorldMatrix().determinant() < 0) {
  10312. this.scalingDeterminant *= -1;
  10313. }
  10314. this._meshToBoneReferal = null;
  10315. this.parent = null;
  10316. };
  10317. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10318. return this._boundingInfo.isInFrustum(frustumPlanes);
  10319. };
  10320. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10321. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  10322. ;
  10323. };
  10324. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10325. if (!this._boundingInfo || !mesh._boundingInfo) {
  10326. return false;
  10327. }
  10328. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10329. };
  10330. AbstractMesh.prototype.intersectsPoint = function (point) {
  10331. if (!this._boundingInfo) {
  10332. return false;
  10333. }
  10334. return this._boundingInfo.intersectsPoint(point);
  10335. };
  10336. // Physics
  10337. /**
  10338. * @Deprecated. Use new PhysicsImpostor instead.
  10339. * */
  10340. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10341. //legacy support
  10342. if (impostor.impostor) {
  10343. options = impostor;
  10344. impostor = impostor.impostor;
  10345. }
  10346. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  10347. return this.physicsImpostor.physicsBody;
  10348. };
  10349. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10350. return this.physicsImpostor;
  10351. };
  10352. /**
  10353. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  10354. */
  10355. AbstractMesh.prototype.getPhysicsMass = function () {
  10356. return this.physicsImpostor.getParam("mass");
  10357. };
  10358. /**
  10359. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  10360. */
  10361. AbstractMesh.prototype.getPhysicsFriction = function () {
  10362. return this.physicsImpostor.getParam("friction");
  10363. };
  10364. /**
  10365. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  10366. */
  10367. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10368. return this.physicsImpostor.getParam("restitution");
  10369. };
  10370. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10371. if (!camera) {
  10372. camera = this.getScene().activeCamera;
  10373. }
  10374. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10375. };
  10376. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10377. if (!camera) {
  10378. camera = this.getScene().activeCamera;
  10379. }
  10380. return this.absolutePosition.subtract(camera.position).length();
  10381. };
  10382. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10383. if (!this.physicsImpostor) {
  10384. return;
  10385. }
  10386. this.physicsImpostor.applyImpulse(force, contactPoint);
  10387. };
  10388. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10389. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  10390. return;
  10391. }
  10392. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  10393. mainPivot: pivot1,
  10394. connectedPivot: pivot2,
  10395. nativeParams: options
  10396. });
  10397. };
  10398. /**
  10399. * @Deprecated
  10400. */
  10401. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10402. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  10403. this.updatePhysicsBody();
  10404. };
  10405. /**
  10406. * @Deprecated
  10407. * Calling this function is not needed anymore.
  10408. * The physics engine takes care of transofmration automatically.
  10409. */
  10410. AbstractMesh.prototype.updatePhysicsBody = function () {
  10411. //Unneeded
  10412. };
  10413. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  10414. // Collisions
  10415. get: function () {
  10416. return this._checkCollisions;
  10417. },
  10418. set: function (collisionEnabled) {
  10419. this._checkCollisions = collisionEnabled;
  10420. if (this.getScene().workerCollisions) {
  10421. this.getScene().collisionCoordinator.onMeshUpdated(this);
  10422. }
  10423. },
  10424. enumerable: true,
  10425. configurable: true
  10426. });
  10427. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10428. var globalPosition = this.getAbsolutePosition();
  10429. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10430. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10431. this._collider.radius = this.ellipsoid;
  10432. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  10433. };
  10434. // Submeshes octree
  10435. /**
  10436. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10437. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10438. */
  10439. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10440. if (maxCapacity === void 0) { maxCapacity = 64; }
  10441. if (maxDepth === void 0) { maxDepth = 2; }
  10442. if (!this._submeshesOctree) {
  10443. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10444. }
  10445. this.computeWorldMatrix(true);
  10446. // Update octree
  10447. var bbox = this.getBoundingInfo().boundingBox;
  10448. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10449. return this._submeshesOctree;
  10450. };
  10451. // Collisions
  10452. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10453. this._generatePointsArray();
  10454. // Transformation
  10455. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10456. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10457. subMesh._lastColliderWorldVertices = [];
  10458. subMesh._trianglePlanes = [];
  10459. var start = subMesh.verticesStart;
  10460. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10461. for (var i = start; i < end; i++) {
  10462. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10463. }
  10464. }
  10465. // Collide
  10466. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  10467. if (collider.collisionFound) {
  10468. collider.collidedMesh = this;
  10469. }
  10470. };
  10471. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10472. var subMeshes;
  10473. var len;
  10474. // Octrees
  10475. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10476. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10477. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10478. len = intersections.length;
  10479. subMeshes = intersections.data;
  10480. }
  10481. else {
  10482. subMeshes = this.subMeshes;
  10483. len = subMeshes.length;
  10484. }
  10485. for (var index = 0; index < len; index++) {
  10486. var subMesh = subMeshes[index];
  10487. // Bounding test
  10488. if (len > 1 && !subMesh._checkCollision(collider))
  10489. continue;
  10490. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10491. }
  10492. };
  10493. AbstractMesh.prototype._checkCollision = function (collider) {
  10494. // Bounding box test
  10495. if (!this._boundingInfo._checkCollision(collider))
  10496. return;
  10497. // Transformation matrix
  10498. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10499. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10500. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10501. };
  10502. // Picking
  10503. AbstractMesh.prototype._generatePointsArray = function () {
  10504. return false;
  10505. };
  10506. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10507. var pickingInfo = new BABYLON.PickingInfo();
  10508. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10509. return pickingInfo;
  10510. }
  10511. if (!this._generatePointsArray()) {
  10512. return pickingInfo;
  10513. }
  10514. var intersectInfo = null;
  10515. // Octrees
  10516. var subMeshes;
  10517. var len;
  10518. if (this._submeshesOctree && this.useOctreeForPicking) {
  10519. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10520. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10521. len = intersections.length;
  10522. subMeshes = intersections.data;
  10523. }
  10524. else {
  10525. subMeshes = this.subMeshes;
  10526. len = subMeshes.length;
  10527. }
  10528. for (var index = 0; index < len; index++) {
  10529. var subMesh = subMeshes[index];
  10530. // Bounding test
  10531. if (len > 1 && !subMesh.canIntersects(ray))
  10532. continue;
  10533. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10534. if (currentIntersectInfo) {
  10535. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10536. intersectInfo = currentIntersectInfo;
  10537. intersectInfo.subMeshId = index;
  10538. if (fastCheck) {
  10539. break;
  10540. }
  10541. }
  10542. }
  10543. }
  10544. if (intersectInfo) {
  10545. // Get picked point
  10546. var world = this.getWorldMatrix();
  10547. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10548. var direction = ray.direction.clone();
  10549. direction = direction.scale(intersectInfo.distance);
  10550. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10551. var pickedPoint = worldOrigin.add(worldDirection);
  10552. // Return result
  10553. pickingInfo.hit = true;
  10554. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10555. pickingInfo.pickedPoint = pickedPoint;
  10556. pickingInfo.pickedMesh = this;
  10557. pickingInfo.bu = intersectInfo.bu;
  10558. pickingInfo.bv = intersectInfo.bv;
  10559. pickingInfo.faceId = intersectInfo.faceId;
  10560. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10561. return pickingInfo;
  10562. }
  10563. return pickingInfo;
  10564. };
  10565. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10566. return null;
  10567. };
  10568. AbstractMesh.prototype.releaseSubMeshes = function () {
  10569. if (this.subMeshes) {
  10570. while (this.subMeshes.length) {
  10571. this.subMeshes[0].dispose();
  10572. }
  10573. }
  10574. else {
  10575. this.subMeshes = new Array();
  10576. }
  10577. };
  10578. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10579. var _this = this;
  10580. var index;
  10581. // Action manager
  10582. if (this.actionManager) {
  10583. this.actionManager.dispose();
  10584. this.actionManager = null;
  10585. }
  10586. // Skeleton
  10587. this.skeleton = null;
  10588. // Animations
  10589. this.getScene().stopAnimation(this);
  10590. // Physics
  10591. if (this.physicsImpostor) {
  10592. this.physicsImpostor.dispose();
  10593. }
  10594. // Intersections in progress
  10595. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10596. var other = this._intersectionsInProgress[index];
  10597. var pos = other._intersectionsInProgress.indexOf(this);
  10598. other._intersectionsInProgress.splice(pos, 1);
  10599. }
  10600. this._intersectionsInProgress = [];
  10601. // Lights
  10602. var lights = this.getScene().lights;
  10603. lights.forEach(function (light) {
  10604. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  10605. if (meshIndex !== -1) {
  10606. light.includedOnlyMeshes.splice(meshIndex, 1);
  10607. }
  10608. meshIndex = light.excludedMeshes.indexOf(_this);
  10609. if (meshIndex !== -1) {
  10610. light.excludedMeshes.splice(meshIndex, 1);
  10611. }
  10612. });
  10613. // Edges
  10614. if (this._edgesRenderer) {
  10615. this._edgesRenderer.dispose();
  10616. this._edgesRenderer = null;
  10617. }
  10618. // SubMeshes
  10619. this.releaseSubMeshes();
  10620. // Remove from scene
  10621. this.getScene().removeMesh(this);
  10622. if (!doNotRecurse) {
  10623. // Particles
  10624. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10625. if (this.getScene().particleSystems[index].emitter === this) {
  10626. this.getScene().particleSystems[index].dispose();
  10627. index--;
  10628. }
  10629. }
  10630. // Children
  10631. var objects = this.getDescendants(true);
  10632. for (index = 0; index < objects.length; index++) {
  10633. objects[index].dispose();
  10634. }
  10635. }
  10636. else {
  10637. var childMeshes = this.getChildMeshes(true);
  10638. for (index = 0; index < childMeshes.length; index++) {
  10639. var child = childMeshes[index];
  10640. child.parent = null;
  10641. child.computeWorldMatrix(true);
  10642. }
  10643. }
  10644. _super.prototype.dispose.call(this);
  10645. this.onAfterWorldMatrixUpdateObservable.clear();
  10646. this.onCollideObservable.clear();
  10647. this.onCollisionPositionChangeObservable.clear();
  10648. this._isDisposed = true;
  10649. // Callback
  10650. this.onDisposeObservable.notifyObservers(this);
  10651. this.onDisposeObservable.clear();
  10652. };
  10653. // Statics
  10654. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10655. AbstractMesh._BILLBOARDMODE_X = 1;
  10656. AbstractMesh._BILLBOARDMODE_Y = 2;
  10657. AbstractMesh._BILLBOARDMODE_Z = 4;
  10658. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10659. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  10660. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  10661. return AbstractMesh;
  10662. })(BABYLON.Node);
  10663. BABYLON.AbstractMesh = AbstractMesh;
  10664. })(BABYLON || (BABYLON = {}));
  10665. var BABYLON;
  10666. (function (BABYLON) {
  10667. var Light = (function (_super) {
  10668. __extends(Light, _super);
  10669. function Light(name, scene) {
  10670. _super.call(this, name, scene);
  10671. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  10672. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  10673. this.intensity = 1.0;
  10674. this.range = Number.MAX_VALUE;
  10675. this.includeOnlyWithLayerMask = 0;
  10676. this.includedOnlyMeshes = new Array();
  10677. this.excludedMeshes = new Array();
  10678. this.excludeWithLayerMask = 0;
  10679. // PBR Properties.
  10680. this.radius = 0.00001;
  10681. this._excludedMeshesIds = new Array();
  10682. this._includedOnlyMeshesIds = new Array();
  10683. scene.addLight(this);
  10684. }
  10685. /**
  10686. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10687. */
  10688. Light.prototype.toString = function (fullDetails) {
  10689. var ret = "Name: " + this.name;
  10690. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  10691. if (this.animations) {
  10692. for (var i = 0; i < this.animations.length; i++) {
  10693. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  10694. }
  10695. }
  10696. if (fullDetails) {
  10697. }
  10698. return ret;
  10699. };
  10700. Light.prototype.getShadowGenerator = function () {
  10701. return this._shadowGenerator;
  10702. };
  10703. Light.prototype.getAbsolutePosition = function () {
  10704. return BABYLON.Vector3.Zero();
  10705. };
  10706. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  10707. };
  10708. Light.prototype._getWorldMatrix = function () {
  10709. return BABYLON.Matrix.Identity();
  10710. };
  10711. Light.prototype.canAffectMesh = function (mesh) {
  10712. if (!mesh) {
  10713. return true;
  10714. }
  10715. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  10716. return false;
  10717. }
  10718. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  10719. return false;
  10720. }
  10721. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  10722. return false;
  10723. }
  10724. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  10725. return false;
  10726. }
  10727. return true;
  10728. };
  10729. Light.prototype.getWorldMatrix = function () {
  10730. this._currentRenderId = this.getScene().getRenderId();
  10731. var worldMatrix = this._getWorldMatrix();
  10732. if (this.parent && this.parent.getWorldMatrix) {
  10733. if (!this._parentedWorldMatrix) {
  10734. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  10735. }
  10736. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  10737. this._markSyncedWithParent();
  10738. return this._parentedWorldMatrix;
  10739. }
  10740. return worldMatrix;
  10741. };
  10742. Light.prototype.dispose = function () {
  10743. if (this._shadowGenerator) {
  10744. this._shadowGenerator.dispose();
  10745. this._shadowGenerator = null;
  10746. }
  10747. // Animations
  10748. this.getScene().stopAnimation(this);
  10749. // Remove from scene
  10750. this.getScene().removeLight(this);
  10751. _super.prototype.dispose.call(this);
  10752. };
  10753. Light.prototype.getTypeID = function () {
  10754. return 0;
  10755. };
  10756. Light.prototype.clone = function (name) {
  10757. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  10758. };
  10759. Light.prototype.serialize = function () {
  10760. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  10761. // Type
  10762. serializationObject.type = this.getTypeID();
  10763. // Parent
  10764. if (this.parent) {
  10765. serializationObject.parentId = this.parent.id;
  10766. }
  10767. // Inclusion / exclusions
  10768. if (this.excludedMeshes.length > 0) {
  10769. serializationObject.excludedMeshesIds = [];
  10770. this.excludedMeshes.forEach(function (mesh) {
  10771. serializationObject.excludedMeshesIds.push(mesh.id);
  10772. });
  10773. }
  10774. if (this.includedOnlyMeshes.length > 0) {
  10775. serializationObject.includedOnlyMeshesIds = [];
  10776. this.includedOnlyMeshes.forEach(function (mesh) {
  10777. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  10778. });
  10779. }
  10780. // Animations
  10781. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10782. serializationObject.ranges = this.serializeAnimationRanges();
  10783. return serializationObject;
  10784. };
  10785. Light.GetConstructorFromName = function (type, name, scene) {
  10786. switch (type) {
  10787. case 0:
  10788. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  10789. case 1:
  10790. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  10791. case 2:
  10792. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  10793. case 3:
  10794. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  10795. }
  10796. };
  10797. Light.Parse = function (parsedLight, scene) {
  10798. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  10799. // Inclusion / exclusions
  10800. if (parsedLight.excludedMeshesIds) {
  10801. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  10802. }
  10803. if (parsedLight.includedOnlyMeshesIds) {
  10804. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  10805. }
  10806. // Parent
  10807. if (parsedLight.parentId) {
  10808. light._waitingParentId = parsedLight.parentId;
  10809. }
  10810. // Animations
  10811. if (parsedLight.animations) {
  10812. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  10813. var parsedAnimation = parsedLight.animations[animationIndex];
  10814. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10815. }
  10816. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  10817. }
  10818. if (parsedLight.autoAnimate) {
  10819. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  10820. }
  10821. return light;
  10822. };
  10823. __decorate([
  10824. BABYLON.serializeAsColor3()
  10825. ], Light.prototype, "diffuse", void 0);
  10826. __decorate([
  10827. BABYLON.serializeAsColor3()
  10828. ], Light.prototype, "specular", void 0);
  10829. __decorate([
  10830. BABYLON.serialize()
  10831. ], Light.prototype, "intensity", void 0);
  10832. __decorate([
  10833. BABYLON.serialize()
  10834. ], Light.prototype, "range", void 0);
  10835. __decorate([
  10836. BABYLON.serialize()
  10837. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  10838. __decorate([
  10839. BABYLON.serialize()
  10840. ], Light.prototype, "excludeWithLayerMask", void 0);
  10841. __decorate([
  10842. BABYLON.serialize()
  10843. ], Light.prototype, "radius", void 0);
  10844. return Light;
  10845. })(BABYLON.Node);
  10846. BABYLON.Light = Light;
  10847. })(BABYLON || (BABYLON = {}));
  10848. var BABYLON;
  10849. (function (BABYLON) {
  10850. var PointLight = (function (_super) {
  10851. __extends(PointLight, _super);
  10852. function PointLight(name, position, scene) {
  10853. _super.call(this, name, scene);
  10854. this.position = position;
  10855. }
  10856. PointLight.prototype.getAbsolutePosition = function () {
  10857. return this.transformedPosition ? this.transformedPosition : this.position;
  10858. };
  10859. PointLight.prototype.computeTransformedPosition = function () {
  10860. if (this.parent && this.parent.getWorldMatrix) {
  10861. if (!this.transformedPosition) {
  10862. this.transformedPosition = BABYLON.Vector3.Zero();
  10863. }
  10864. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10865. return true;
  10866. }
  10867. return false;
  10868. };
  10869. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  10870. if (this.parent && this.parent.getWorldMatrix) {
  10871. this.computeTransformedPosition();
  10872. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  10873. return;
  10874. }
  10875. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  10876. };
  10877. PointLight.prototype.needCube = function () {
  10878. return true;
  10879. };
  10880. PointLight.prototype.supportsVSM = function () {
  10881. return false;
  10882. };
  10883. PointLight.prototype.needRefreshPerFrame = function () {
  10884. return false;
  10885. };
  10886. PointLight.prototype.getShadowDirection = function (faceIndex) {
  10887. switch (faceIndex) {
  10888. case 0:
  10889. return new BABYLON.Vector3(1, 0, 0);
  10890. case 1:
  10891. return new BABYLON.Vector3(-1, 0, 0);
  10892. case 2:
  10893. return new BABYLON.Vector3(0, -1, 0);
  10894. case 3:
  10895. return new BABYLON.Vector3(0, 1, 0);
  10896. case 4:
  10897. return new BABYLON.Vector3(0, 0, 1);
  10898. case 5:
  10899. return new BABYLON.Vector3(0, 0, -1);
  10900. }
  10901. return BABYLON.Vector3.Zero();
  10902. };
  10903. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10904. var activeCamera = this.getScene().activeCamera;
  10905. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  10906. };
  10907. PointLight.prototype._getWorldMatrix = function () {
  10908. if (!this._worldMatrix) {
  10909. this._worldMatrix = BABYLON.Matrix.Identity();
  10910. }
  10911. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10912. return this._worldMatrix;
  10913. };
  10914. PointLight.prototype.getTypeID = function () {
  10915. return 0;
  10916. };
  10917. __decorate([
  10918. BABYLON.serializeAsVector3()
  10919. ], PointLight.prototype, "position", void 0);
  10920. return PointLight;
  10921. })(BABYLON.Light);
  10922. BABYLON.PointLight = PointLight;
  10923. })(BABYLON || (BABYLON = {}));
  10924. var BABYLON;
  10925. (function (BABYLON) {
  10926. var SpotLight = (function (_super) {
  10927. __extends(SpotLight, _super);
  10928. function SpotLight(name, position, direction, angle, exponent, scene) {
  10929. _super.call(this, name, scene);
  10930. this.position = position;
  10931. this.direction = direction;
  10932. this.angle = angle;
  10933. this.exponent = exponent;
  10934. }
  10935. SpotLight.prototype.getAbsolutePosition = function () {
  10936. return this.transformedPosition ? this.transformedPosition : this.position;
  10937. };
  10938. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10939. var activeCamera = this.getScene().activeCamera;
  10940. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  10941. };
  10942. SpotLight.prototype.needCube = function () {
  10943. return false;
  10944. };
  10945. SpotLight.prototype.supportsVSM = function () {
  10946. return true;
  10947. };
  10948. SpotLight.prototype.needRefreshPerFrame = function () {
  10949. return false;
  10950. };
  10951. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  10952. return this.direction;
  10953. };
  10954. SpotLight.prototype.setDirectionToTarget = function (target) {
  10955. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  10956. return this.direction;
  10957. };
  10958. SpotLight.prototype.computeTransformedPosition = function () {
  10959. if (this.parent && this.parent.getWorldMatrix) {
  10960. if (!this.transformedPosition) {
  10961. this.transformedPosition = BABYLON.Vector3.Zero();
  10962. }
  10963. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10964. return true;
  10965. }
  10966. return false;
  10967. };
  10968. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  10969. var normalizeDirection;
  10970. if (this.parent && this.parent.getWorldMatrix) {
  10971. if (!this._transformedDirection) {
  10972. this._transformedDirection = BABYLON.Vector3.Zero();
  10973. }
  10974. this.computeTransformedPosition();
  10975. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  10976. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  10977. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  10978. }
  10979. else {
  10980. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  10981. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  10982. }
  10983. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  10984. };
  10985. SpotLight.prototype._getWorldMatrix = function () {
  10986. if (!this._worldMatrix) {
  10987. this._worldMatrix = BABYLON.Matrix.Identity();
  10988. }
  10989. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10990. return this._worldMatrix;
  10991. };
  10992. SpotLight.prototype.getTypeID = function () {
  10993. return 2;
  10994. };
  10995. __decorate([
  10996. BABYLON.serializeAsVector3()
  10997. ], SpotLight.prototype, "position", void 0);
  10998. __decorate([
  10999. BABYLON.serializeAsVector3()
  11000. ], SpotLight.prototype, "direction", void 0);
  11001. __decorate([
  11002. BABYLON.serialize()
  11003. ], SpotLight.prototype, "angle", void 0);
  11004. __decorate([
  11005. BABYLON.serialize()
  11006. ], SpotLight.prototype, "exponent", void 0);
  11007. return SpotLight;
  11008. })(BABYLON.Light);
  11009. BABYLON.SpotLight = SpotLight;
  11010. })(BABYLON || (BABYLON = {}));
  11011. var BABYLON;
  11012. (function (BABYLON) {
  11013. var HemisphericLight = (function (_super) {
  11014. __extends(HemisphericLight, _super);
  11015. function HemisphericLight(name, direction, scene) {
  11016. _super.call(this, name, scene);
  11017. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  11018. this.direction = direction;
  11019. }
  11020. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  11021. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  11022. return this.direction;
  11023. };
  11024. HemisphericLight.prototype.getShadowGenerator = function () {
  11025. return null;
  11026. };
  11027. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  11028. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11029. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  11030. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  11031. };
  11032. HemisphericLight.prototype._getWorldMatrix = function () {
  11033. if (!this._worldMatrix) {
  11034. this._worldMatrix = BABYLON.Matrix.Identity();
  11035. }
  11036. return this._worldMatrix;
  11037. };
  11038. HemisphericLight.prototype.getTypeID = function () {
  11039. return 3;
  11040. };
  11041. __decorate([
  11042. BABYLON.serializeAsColor3()
  11043. ], HemisphericLight.prototype, "groundColor", void 0);
  11044. __decorate([
  11045. BABYLON.serializeAsVector3()
  11046. ], HemisphericLight.prototype, "direction", void 0);
  11047. return HemisphericLight;
  11048. })(BABYLON.Light);
  11049. BABYLON.HemisphericLight = HemisphericLight;
  11050. })(BABYLON || (BABYLON = {}));
  11051. var BABYLON;
  11052. (function (BABYLON) {
  11053. var DirectionalLight = (function (_super) {
  11054. __extends(DirectionalLight, _super);
  11055. function DirectionalLight(name, direction, scene) {
  11056. _super.call(this, name, scene);
  11057. this.shadowOrthoScale = 0.5;
  11058. this.autoUpdateExtends = true;
  11059. // Cache
  11060. this._orthoLeft = Number.MAX_VALUE;
  11061. this._orthoRight = Number.MIN_VALUE;
  11062. this._orthoTop = Number.MIN_VALUE;
  11063. this._orthoBottom = Number.MAX_VALUE;
  11064. this.position = direction.scale(-1);
  11065. this.direction = direction;
  11066. }
  11067. DirectionalLight.prototype.getAbsolutePosition = function () {
  11068. return this.transformedPosition ? this.transformedPosition : this.position;
  11069. };
  11070. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  11071. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11072. return this.direction;
  11073. };
  11074. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11075. var activeCamera = this.getScene().activeCamera;
  11076. // Check extends
  11077. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  11078. var tempVector3 = BABYLON.Vector3.Zero();
  11079. this._orthoLeft = Number.MAX_VALUE;
  11080. this._orthoRight = Number.MIN_VALUE;
  11081. this._orthoTop = Number.MIN_VALUE;
  11082. this._orthoBottom = Number.MAX_VALUE;
  11083. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  11084. var mesh = renderList[meshIndex];
  11085. if (!mesh) {
  11086. continue;
  11087. }
  11088. var boundingInfo = mesh.getBoundingInfo();
  11089. if (!boundingInfo) {
  11090. continue;
  11091. }
  11092. var boundingBox = boundingInfo.boundingBox;
  11093. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  11094. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  11095. if (tempVector3.x < this._orthoLeft)
  11096. this._orthoLeft = tempVector3.x;
  11097. if (tempVector3.y < this._orthoBottom)
  11098. this._orthoBottom = tempVector3.y;
  11099. if (tempVector3.x > this._orthoRight)
  11100. this._orthoRight = tempVector3.x;
  11101. if (tempVector3.y > this._orthoTop)
  11102. this._orthoTop = tempVector3.y;
  11103. }
  11104. }
  11105. }
  11106. var xOffset = this._orthoRight - this._orthoLeft;
  11107. var yOffset = this._orthoTop - this._orthoBottom;
  11108. 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);
  11109. };
  11110. DirectionalLight.prototype.supportsVSM = function () {
  11111. return true;
  11112. };
  11113. DirectionalLight.prototype.needRefreshPerFrame = function () {
  11114. return true;
  11115. };
  11116. DirectionalLight.prototype.needCube = function () {
  11117. return false;
  11118. };
  11119. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  11120. return this.direction;
  11121. };
  11122. DirectionalLight.prototype.computeTransformedPosition = function () {
  11123. if (this.parent && this.parent.getWorldMatrix) {
  11124. if (!this.transformedPosition) {
  11125. this.transformedPosition = BABYLON.Vector3.Zero();
  11126. }
  11127. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11128. return true;
  11129. }
  11130. return false;
  11131. };
  11132. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  11133. if (this.parent && this.parent.getWorldMatrix) {
  11134. if (!this._transformedDirection) {
  11135. this._transformedDirection = BABYLON.Vector3.Zero();
  11136. }
  11137. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11138. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  11139. return;
  11140. }
  11141. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  11142. };
  11143. DirectionalLight.prototype._getWorldMatrix = function () {
  11144. if (!this._worldMatrix) {
  11145. this._worldMatrix = BABYLON.Matrix.Identity();
  11146. }
  11147. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11148. return this._worldMatrix;
  11149. };
  11150. DirectionalLight.prototype.getTypeID = function () {
  11151. return 1;
  11152. };
  11153. __decorate([
  11154. BABYLON.serializeAsVector3()
  11155. ], DirectionalLight.prototype, "position", void 0);
  11156. __decorate([
  11157. BABYLON.serializeAsVector3()
  11158. ], DirectionalLight.prototype, "direction", void 0);
  11159. __decorate([
  11160. BABYLON.serialize()
  11161. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  11162. __decorate([
  11163. BABYLON.serialize()
  11164. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  11165. return DirectionalLight;
  11166. })(BABYLON.Light);
  11167. BABYLON.DirectionalLight = DirectionalLight;
  11168. })(BABYLON || (BABYLON = {}));
  11169. var BABYLON;
  11170. (function (BABYLON) {
  11171. var ShadowGenerator = (function () {
  11172. function ShadowGenerator(mapSize, light) {
  11173. var _this = this;
  11174. // Members
  11175. this._filter = ShadowGenerator.FILTER_NONE;
  11176. this.blurScale = 2;
  11177. this._blurBoxOffset = 0;
  11178. this._bias = 0.00005;
  11179. this._lightDirection = BABYLON.Vector3.Zero();
  11180. this.forceBackFacesOnly = false;
  11181. this._darkness = 0;
  11182. this._transparencyShadow = false;
  11183. this._viewMatrix = BABYLON.Matrix.Zero();
  11184. this._projectionMatrix = BABYLON.Matrix.Zero();
  11185. this._transformMatrix = BABYLON.Matrix.Zero();
  11186. this._worldViewProjection = BABYLON.Matrix.Zero();
  11187. this._currentFaceIndex = 0;
  11188. this._currentFaceIndexCache = 0;
  11189. this._useFullFloat = true;
  11190. this._light = light;
  11191. this._scene = light.getScene();
  11192. this._mapSize = mapSize;
  11193. light._shadowGenerator = this;
  11194. // Texture type fallback from float to int if not supported.
  11195. var textureType;
  11196. var caps = this._scene.getEngine().getCaps();
  11197. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  11198. this._useFullFloat = true;
  11199. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  11200. }
  11201. else {
  11202. this._useFullFloat = false;
  11203. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  11204. }
  11205. // Render target
  11206. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  11207. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11208. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11209. this._shadowMap.anisotropicFilteringLevel = 1;
  11210. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11211. this._shadowMap.renderParticles = false;
  11212. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  11213. _this._currentFaceIndex = faceIndex;
  11214. });
  11215. this._shadowMap.onAfterUnbindObservable.add(function () {
  11216. if (!_this.useBlurVarianceShadowMap) {
  11217. return;
  11218. }
  11219. if (!_this._shadowMap2) {
  11220. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  11221. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11222. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11223. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  11224. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  11225. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  11226. effect.setTexture("textureSampler", _this._shadowMap);
  11227. });
  11228. _this.blurBoxOffset = 1;
  11229. }
  11230. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  11231. });
  11232. // Custom render function
  11233. var renderSubMesh = function (subMesh) {
  11234. var mesh = subMesh.getRenderingMesh();
  11235. var scene = _this._scene;
  11236. var engine = scene.getEngine();
  11237. // Culling
  11238. engine.setState(subMesh.getMaterial().backFaceCulling);
  11239. // Managing instances
  11240. var batch = mesh._getInstancesRenderList(subMesh._id);
  11241. if (batch.mustReturn) {
  11242. return;
  11243. }
  11244. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11245. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  11246. engine.enableEffect(_this._effect);
  11247. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  11248. var material = subMesh.getMaterial();
  11249. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  11250. _this._effect.setVector3("lightPosition", _this.getLight().position);
  11251. if (_this.getLight().needCube()) {
  11252. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  11253. }
  11254. // Alpha test
  11255. if (material && material.needAlphaTesting()) {
  11256. var alphaTexture = material.getAlphaTestTexture();
  11257. _this._effect.setTexture("diffuseSampler", alphaTexture);
  11258. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  11259. }
  11260. // Bones
  11261. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11262. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  11263. }
  11264. if (_this.forceBackFacesOnly) {
  11265. engine.setState(true, 0, false, true);
  11266. }
  11267. // Draw
  11268. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  11269. if (_this.forceBackFacesOnly) {
  11270. engine.setState(true, 0, false, false);
  11271. }
  11272. }
  11273. else {
  11274. // Need to reset refresh rate of the shadowMap
  11275. _this._shadowMap.resetRefreshCounter();
  11276. }
  11277. };
  11278. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  11279. var index;
  11280. for (index = 0; index < opaqueSubMeshes.length; index++) {
  11281. renderSubMesh(opaqueSubMeshes.data[index]);
  11282. }
  11283. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  11284. renderSubMesh(alphaTestSubMeshes.data[index]);
  11285. }
  11286. if (_this._transparencyShadow) {
  11287. for (index = 0; index < transparentSubMeshes.length; index++) {
  11288. renderSubMesh(transparentSubMeshes.data[index]);
  11289. }
  11290. }
  11291. };
  11292. this._shadowMap.onClearObservable.add(function (engine) {
  11293. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  11294. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  11295. }
  11296. else {
  11297. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  11298. }
  11299. });
  11300. }
  11301. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  11302. // Static
  11303. get: function () {
  11304. return ShadowGenerator._FILTER_NONE;
  11305. },
  11306. enumerable: true,
  11307. configurable: true
  11308. });
  11309. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  11310. get: function () {
  11311. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  11312. },
  11313. enumerable: true,
  11314. configurable: true
  11315. });
  11316. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  11317. get: function () {
  11318. return ShadowGenerator._FILTER_POISSONSAMPLING;
  11319. },
  11320. enumerable: true,
  11321. configurable: true
  11322. });
  11323. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  11324. get: function () {
  11325. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  11326. },
  11327. enumerable: true,
  11328. configurable: true
  11329. });
  11330. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  11331. get: function () {
  11332. return this._bias;
  11333. },
  11334. set: function (bias) {
  11335. this._bias = bias;
  11336. },
  11337. enumerable: true,
  11338. configurable: true
  11339. });
  11340. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  11341. get: function () {
  11342. return this._blurBoxOffset;
  11343. },
  11344. set: function (value) {
  11345. var _this = this;
  11346. if (this._blurBoxOffset === value) {
  11347. return;
  11348. }
  11349. this._blurBoxOffset = value;
  11350. if (this._boxBlurPostprocess) {
  11351. this._boxBlurPostprocess.dispose();
  11352. }
  11353. 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);
  11354. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  11355. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  11356. });
  11357. },
  11358. enumerable: true,
  11359. configurable: true
  11360. });
  11361. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  11362. get: function () {
  11363. return this._filter;
  11364. },
  11365. set: function (value) {
  11366. if (this._filter === value) {
  11367. return;
  11368. }
  11369. this._filter = value;
  11370. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  11371. this._shadowMap.anisotropicFilteringLevel = 16;
  11372. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  11373. }
  11374. else {
  11375. this._shadowMap.anisotropicFilteringLevel = 1;
  11376. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11377. }
  11378. },
  11379. enumerable: true,
  11380. configurable: true
  11381. });
  11382. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  11383. get: function () {
  11384. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  11385. },
  11386. set: function (value) {
  11387. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11388. },
  11389. enumerable: true,
  11390. configurable: true
  11391. });
  11392. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  11393. get: function () {
  11394. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  11395. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  11396. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  11397. },
  11398. set: function (value) {
  11399. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  11400. },
  11401. enumerable: true,
  11402. configurable: true
  11403. });
  11404. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  11405. get: function () {
  11406. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  11407. },
  11408. set: function (value) {
  11409. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11410. },
  11411. enumerable: true,
  11412. configurable: true
  11413. });
  11414. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  11415. var defines = [];
  11416. if (this._useFullFloat) {
  11417. defines.push("#define FULLFLOAT");
  11418. }
  11419. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  11420. defines.push("#define VSM");
  11421. }
  11422. if (this.getLight().needCube()) {
  11423. defines.push("#define CUBEMAP");
  11424. }
  11425. var attribs = [BABYLON.VertexBuffer.PositionKind];
  11426. var mesh = subMesh.getMesh();
  11427. var material = subMesh.getMaterial();
  11428. // Alpha test
  11429. if (material && material.needAlphaTesting()) {
  11430. defines.push("#define ALPHATEST");
  11431. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11432. attribs.push(BABYLON.VertexBuffer.UVKind);
  11433. defines.push("#define UV1");
  11434. }
  11435. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  11436. var alphaTexture = material.getAlphaTestTexture();
  11437. if (alphaTexture.coordinatesIndex === 1) {
  11438. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  11439. defines.push("#define UV2");
  11440. }
  11441. }
  11442. }
  11443. // Bones
  11444. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11445. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  11446. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  11447. if (mesh.numBoneInfluencers > 4) {
  11448. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  11449. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  11450. }
  11451. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  11452. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  11453. }
  11454. else {
  11455. defines.push("#define NUM_BONE_INFLUENCERS 0");
  11456. }
  11457. // Instances
  11458. if (useInstances) {
  11459. defines.push("#define INSTANCES");
  11460. attribs.push("world0");
  11461. attribs.push("world1");
  11462. attribs.push("world2");
  11463. attribs.push("world3");
  11464. }
  11465. // Get correct effect
  11466. var join = defines.join("\n");
  11467. if (this._cachedDefines !== join) {
  11468. this._cachedDefines = join;
  11469. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  11470. }
  11471. return this._effect.isReady();
  11472. };
  11473. ShadowGenerator.prototype.getShadowMap = function () {
  11474. return this._shadowMap;
  11475. };
  11476. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  11477. if (this._shadowMap2) {
  11478. return this._shadowMap2;
  11479. }
  11480. return this._shadowMap;
  11481. };
  11482. ShadowGenerator.prototype.getLight = function () {
  11483. return this._light;
  11484. };
  11485. // Methods
  11486. ShadowGenerator.prototype.getTransformMatrix = function () {
  11487. var scene = this._scene;
  11488. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  11489. return this._transformMatrix;
  11490. }
  11491. this._currentRenderID = scene.getRenderId();
  11492. this._currentFaceIndexCache = this._currentFaceIndex;
  11493. var lightPosition = this._light.position;
  11494. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  11495. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  11496. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  11497. }
  11498. if (this._light.computeTransformedPosition()) {
  11499. lightPosition = this._light.transformedPosition;
  11500. }
  11501. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  11502. this._cachedPosition = lightPosition.clone();
  11503. this._cachedDirection = this._lightDirection.clone();
  11504. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  11505. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  11506. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  11507. }
  11508. return this._transformMatrix;
  11509. };
  11510. ShadowGenerator.prototype.getDarkness = function () {
  11511. return this._darkness;
  11512. };
  11513. ShadowGenerator.prototype.setDarkness = function (darkness) {
  11514. if (darkness >= 1.0)
  11515. this._darkness = 1.0;
  11516. else if (darkness <= 0.0)
  11517. this._darkness = 0.0;
  11518. else
  11519. this._darkness = darkness;
  11520. };
  11521. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  11522. this._transparencyShadow = hasShadow;
  11523. };
  11524. ShadowGenerator.prototype._packHalf = function (depth) {
  11525. var scale = depth * 255.0;
  11526. var fract = scale - Math.floor(scale);
  11527. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  11528. };
  11529. ShadowGenerator.prototype.dispose = function () {
  11530. this._shadowMap.dispose();
  11531. if (this._shadowMap2) {
  11532. this._shadowMap2.dispose();
  11533. }
  11534. if (this._downSamplePostprocess) {
  11535. this._downSamplePostprocess.dispose();
  11536. }
  11537. if (this._boxBlurPostprocess) {
  11538. this._boxBlurPostprocess.dispose();
  11539. }
  11540. };
  11541. ShadowGenerator.prototype.serialize = function () {
  11542. var serializationObject = {};
  11543. serializationObject.lightId = this._light.id;
  11544. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  11545. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  11546. serializationObject.usePoissonSampling = this.usePoissonSampling;
  11547. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  11548. serializationObject.renderList = [];
  11549. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  11550. var mesh = this.getShadowMap().renderList[meshIndex];
  11551. serializationObject.renderList.push(mesh.id);
  11552. }
  11553. return serializationObject;
  11554. };
  11555. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  11556. //casting to point light, as light is missing the position attr and typescript complains.
  11557. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  11558. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  11559. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  11560. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  11561. meshes.forEach(function (mesh) {
  11562. shadowGenerator.getShadowMap().renderList.push(mesh);
  11563. });
  11564. }
  11565. if (parsedShadowGenerator.usePoissonSampling) {
  11566. shadowGenerator.usePoissonSampling = true;
  11567. }
  11568. else if (parsedShadowGenerator.useVarianceShadowMap) {
  11569. shadowGenerator.useVarianceShadowMap = true;
  11570. }
  11571. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  11572. shadowGenerator.useBlurVarianceShadowMap = true;
  11573. if (parsedShadowGenerator.blurScale) {
  11574. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  11575. }
  11576. if (parsedShadowGenerator.blurBoxOffset) {
  11577. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  11578. }
  11579. }
  11580. if (parsedShadowGenerator.bias !== undefined) {
  11581. shadowGenerator.bias = parsedShadowGenerator.bias;
  11582. }
  11583. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  11584. return shadowGenerator;
  11585. };
  11586. ShadowGenerator._FILTER_NONE = 0;
  11587. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  11588. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  11589. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  11590. return ShadowGenerator;
  11591. })();
  11592. BABYLON.ShadowGenerator = ShadowGenerator;
  11593. })(BABYLON || (BABYLON = {}));
  11594. var BABYLON;
  11595. (function (BABYLON) {
  11596. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  11597. if (boxMin.x > sphereCenter.x + sphereRadius)
  11598. return false;
  11599. if (sphereCenter.x - sphereRadius > boxMax.x)
  11600. return false;
  11601. if (boxMin.y > sphereCenter.y + sphereRadius)
  11602. return false;
  11603. if (sphereCenter.y - sphereRadius > boxMax.y)
  11604. return false;
  11605. if (boxMin.z > sphereCenter.z + sphereRadius)
  11606. return false;
  11607. if (sphereCenter.z - sphereRadius > boxMax.z)
  11608. return false;
  11609. return true;
  11610. };
  11611. var getLowestRoot = (function () {
  11612. var result = { root: 0, found: false };
  11613. return function (a, b, c, maxR) {
  11614. result.root = 0;
  11615. result.found = false;
  11616. var determinant = b * b - 4.0 * a * c;
  11617. if (determinant < 0)
  11618. return result;
  11619. var sqrtD = Math.sqrt(determinant);
  11620. var r1 = (-b - sqrtD) / (2.0 * a);
  11621. var r2 = (-b + sqrtD) / (2.0 * a);
  11622. if (r1 > r2) {
  11623. var temp = r2;
  11624. r2 = r1;
  11625. r1 = temp;
  11626. }
  11627. if (r1 > 0 && r1 < maxR) {
  11628. result.root = r1;
  11629. result.found = true;
  11630. return result;
  11631. }
  11632. if (r2 > 0 && r2 < maxR) {
  11633. result.root = r2;
  11634. result.found = true;
  11635. return result;
  11636. }
  11637. return result;
  11638. };
  11639. })();
  11640. var Collider = (function () {
  11641. function Collider() {
  11642. this.radius = new BABYLON.Vector3(1, 1, 1);
  11643. this.retry = 0;
  11644. this.basePointWorld = BABYLON.Vector3.Zero();
  11645. this.velocityWorld = BABYLON.Vector3.Zero();
  11646. this.normalizedVelocity = BABYLON.Vector3.Zero();
  11647. this._collisionPoint = BABYLON.Vector3.Zero();
  11648. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  11649. this._tempVector = BABYLON.Vector3.Zero();
  11650. this._tempVector2 = BABYLON.Vector3.Zero();
  11651. this._tempVector3 = BABYLON.Vector3.Zero();
  11652. this._tempVector4 = BABYLON.Vector3.Zero();
  11653. this._edge = BABYLON.Vector3.Zero();
  11654. this._baseToVertex = BABYLON.Vector3.Zero();
  11655. this._destinationPoint = BABYLON.Vector3.Zero();
  11656. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  11657. this._displacementVector = BABYLON.Vector3.Zero();
  11658. }
  11659. // Methods
  11660. Collider.prototype._initialize = function (source, dir, e) {
  11661. this.velocity = dir;
  11662. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  11663. this.basePoint = source;
  11664. source.multiplyToRef(this.radius, this.basePointWorld);
  11665. dir.multiplyToRef(this.radius, this.velocityWorld);
  11666. this.velocityWorldLength = this.velocityWorld.length();
  11667. this.epsilon = e;
  11668. this.collisionFound = false;
  11669. };
  11670. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  11671. pa.subtractToRef(point, this._tempVector);
  11672. pb.subtractToRef(point, this._tempVector2);
  11673. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  11674. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11675. if (d < 0)
  11676. return false;
  11677. pc.subtractToRef(point, this._tempVector3);
  11678. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  11679. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11680. if (d < 0)
  11681. return false;
  11682. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  11683. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11684. return d >= 0;
  11685. };
  11686. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  11687. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  11688. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  11689. if (distance > this.velocityWorldLength + max + sphereRadius) {
  11690. return false;
  11691. }
  11692. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  11693. return false;
  11694. return true;
  11695. };
  11696. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  11697. var t0;
  11698. var embeddedInPlane = false;
  11699. //defensive programming, actually not needed.
  11700. if (!trianglePlaneArray) {
  11701. trianglePlaneArray = [];
  11702. }
  11703. if (!trianglePlaneArray[faceIndex]) {
  11704. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  11705. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  11706. }
  11707. var trianglePlane = trianglePlaneArray[faceIndex];
  11708. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  11709. return;
  11710. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  11711. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  11712. if (normalDotVelocity == 0) {
  11713. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  11714. return;
  11715. embeddedInPlane = true;
  11716. t0 = 0;
  11717. }
  11718. else {
  11719. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  11720. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  11721. if (t0 > t1) {
  11722. var temp = t1;
  11723. t1 = t0;
  11724. t0 = temp;
  11725. }
  11726. if (t0 > 1.0 || t1 < 0.0)
  11727. return;
  11728. if (t0 < 0)
  11729. t0 = 0;
  11730. if (t0 > 1.0)
  11731. t0 = 1.0;
  11732. }
  11733. this._collisionPoint.copyFromFloats(0, 0, 0);
  11734. var found = false;
  11735. var t = 1.0;
  11736. if (!embeddedInPlane) {
  11737. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  11738. this.velocity.scaleToRef(t0, this._tempVector);
  11739. this._planeIntersectionPoint.addInPlace(this._tempVector);
  11740. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  11741. found = true;
  11742. t = t0;
  11743. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  11744. }
  11745. }
  11746. if (!found) {
  11747. var velocitySquaredLength = this.velocity.lengthSquared();
  11748. var a = velocitySquaredLength;
  11749. this.basePoint.subtractToRef(p1, this._tempVector);
  11750. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11751. var c = this._tempVector.lengthSquared() - 1.0;
  11752. var lowestRoot = getLowestRoot(a, b, c, t);
  11753. if (lowestRoot.found) {
  11754. t = lowestRoot.root;
  11755. found = true;
  11756. this._collisionPoint.copyFrom(p1);
  11757. }
  11758. this.basePoint.subtractToRef(p2, this._tempVector);
  11759. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11760. c = this._tempVector.lengthSquared() - 1.0;
  11761. lowestRoot = getLowestRoot(a, b, c, t);
  11762. if (lowestRoot.found) {
  11763. t = lowestRoot.root;
  11764. found = true;
  11765. this._collisionPoint.copyFrom(p2);
  11766. }
  11767. this.basePoint.subtractToRef(p3, this._tempVector);
  11768. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11769. c = this._tempVector.lengthSquared() - 1.0;
  11770. lowestRoot = getLowestRoot(a, b, c, t);
  11771. if (lowestRoot.found) {
  11772. t = lowestRoot.root;
  11773. found = true;
  11774. this._collisionPoint.copyFrom(p3);
  11775. }
  11776. p2.subtractToRef(p1, this._edge);
  11777. p1.subtractToRef(this.basePoint, this._baseToVertex);
  11778. var edgeSquaredLength = this._edge.lengthSquared();
  11779. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11780. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11781. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11782. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11783. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11784. lowestRoot = getLowestRoot(a, b, c, t);
  11785. if (lowestRoot.found) {
  11786. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11787. if (f >= 0.0 && f <= 1.0) {
  11788. t = lowestRoot.root;
  11789. found = true;
  11790. this._edge.scaleInPlace(f);
  11791. p1.addToRef(this._edge, this._collisionPoint);
  11792. }
  11793. }
  11794. p3.subtractToRef(p2, this._edge);
  11795. p2.subtractToRef(this.basePoint, this._baseToVertex);
  11796. edgeSquaredLength = this._edge.lengthSquared();
  11797. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11798. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11799. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11800. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11801. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11802. lowestRoot = getLowestRoot(a, b, c, t);
  11803. if (lowestRoot.found) {
  11804. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11805. if (f >= 0.0 && f <= 1.0) {
  11806. t = lowestRoot.root;
  11807. found = true;
  11808. this._edge.scaleInPlace(f);
  11809. p2.addToRef(this._edge, this._collisionPoint);
  11810. }
  11811. }
  11812. p1.subtractToRef(p3, this._edge);
  11813. p3.subtractToRef(this.basePoint, this._baseToVertex);
  11814. edgeSquaredLength = this._edge.lengthSquared();
  11815. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11816. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11817. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11818. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11819. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11820. lowestRoot = getLowestRoot(a, b, c, t);
  11821. if (lowestRoot.found) {
  11822. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11823. if (f >= 0.0 && f <= 1.0) {
  11824. t = lowestRoot.root;
  11825. found = true;
  11826. this._edge.scaleInPlace(f);
  11827. p3.addToRef(this._edge, this._collisionPoint);
  11828. }
  11829. }
  11830. }
  11831. if (found) {
  11832. var distToCollision = t * this.velocity.length();
  11833. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  11834. if (!this.intersectionPoint) {
  11835. this.intersectionPoint = this._collisionPoint.clone();
  11836. }
  11837. else {
  11838. this.intersectionPoint.copyFrom(this._collisionPoint);
  11839. }
  11840. this.nearestDistance = distToCollision;
  11841. this.collisionFound = true;
  11842. }
  11843. }
  11844. };
  11845. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  11846. for (var i = indexStart; i < indexEnd; i += 3) {
  11847. var p1 = pts[indices[i] - decal];
  11848. var p2 = pts[indices[i + 1] - decal];
  11849. var p3 = pts[indices[i + 2] - decal];
  11850. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  11851. }
  11852. };
  11853. Collider.prototype._getResponse = function (pos, vel) {
  11854. pos.addToRef(vel, this._destinationPoint);
  11855. vel.scaleInPlace((this.nearestDistance / vel.length()));
  11856. this.basePoint.addToRef(vel, pos);
  11857. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  11858. this._slidePlaneNormal.normalize();
  11859. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  11860. pos.addInPlace(this._displacementVector);
  11861. this.intersectionPoint.addInPlace(this._displacementVector);
  11862. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  11863. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  11864. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  11865. };
  11866. return Collider;
  11867. })();
  11868. BABYLON.Collider = Collider;
  11869. })(BABYLON || (BABYLON = {}));
  11870. var BABYLON;
  11871. (function (BABYLON) {
  11872. //WebWorker code will be inserted to this variable.
  11873. BABYLON.CollisionWorker = "";
  11874. (function (WorkerTaskType) {
  11875. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  11876. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  11877. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  11878. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  11879. var WorkerTaskType = BABYLON.WorkerTaskType;
  11880. (function (WorkerReplyType) {
  11881. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  11882. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  11883. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  11884. var WorkerReplyType = BABYLON.WorkerReplyType;
  11885. var CollisionCoordinatorWorker = (function () {
  11886. function CollisionCoordinatorWorker() {
  11887. var _this = this;
  11888. this._scaledPosition = BABYLON.Vector3.Zero();
  11889. this._scaledVelocity = BABYLON.Vector3.Zero();
  11890. this.onMeshUpdated = function (mesh) {
  11891. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  11892. };
  11893. this.onGeometryUpdated = function (geometry) {
  11894. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  11895. };
  11896. this._afterRender = function () {
  11897. if (!_this._init)
  11898. return;
  11899. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  11900. return;
  11901. }
  11902. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  11903. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  11904. if (_this._runningUpdated > 4) {
  11905. return;
  11906. }
  11907. ++_this._runningUpdated;
  11908. var payload = {
  11909. updatedMeshes: _this._addUpdateMeshesList,
  11910. updatedGeometries: _this._addUpdateGeometriesList,
  11911. removedGeometries: _this._toRemoveGeometryArray,
  11912. removedMeshes: _this._toRemoveMeshesArray
  11913. };
  11914. var message = {
  11915. payload: payload,
  11916. taskType: WorkerTaskType.UPDATE
  11917. };
  11918. var serializable = [];
  11919. for (var id in payload.updatedGeometries) {
  11920. if (payload.updatedGeometries.hasOwnProperty(id)) {
  11921. //prepare transferables
  11922. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  11923. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  11924. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  11925. }
  11926. }
  11927. _this._worker.postMessage(message, serializable);
  11928. _this._addUpdateMeshesList = {};
  11929. _this._addUpdateGeometriesList = {};
  11930. _this._toRemoveGeometryArray = [];
  11931. _this._toRemoveMeshesArray = [];
  11932. };
  11933. this._onMessageFromWorker = function (e) {
  11934. var returnData = e.data;
  11935. if (returnData.error != WorkerReplyType.SUCCESS) {
  11936. //TODO what errors can be returned from the worker?
  11937. BABYLON.Tools.Warn("error returned from worker!");
  11938. return;
  11939. }
  11940. switch (returnData.taskType) {
  11941. case WorkerTaskType.INIT:
  11942. _this._init = true;
  11943. //Update the worked with ALL of the scene's current state
  11944. _this._scene.meshes.forEach(function (mesh) {
  11945. _this.onMeshAdded(mesh);
  11946. });
  11947. _this._scene.getGeometries().forEach(function (geometry) {
  11948. _this.onGeometryAdded(geometry);
  11949. });
  11950. break;
  11951. case WorkerTaskType.UPDATE:
  11952. _this._runningUpdated--;
  11953. break;
  11954. case WorkerTaskType.COLLIDE:
  11955. _this._runningCollisionTask = false;
  11956. var returnPayload = returnData.payload;
  11957. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  11958. return;
  11959. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  11960. //cleanup
  11961. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  11962. break;
  11963. }
  11964. };
  11965. this._collisionsCallbackArray = [];
  11966. this._init = false;
  11967. this._runningUpdated = 0;
  11968. this._runningCollisionTask = false;
  11969. this._addUpdateMeshesList = {};
  11970. this._addUpdateGeometriesList = {};
  11971. this._toRemoveGeometryArray = [];
  11972. this._toRemoveMeshesArray = [];
  11973. }
  11974. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  11975. if (!this._init)
  11976. return;
  11977. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  11978. return;
  11979. position.divideToRef(collider.radius, this._scaledPosition);
  11980. velocity.divideToRef(collider.radius, this._scaledVelocity);
  11981. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  11982. var payload = {
  11983. collider: {
  11984. position: this._scaledPosition.asArray(),
  11985. velocity: this._scaledVelocity.asArray(),
  11986. radius: collider.radius.asArray()
  11987. },
  11988. collisionId: collisionIndex,
  11989. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  11990. maximumRetry: maximumRetry
  11991. };
  11992. var message = {
  11993. payload: payload,
  11994. taskType: WorkerTaskType.COLLIDE
  11995. };
  11996. this._worker.postMessage(message);
  11997. };
  11998. CollisionCoordinatorWorker.prototype.init = function (scene) {
  11999. this._scene = scene;
  12000. this._scene.registerAfterRender(this._afterRender);
  12001. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  12002. this._worker = new Worker(workerUrl);
  12003. this._worker.onmessage = this._onMessageFromWorker;
  12004. var message = {
  12005. payload: {},
  12006. taskType: WorkerTaskType.INIT
  12007. };
  12008. this._worker.postMessage(message);
  12009. };
  12010. CollisionCoordinatorWorker.prototype.destroy = function () {
  12011. this._scene.unregisterAfterRender(this._afterRender);
  12012. this._worker.terminate();
  12013. };
  12014. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  12015. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  12016. this.onMeshUpdated(mesh);
  12017. };
  12018. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  12019. this._toRemoveMeshesArray.push(mesh.uniqueId);
  12020. };
  12021. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  12022. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  12023. geometry.onGeometryUpdated = this.onGeometryUpdated;
  12024. this.onGeometryUpdated(geometry);
  12025. };
  12026. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  12027. this._toRemoveGeometryArray.push(geometry.id);
  12028. };
  12029. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  12030. var submeshes = [];
  12031. if (mesh.subMeshes) {
  12032. submeshes = mesh.subMeshes.map(function (sm, idx) {
  12033. return {
  12034. position: idx,
  12035. verticesStart: sm.verticesStart,
  12036. verticesCount: sm.verticesCount,
  12037. indexStart: sm.indexStart,
  12038. indexCount: sm.indexCount,
  12039. hasMaterial: !!sm.getMaterial(),
  12040. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12041. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  12042. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12043. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  12044. };
  12045. });
  12046. }
  12047. var geometryId = null;
  12048. if (mesh instanceof BABYLON.Mesh) {
  12049. geometryId = mesh.geometry ? mesh.geometry.id : null;
  12050. }
  12051. else if (mesh instanceof BABYLON.InstancedMesh) {
  12052. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  12053. }
  12054. return {
  12055. uniqueId: mesh.uniqueId,
  12056. id: mesh.id,
  12057. name: mesh.name,
  12058. geometryId: geometryId,
  12059. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12060. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  12061. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12062. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  12063. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  12064. subMeshes: submeshes,
  12065. checkCollisions: mesh.checkCollisions
  12066. };
  12067. };
  12068. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  12069. return {
  12070. id: geometry.id,
  12071. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  12072. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  12073. indices: new Int32Array(geometry.getIndices() || []),
  12074. };
  12075. };
  12076. return CollisionCoordinatorWorker;
  12077. })();
  12078. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  12079. var CollisionCoordinatorLegacy = (function () {
  12080. function CollisionCoordinatorLegacy() {
  12081. this._scaledPosition = BABYLON.Vector3.Zero();
  12082. this._scaledVelocity = BABYLON.Vector3.Zero();
  12083. this._finalPosition = BABYLON.Vector3.Zero();
  12084. }
  12085. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12086. position.divideToRef(collider.radius, this._scaledPosition);
  12087. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12088. collider.collidedMesh = null;
  12089. collider.retry = 0;
  12090. collider.initialVelocity = this._scaledVelocity;
  12091. collider.initialPosition = this._scaledPosition;
  12092. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  12093. this._finalPosition.multiplyInPlace(collider.radius);
  12094. //run the callback
  12095. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  12096. };
  12097. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  12098. this._scene = scene;
  12099. };
  12100. CollisionCoordinatorLegacy.prototype.destroy = function () {
  12101. //Legacy need no destruction method.
  12102. };
  12103. //No update in legacy mode
  12104. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  12105. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  12106. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  12107. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  12108. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  12109. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  12110. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  12111. if (excludedMesh === void 0) { excludedMesh = null; }
  12112. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  12113. if (collider.retry >= maximumRetry) {
  12114. finalPosition.copyFrom(position);
  12115. return;
  12116. }
  12117. collider._initialize(position, velocity, closeDistance);
  12118. // Check all meshes
  12119. for (var index = 0; index < this._scene.meshes.length; index++) {
  12120. var mesh = this._scene.meshes[index];
  12121. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  12122. mesh._checkCollision(collider);
  12123. }
  12124. }
  12125. if (!collider.collisionFound) {
  12126. position.addToRef(velocity, finalPosition);
  12127. return;
  12128. }
  12129. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  12130. collider._getResponse(position, velocity);
  12131. }
  12132. if (velocity.length() <= closeDistance) {
  12133. finalPosition.copyFrom(position);
  12134. return;
  12135. }
  12136. collider.retry++;
  12137. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  12138. };
  12139. return CollisionCoordinatorLegacy;
  12140. })();
  12141. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  12142. })(BABYLON || (BABYLON = {}));
  12143. var BABYLON;
  12144. (function (BABYLON) {
  12145. var Camera = (function (_super) {
  12146. __extends(Camera, _super);
  12147. function Camera(name, position, scene) {
  12148. _super.call(this, name, scene);
  12149. this.upVector = BABYLON.Vector3.Up();
  12150. this.orthoLeft = null;
  12151. this.orthoRight = null;
  12152. this.orthoBottom = null;
  12153. this.orthoTop = null;
  12154. this.fov = 0.8;
  12155. this.minZ = 1.0;
  12156. this.maxZ = 10000.0;
  12157. this.inertia = 0.9;
  12158. this.mode = Camera.PERSPECTIVE_CAMERA;
  12159. this.isIntermediate = false;
  12160. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  12161. this.layerMask = 0x0FFFFFFF;
  12162. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  12163. // Camera rig members
  12164. this.cameraRigMode = Camera.RIG_MODE_NONE;
  12165. this._rigCameras = new Array();
  12166. // Cache
  12167. this._computedViewMatrix = BABYLON.Matrix.Identity();
  12168. this._projectionMatrix = new BABYLON.Matrix();
  12169. this._postProcesses = new Array();
  12170. this._transformMatrix = BABYLON.Matrix.Zero();
  12171. this._activeMeshes = new BABYLON.SmartArray(256);
  12172. this._globalPosition = BABYLON.Vector3.Zero();
  12173. this._refreshFrustumPlanes = true;
  12174. scene.addCamera(this);
  12175. if (!scene.activeCamera) {
  12176. scene.activeCamera = this;
  12177. }
  12178. this.position = position;
  12179. }
  12180. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  12181. get: function () {
  12182. return Camera._PERSPECTIVE_CAMERA;
  12183. },
  12184. enumerable: true,
  12185. configurable: true
  12186. });
  12187. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  12188. get: function () {
  12189. return Camera._ORTHOGRAPHIC_CAMERA;
  12190. },
  12191. enumerable: true,
  12192. configurable: true
  12193. });
  12194. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  12195. get: function () {
  12196. return Camera._FOVMODE_VERTICAL_FIXED;
  12197. },
  12198. enumerable: true,
  12199. configurable: true
  12200. });
  12201. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  12202. get: function () {
  12203. return Camera._FOVMODE_HORIZONTAL_FIXED;
  12204. },
  12205. enumerable: true,
  12206. configurable: true
  12207. });
  12208. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  12209. get: function () {
  12210. return Camera._RIG_MODE_NONE;
  12211. },
  12212. enumerable: true,
  12213. configurable: true
  12214. });
  12215. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  12216. get: function () {
  12217. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  12218. },
  12219. enumerable: true,
  12220. configurable: true
  12221. });
  12222. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  12223. get: function () {
  12224. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  12225. },
  12226. enumerable: true,
  12227. configurable: true
  12228. });
  12229. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  12230. get: function () {
  12231. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12232. },
  12233. enumerable: true,
  12234. configurable: true
  12235. });
  12236. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  12237. get: function () {
  12238. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  12239. },
  12240. enumerable: true,
  12241. configurable: true
  12242. });
  12243. Object.defineProperty(Camera, "RIG_MODE_VR", {
  12244. get: function () {
  12245. return Camera._RIG_MODE_VR;
  12246. },
  12247. enumerable: true,
  12248. configurable: true
  12249. });
  12250. /**
  12251. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12252. */
  12253. Camera.prototype.toString = function (fullDetails) {
  12254. var ret = "Name: " + this.name;
  12255. ret += ", type: " + this.getTypeName();
  12256. if (this.animations) {
  12257. for (var i = 0; i < this.animations.length; i++) {
  12258. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12259. }
  12260. }
  12261. if (fullDetails) {
  12262. }
  12263. return ret;
  12264. };
  12265. Object.defineProperty(Camera.prototype, "globalPosition", {
  12266. get: function () {
  12267. return this._globalPosition;
  12268. },
  12269. enumerable: true,
  12270. configurable: true
  12271. });
  12272. Camera.prototype.getActiveMeshes = function () {
  12273. return this._activeMeshes;
  12274. };
  12275. Camera.prototype.isActiveMesh = function (mesh) {
  12276. return (this._activeMeshes.indexOf(mesh) !== -1);
  12277. };
  12278. //Cache
  12279. Camera.prototype._initCache = function () {
  12280. _super.prototype._initCache.call(this);
  12281. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12282. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12283. this._cache.mode = undefined;
  12284. this._cache.minZ = undefined;
  12285. this._cache.maxZ = undefined;
  12286. this._cache.fov = undefined;
  12287. this._cache.aspectRatio = undefined;
  12288. this._cache.orthoLeft = undefined;
  12289. this._cache.orthoRight = undefined;
  12290. this._cache.orthoBottom = undefined;
  12291. this._cache.orthoTop = undefined;
  12292. this._cache.renderWidth = undefined;
  12293. this._cache.renderHeight = undefined;
  12294. };
  12295. Camera.prototype._updateCache = function (ignoreParentClass) {
  12296. if (!ignoreParentClass) {
  12297. _super.prototype._updateCache.call(this);
  12298. }
  12299. var engine = this.getEngine();
  12300. this._cache.position.copyFrom(this.position);
  12301. this._cache.upVector.copyFrom(this.upVector);
  12302. this._cache.mode = this.mode;
  12303. this._cache.minZ = this.minZ;
  12304. this._cache.maxZ = this.maxZ;
  12305. this._cache.fov = this.fov;
  12306. this._cache.aspectRatio = engine.getAspectRatio(this);
  12307. this._cache.orthoLeft = this.orthoLeft;
  12308. this._cache.orthoRight = this.orthoRight;
  12309. this._cache.orthoBottom = this.orthoBottom;
  12310. this._cache.orthoTop = this.orthoTop;
  12311. this._cache.renderWidth = engine.getRenderWidth();
  12312. this._cache.renderHeight = engine.getRenderHeight();
  12313. };
  12314. Camera.prototype._updateFromScene = function () {
  12315. this.updateCache();
  12316. this.update();
  12317. };
  12318. // Synchronized
  12319. Camera.prototype._isSynchronized = function () {
  12320. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  12321. };
  12322. Camera.prototype._isSynchronizedViewMatrix = function () {
  12323. if (!_super.prototype._isSynchronized.call(this))
  12324. return false;
  12325. return this._cache.position.equals(this.position)
  12326. && this._cache.upVector.equals(this.upVector)
  12327. && this.isSynchronizedWithParent();
  12328. };
  12329. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  12330. var check = this._cache.mode === this.mode
  12331. && this._cache.minZ === this.minZ
  12332. && this._cache.maxZ === this.maxZ;
  12333. if (!check) {
  12334. return false;
  12335. }
  12336. var engine = this.getEngine();
  12337. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12338. check = this._cache.fov === this.fov
  12339. && this._cache.aspectRatio === engine.getAspectRatio(this);
  12340. }
  12341. else {
  12342. check = this._cache.orthoLeft === this.orthoLeft
  12343. && this._cache.orthoRight === this.orthoRight
  12344. && this._cache.orthoBottom === this.orthoBottom
  12345. && this._cache.orthoTop === this.orthoTop
  12346. && this._cache.renderWidth === engine.getRenderWidth()
  12347. && this._cache.renderHeight === engine.getRenderHeight();
  12348. }
  12349. return check;
  12350. };
  12351. // Controls
  12352. Camera.prototype.attachControl = function (element, noPreventDefault) {
  12353. };
  12354. Camera.prototype.detachControl = function (element) {
  12355. };
  12356. Camera.prototype.update = function () {
  12357. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12358. this._updateRigCameras();
  12359. }
  12360. this._checkInputs();
  12361. };
  12362. Camera.prototype._checkInputs = function () {
  12363. };
  12364. Camera.prototype._cascadePostProcessesToRigCams = function () {
  12365. // invalidate framebuffer
  12366. if (this._postProcesses.length > 0) {
  12367. this._postProcesses[0].markTextureDirty();
  12368. }
  12369. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  12370. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  12371. var cam = this._rigCameras[i];
  12372. var rigPostProcess = cam._rigPostProcess;
  12373. // for VR rig, there does not have to be a post process
  12374. if (rigPostProcess) {
  12375. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  12376. if (isPass) {
  12377. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  12378. cam.isIntermediate = this._postProcesses.length === 0;
  12379. }
  12380. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  12381. rigPostProcess.markTextureDirty();
  12382. }
  12383. else {
  12384. cam._postProcesses = this._postProcesses.slice(0);
  12385. }
  12386. }
  12387. };
  12388. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  12389. if (insertAt === void 0) { insertAt = null; }
  12390. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  12391. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  12392. return 0;
  12393. }
  12394. if (insertAt == null || insertAt < 0) {
  12395. this._postProcesses.push(postProcess);
  12396. }
  12397. else {
  12398. this._postProcesses.splice(insertAt, 0, postProcess);
  12399. }
  12400. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12401. return this._postProcesses.indexOf(postProcess);
  12402. };
  12403. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  12404. if (atIndices === void 0) { atIndices = null; }
  12405. var result = [];
  12406. var i;
  12407. var index;
  12408. if (!atIndices) {
  12409. var idx = this._postProcesses.indexOf(postProcess);
  12410. if (idx !== -1) {
  12411. this._postProcesses.splice(idx, 1);
  12412. }
  12413. }
  12414. else {
  12415. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  12416. // iterate descending, so can just splice as we go
  12417. for (i = atIndices.length - 1; i >= 0; i--) {
  12418. if (this._postProcesses[atIndices[i]] !== postProcess) {
  12419. result.push(i);
  12420. continue;
  12421. }
  12422. this._postProcesses.splice(index, 1);
  12423. }
  12424. }
  12425. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12426. return result;
  12427. };
  12428. Camera.prototype.getWorldMatrix = function () {
  12429. if (!this._worldMatrix) {
  12430. this._worldMatrix = BABYLON.Matrix.Identity();
  12431. }
  12432. var viewMatrix = this.getViewMatrix();
  12433. viewMatrix.invertToRef(this._worldMatrix);
  12434. return this._worldMatrix;
  12435. };
  12436. Camera.prototype._getViewMatrix = function () {
  12437. return BABYLON.Matrix.Identity();
  12438. };
  12439. Camera.prototype.getViewMatrix = function (force) {
  12440. this._computedViewMatrix = this._computeViewMatrix(force);
  12441. if (!force && this._isSynchronizedViewMatrix()) {
  12442. return this._computedViewMatrix;
  12443. }
  12444. this._refreshFrustumPlanes = true;
  12445. if (!this.parent || !this.parent.getWorldMatrix) {
  12446. this._globalPosition.copyFrom(this.position);
  12447. }
  12448. else {
  12449. if (!this._worldMatrix) {
  12450. this._worldMatrix = BABYLON.Matrix.Identity();
  12451. }
  12452. this._computedViewMatrix.invertToRef(this._worldMatrix);
  12453. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  12454. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  12455. this._computedViewMatrix.invert();
  12456. this._markSyncedWithParent();
  12457. }
  12458. this._currentRenderId = this.getScene().getRenderId();
  12459. return this._computedViewMatrix;
  12460. };
  12461. Camera.prototype._computeViewMatrix = function (force) {
  12462. if (!force && this._isSynchronizedViewMatrix()) {
  12463. return this._computedViewMatrix;
  12464. }
  12465. this._computedViewMatrix = this._getViewMatrix();
  12466. this._currentRenderId = this.getScene().getRenderId();
  12467. return this._computedViewMatrix;
  12468. };
  12469. Camera.prototype.getProjectionMatrix = function (force) {
  12470. if (!force && this._isSynchronizedProjectionMatrix()) {
  12471. return this._projectionMatrix;
  12472. }
  12473. this._refreshFrustumPlanes = true;
  12474. var engine = this.getEngine();
  12475. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12476. if (this.minZ <= 0) {
  12477. this.minZ = 0.1;
  12478. }
  12479. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  12480. return this._projectionMatrix;
  12481. }
  12482. var halfWidth = engine.getRenderWidth() / 2.0;
  12483. var halfHeight = engine.getRenderHeight() / 2.0;
  12484. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  12485. return this._projectionMatrix;
  12486. };
  12487. Camera.prototype.getTranformationMatrix = function () {
  12488. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12489. return this._transformMatrix;
  12490. };
  12491. Camera.prototype.updateFrustumPlanes = function () {
  12492. if (!this._refreshFrustumPlanes) {
  12493. return;
  12494. }
  12495. this.getTranformationMatrix();
  12496. if (!this._frustumPlanes) {
  12497. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12498. }
  12499. else {
  12500. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12501. }
  12502. this._refreshFrustumPlanes = false;
  12503. };
  12504. Camera.prototype.isInFrustum = function (target) {
  12505. this.updateFrustumPlanes();
  12506. return target.isInFrustum(this._frustumPlanes);
  12507. };
  12508. Camera.prototype.isCompletelyInFrustum = function (target) {
  12509. this.updateFrustumPlanes();
  12510. return target.isCompletelyInFrustum(this._frustumPlanes);
  12511. };
  12512. Camera.prototype.dispose = function () {
  12513. // Animations
  12514. this.getScene().stopAnimation(this);
  12515. // Remove from scene
  12516. this.getScene().removeCamera(this);
  12517. while (this._rigCameras.length > 0) {
  12518. this._rigCameras.pop().dispose();
  12519. }
  12520. // Postprocesses
  12521. for (var i = 0; i < this._postProcesses.length; ++i) {
  12522. this._postProcesses[i].dispose(this);
  12523. }
  12524. _super.prototype.dispose.call(this);
  12525. };
  12526. // ---- Camera rigs section ----
  12527. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  12528. while (this._rigCameras.length > 0) {
  12529. this._rigCameras.pop().dispose();
  12530. }
  12531. this.cameraRigMode = mode;
  12532. this._cameraRigParams = {};
  12533. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  12534. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  12535. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  12536. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  12537. // create the rig cameras, unless none
  12538. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12539. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  12540. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  12541. }
  12542. switch (this.cameraRigMode) {
  12543. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12544. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12545. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  12546. break;
  12547. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12548. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12549. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12550. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12551. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12552. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  12553. break;
  12554. case Camera.RIG_MODE_VR:
  12555. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  12556. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  12557. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  12558. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12559. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  12560. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  12561. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  12562. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  12563. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  12564. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12565. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  12566. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  12567. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  12568. if (metrics.compensateDistortion) {
  12569. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  12570. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  12571. }
  12572. break;
  12573. }
  12574. this._cascadePostProcessesToRigCams();
  12575. this.
  12576. update();
  12577. };
  12578. Camera.prototype._getVRProjectionMatrix = function () {
  12579. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  12580. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  12581. return this._projectionMatrix;
  12582. };
  12583. Camera.prototype.setCameraRigParameter = function (name, value) {
  12584. if (!this._cameraRigParams) {
  12585. this._cameraRigParams = {};
  12586. }
  12587. this._cameraRigParams[name] = value;
  12588. //provisionnally:
  12589. if (name === "interaxialDistance") {
  12590. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  12591. }
  12592. };
  12593. /**
  12594. * needs to be overridden by children so sub has required properties to be copied
  12595. */
  12596. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  12597. return null;
  12598. };
  12599. /**
  12600. * May need to be overridden by children
  12601. */
  12602. Camera.prototype._updateRigCameras = function () {
  12603. for (var i = 0; i < this._rigCameras.length; i++) {
  12604. this._rigCameras[i].minZ = this.minZ;
  12605. this._rigCameras[i].maxZ = this.maxZ;
  12606. this._rigCameras[i].fov = this.fov;
  12607. }
  12608. // only update viewport when ANAGLYPH
  12609. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  12610. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  12611. }
  12612. };
  12613. Camera.prototype._setupInputs = function () {
  12614. };
  12615. Camera.prototype.serialize = function () {
  12616. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  12617. // Type
  12618. serializationObject.type = this.getTypeName();
  12619. // Parent
  12620. if (this.parent) {
  12621. serializationObject.parentId = this.parent.id;
  12622. }
  12623. if (this.inputs) {
  12624. this.inputs.serialize(serializationObject);
  12625. }
  12626. // Animations
  12627. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  12628. serializationObject.ranges = this.serializeAnimationRanges();
  12629. return serializationObject;
  12630. };
  12631. Camera.prototype.getTypeName = function () {
  12632. return "Camera";
  12633. };
  12634. Camera.prototype.clone = function (name) {
  12635. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  12636. };
  12637. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  12638. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  12639. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  12640. switch (type) {
  12641. case "ArcRotateCamera":
  12642. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  12643. case "DeviceOrientationCamera":
  12644. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  12645. case "FollowCamera":
  12646. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  12647. case "ArcFollowCamera":
  12648. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  12649. case "GamepadCamera":
  12650. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  12651. case "TouchCamera":
  12652. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  12653. case "VirtualJoysticksCamera":
  12654. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  12655. case "WebVRFreeCamera":
  12656. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  12657. case "VRDeviceOrientationFreeCamera":
  12658. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  12659. case "AnaglyphArcRotateCamera":
  12660. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12661. case "AnaglyphFreeCamera":
  12662. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12663. case "AnaglyphGamepadCamera":
  12664. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12665. case "AnaglyphUniversalCamera":
  12666. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12667. case "StereoscopicArcRotateCamera":
  12668. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12669. case "StereoscopicFreeCamera":
  12670. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12671. case "StereoscopicGamepadCamera":
  12672. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12673. case "StereoscopicUniversalCamera":
  12674. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12675. case "FreeCamera":
  12676. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  12677. default:
  12678. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  12679. }
  12680. };
  12681. Camera.Parse = function (parsedCamera, scene) {
  12682. var type = parsedCamera.type;
  12683. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  12684. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  12685. // Parent
  12686. if (parsedCamera.parentId) {
  12687. camera._waitingParentId = parsedCamera.parentId;
  12688. }
  12689. //If camera has an input manager, let it parse inputs settings
  12690. if (camera.inputs) {
  12691. camera.inputs.parse(parsedCamera);
  12692. camera._setupInputs();
  12693. }
  12694. // Target
  12695. if (parsedCamera.target) {
  12696. if (camera.setTarget) {
  12697. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  12698. }
  12699. }
  12700. // Apply 3d rig, when found
  12701. if (parsedCamera.cameraRigMode) {
  12702. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  12703. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  12704. }
  12705. // Animations
  12706. if (parsedCamera.animations) {
  12707. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  12708. var parsedAnimation = parsedCamera.animations[animationIndex];
  12709. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  12710. }
  12711. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  12712. }
  12713. if (parsedCamera.autoAnimate) {
  12714. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  12715. }
  12716. return camera;
  12717. };
  12718. // Statics
  12719. Camera._PERSPECTIVE_CAMERA = 0;
  12720. Camera._ORTHOGRAPHIC_CAMERA = 1;
  12721. Camera._FOVMODE_VERTICAL_FIXED = 0;
  12722. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  12723. Camera._RIG_MODE_NONE = 0;
  12724. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  12725. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  12726. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  12727. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  12728. Camera._RIG_MODE_VR = 20;
  12729. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  12730. __decorate([
  12731. BABYLON.serializeAsVector3()
  12732. ], Camera.prototype, "position", void 0);
  12733. __decorate([
  12734. BABYLON.serializeAsVector3()
  12735. ], Camera.prototype, "upVector", void 0);
  12736. __decorate([
  12737. BABYLON.serialize()
  12738. ], Camera.prototype, "orthoLeft", void 0);
  12739. __decorate([
  12740. BABYLON.serialize()
  12741. ], Camera.prototype, "orthoRight", void 0);
  12742. __decorate([
  12743. BABYLON.serialize()
  12744. ], Camera.prototype, "orthoBottom", void 0);
  12745. __decorate([
  12746. BABYLON.serialize()
  12747. ], Camera.prototype, "orthoTop", void 0);
  12748. __decorate([
  12749. BABYLON.serialize()
  12750. ], Camera.prototype, "fov", void 0);
  12751. __decorate([
  12752. BABYLON.serialize()
  12753. ], Camera.prototype, "minZ", void 0);
  12754. __decorate([
  12755. BABYLON.serialize()
  12756. ], Camera.prototype, "maxZ", void 0);
  12757. __decorate([
  12758. BABYLON.serialize()
  12759. ], Camera.prototype, "inertia", void 0);
  12760. __decorate([
  12761. BABYLON.serialize()
  12762. ], Camera.prototype, "mode", void 0);
  12763. __decorate([
  12764. BABYLON.serialize()
  12765. ], Camera.prototype, "layerMask", void 0);
  12766. __decorate([
  12767. BABYLON.serialize()
  12768. ], Camera.prototype, "fovMode", void 0);
  12769. __decorate([
  12770. BABYLON.serialize()
  12771. ], Camera.prototype, "cameraRigMode", void 0);
  12772. __decorate([
  12773. BABYLON.serialize()
  12774. ], Camera.prototype, "interaxialDistance", void 0);
  12775. __decorate([
  12776. BABYLON.serialize()
  12777. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  12778. return Camera;
  12779. })(BABYLON.Node);
  12780. BABYLON.Camera = Camera;
  12781. })(BABYLON || (BABYLON = {}));
  12782. var BABYLON;
  12783. (function (BABYLON) {
  12784. BABYLON.CameraInputTypes = {};
  12785. var CameraInputsManager = (function () {
  12786. function CameraInputsManager(camera) {
  12787. this.attached = {};
  12788. this.camera = camera;
  12789. this.checkInputs = function () { };
  12790. }
  12791. CameraInputsManager.prototype.add = function (input) {
  12792. var type = input.getSimpleName();
  12793. if (this.attached[type]) {
  12794. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  12795. return;
  12796. }
  12797. this.attached[type] = input;
  12798. input.camera = this.camera;
  12799. //for checkInputs, we are dynamically creating a function
  12800. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  12801. if (input.checkInputs) {
  12802. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12803. }
  12804. if (this.attachedElement) {
  12805. input.attachControl(this.attachedElement);
  12806. }
  12807. };
  12808. CameraInputsManager.prototype.remove = function (inputToRemove) {
  12809. for (var cam in this.attached) {
  12810. var input = this.attached[cam];
  12811. if (input === inputToRemove) {
  12812. input.detachControl(this.attachedElement);
  12813. delete this.attached[cam];
  12814. this.rebuildInputCheck();
  12815. }
  12816. }
  12817. };
  12818. CameraInputsManager.prototype.removeByType = function (inputType) {
  12819. for (var cam in this.attached) {
  12820. var input = this.attached[cam];
  12821. if (input.getTypeName() === inputType) {
  12822. input.detachControl(this.attachedElement);
  12823. delete this.attached[cam];
  12824. this.rebuildInputCheck();
  12825. }
  12826. }
  12827. };
  12828. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  12829. var current = this.checkInputs;
  12830. return function () {
  12831. current();
  12832. fn();
  12833. };
  12834. };
  12835. CameraInputsManager.prototype.attachInput = function (input) {
  12836. input.attachControl(this.attachedElement, this.noPreventDefault);
  12837. };
  12838. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  12839. if (this.attachedElement) {
  12840. return;
  12841. }
  12842. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  12843. this.attachedElement = element;
  12844. this.noPreventDefault = noPreventDefault;
  12845. for (var cam in this.attached) {
  12846. var input = this.attached[cam];
  12847. this.attached[cam].attachControl(element, noPreventDefault);
  12848. }
  12849. };
  12850. CameraInputsManager.prototype.detachElement = function (element) {
  12851. if (this.attachedElement !== element) {
  12852. return;
  12853. }
  12854. for (var cam in this.attached) {
  12855. var input = this.attached[cam];
  12856. this.attached[cam].detachControl(element);
  12857. }
  12858. this.attachedElement = null;
  12859. };
  12860. CameraInputsManager.prototype.rebuildInputCheck = function () {
  12861. this.checkInputs = function () { };
  12862. for (var cam in this.attached) {
  12863. var input = this.attached[cam];
  12864. if (input.checkInputs) {
  12865. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12866. }
  12867. }
  12868. };
  12869. CameraInputsManager.prototype.clear = function () {
  12870. if (this.attachedElement) {
  12871. this.detachElement(this.attachedElement);
  12872. }
  12873. this.attached = {};
  12874. this.attachedElement = null;
  12875. this.checkInputs = function () { };
  12876. };
  12877. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  12878. var inputs = {};
  12879. for (var cam in this.attached) {
  12880. var input = this.attached[cam];
  12881. var res = BABYLON.SerializationHelper.Serialize(input);
  12882. inputs[input.getTypeName()] = res;
  12883. }
  12884. serializedCamera.inputsmgr = inputs;
  12885. };
  12886. CameraInputsManager.prototype.parse = function (parsedCamera) {
  12887. var parsedInputs = parsedCamera.inputsmgr;
  12888. if (parsedInputs) {
  12889. this.clear();
  12890. for (var n in parsedInputs) {
  12891. var construct = BABYLON.CameraInputTypes[n];
  12892. if (construct) {
  12893. var parsedinput = parsedInputs[n];
  12894. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  12895. this.add(input);
  12896. }
  12897. }
  12898. }
  12899. else {
  12900. //2016-03-08 this part is for managing backward compatibility
  12901. for (var n in this.attached) {
  12902. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  12903. if (construct) {
  12904. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  12905. this.remove(this.attached[n]);
  12906. this.add(input);
  12907. }
  12908. }
  12909. }
  12910. };
  12911. return CameraInputsManager;
  12912. })();
  12913. BABYLON.CameraInputsManager = CameraInputsManager;
  12914. })(BABYLON || (BABYLON = {}));
  12915. var BABYLON;
  12916. (function (BABYLON) {
  12917. var FreeCameraMouseInput = (function () {
  12918. function FreeCameraMouseInput(touchEnabled) {
  12919. if (touchEnabled === void 0) { touchEnabled = true; }
  12920. this.touchEnabled = touchEnabled;
  12921. this.angularSensibility = 2000.0;
  12922. }
  12923. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  12924. var _this = this;
  12925. if (!this._pointerInput) {
  12926. var camera = this.camera;
  12927. var engine = this.camera.getEngine();
  12928. this._pointerInput = function (p, s) {
  12929. var evt = p.event;
  12930. if (!_this.touchEnabled && evt.pointerType === "touch") {
  12931. return;
  12932. }
  12933. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12934. try {
  12935. evt.srcElement.setPointerCapture(evt.pointerId);
  12936. }
  12937. catch (e) {
  12938. }
  12939. _this.previousPosition = {
  12940. x: evt.clientX,
  12941. y: evt.clientY
  12942. };
  12943. if (!noPreventDefault) {
  12944. evt.preventDefault();
  12945. element.focus();
  12946. }
  12947. }
  12948. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12949. try {
  12950. evt.srcElement.releasePointerCapture(evt.pointerId);
  12951. }
  12952. catch (e) {
  12953. }
  12954. _this.previousPosition = null;
  12955. if (!noPreventDefault) {
  12956. evt.preventDefault();
  12957. }
  12958. }
  12959. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12960. if (!_this.previousPosition && !engine.isPointerLock) {
  12961. return;
  12962. }
  12963. var offsetX;
  12964. var offsetY;
  12965. if (!engine.isPointerLock) {
  12966. offsetX = evt.clientX - _this.previousPosition.x;
  12967. offsetY = evt.clientY - _this.previousPosition.y;
  12968. }
  12969. else {
  12970. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12971. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12972. }
  12973. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  12974. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  12975. _this.previousPosition = {
  12976. x: evt.clientX,
  12977. y: evt.clientY
  12978. };
  12979. if (!noPreventDefault) {
  12980. evt.preventDefault();
  12981. }
  12982. }
  12983. };
  12984. }
  12985. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12986. };
  12987. FreeCameraMouseInput.prototype.detachControl = function (element) {
  12988. if (this._observer && element) {
  12989. this.camera.getScene().onPointerObservable.remove(this._observer);
  12990. this._observer = null;
  12991. this.previousPosition = null;
  12992. }
  12993. };
  12994. FreeCameraMouseInput.prototype.getTypeName = function () {
  12995. return "FreeCameraMouseInput";
  12996. };
  12997. FreeCameraMouseInput.prototype.getSimpleName = function () {
  12998. return "mouse";
  12999. };
  13000. __decorate([
  13001. BABYLON.serialize()
  13002. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  13003. return FreeCameraMouseInput;
  13004. })();
  13005. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  13006. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  13007. })(BABYLON || (BABYLON = {}));
  13008. var BABYLON;
  13009. (function (BABYLON) {
  13010. var FreeCameraKeyboardMoveInput = (function () {
  13011. function FreeCameraKeyboardMoveInput() {
  13012. this._keys = [];
  13013. this.keysUp = [38];
  13014. this.keysDown = [40];
  13015. this.keysLeft = [37];
  13016. this.keysRight = [39];
  13017. }
  13018. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13019. var _this = this;
  13020. if (!this._onKeyDown) {
  13021. element.tabIndex = 1;
  13022. this._onKeyDown = function (evt) {
  13023. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13024. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13025. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13026. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13027. var index = _this._keys.indexOf(evt.keyCode);
  13028. if (index === -1) {
  13029. _this._keys.push(evt.keyCode);
  13030. }
  13031. if (!noPreventDefault) {
  13032. evt.preventDefault();
  13033. }
  13034. }
  13035. };
  13036. this._onKeyUp = function (evt) {
  13037. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13038. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13039. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13040. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13041. var index = _this._keys.indexOf(evt.keyCode);
  13042. if (index >= 0) {
  13043. _this._keys.splice(index, 1);
  13044. }
  13045. if (!noPreventDefault) {
  13046. evt.preventDefault();
  13047. }
  13048. }
  13049. };
  13050. element.addEventListener("keydown", this._onKeyDown, false);
  13051. element.addEventListener("keyup", this._onKeyUp, false);
  13052. BABYLON.Tools.RegisterTopRootEvents([
  13053. { name: "blur", handler: this._onLostFocus }
  13054. ]);
  13055. }
  13056. };
  13057. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13058. if (this._onKeyDown) {
  13059. element.removeEventListener("keydown", this._onKeyDown);
  13060. element.removeEventListener("keyup", this._onKeyUp);
  13061. BABYLON.Tools.UnregisterTopRootEvents([
  13062. { name: "blur", handler: this._onLostFocus }
  13063. ]);
  13064. this._keys = [];
  13065. this._onKeyDown = null;
  13066. this._onKeyUp = null;
  13067. }
  13068. };
  13069. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13070. if (this._onKeyDown) {
  13071. var camera = this.camera;
  13072. // Keyboard
  13073. for (var index = 0; index < this._keys.length; index++) {
  13074. var keyCode = this._keys[index];
  13075. var speed = camera._computeLocalCameraSpeed();
  13076. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13077. camera._localDirection.copyFromFloats(-speed, 0, 0);
  13078. }
  13079. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13080. camera._localDirection.copyFromFloats(0, 0, speed);
  13081. }
  13082. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13083. camera._localDirection.copyFromFloats(speed, 0, 0);
  13084. }
  13085. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13086. camera._localDirection.copyFromFloats(0, 0, -speed);
  13087. }
  13088. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  13089. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  13090. camera.cameraDirection.addInPlace(camera._transformedDirection);
  13091. }
  13092. }
  13093. };
  13094. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13095. return "FreeCameraKeyboardMoveInput";
  13096. };
  13097. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  13098. this._keys = [];
  13099. };
  13100. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13101. return "keyboard";
  13102. };
  13103. __decorate([
  13104. BABYLON.serialize()
  13105. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13106. __decorate([
  13107. BABYLON.serialize()
  13108. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13109. __decorate([
  13110. BABYLON.serialize()
  13111. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13112. __decorate([
  13113. BABYLON.serialize()
  13114. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13115. return FreeCameraKeyboardMoveInput;
  13116. })();
  13117. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  13118. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  13119. })(BABYLON || (BABYLON = {}));
  13120. var BABYLON;
  13121. (function (BABYLON) {
  13122. var FreeCameraTouchInput = (function () {
  13123. function FreeCameraTouchInput() {
  13124. this._offsetX = null;
  13125. this._offsetY = null;
  13126. this._pointerCount = 0;
  13127. this._pointerPressed = [];
  13128. this.touchAngularSensibility = 200000.0;
  13129. this.touchMoveSensibility = 250.0;
  13130. }
  13131. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  13132. var _this = this;
  13133. var previousPosition;
  13134. if (this._pointerInput === undefined) {
  13135. this._onLostFocus = function (evt) {
  13136. _this._offsetX = null;
  13137. _this._offsetY = null;
  13138. };
  13139. this._pointerInput = function (p, s) {
  13140. var evt = p.event;
  13141. if (evt.pointerType === "mouse") {
  13142. return;
  13143. }
  13144. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13145. if (!noPreventDefault) {
  13146. evt.preventDefault();
  13147. }
  13148. _this._pointerPressed.push(evt.pointerId);
  13149. if (_this._pointerPressed.length !== 1) {
  13150. return;
  13151. }
  13152. previousPosition = {
  13153. x: evt.clientX,
  13154. y: evt.clientY
  13155. };
  13156. }
  13157. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13158. if (!noPreventDefault) {
  13159. evt.preventDefault();
  13160. }
  13161. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13162. if (index === -1) {
  13163. return;
  13164. }
  13165. _this._pointerPressed.splice(index, 1);
  13166. if (index != 0) {
  13167. return;
  13168. }
  13169. previousPosition = null;
  13170. _this._offsetX = null;
  13171. _this._offsetY = null;
  13172. }
  13173. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13174. if (!noPreventDefault) {
  13175. evt.preventDefault();
  13176. }
  13177. if (!previousPosition) {
  13178. return;
  13179. }
  13180. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13181. if (index != 0) {
  13182. return;
  13183. }
  13184. _this._offsetX = evt.clientX - previousPosition.x;
  13185. _this._offsetY = -(evt.clientY - previousPosition.y);
  13186. }
  13187. };
  13188. }
  13189. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13190. element.addEventListener("blur", this._onLostFocus);
  13191. };
  13192. FreeCameraTouchInput.prototype.detachControl = function (element) {
  13193. if (this._pointerInput && element) {
  13194. this.camera.getScene().onPointerObservable.remove(this._observer);
  13195. this._observer = null;
  13196. element.removeEventListener("blur", this._onLostFocus);
  13197. this._onLostFocus = null;
  13198. this._pointerPressed = [];
  13199. this._offsetX = null;
  13200. this._offsetY = null;
  13201. this._pointerCount = 0;
  13202. }
  13203. };
  13204. FreeCameraTouchInput.prototype.checkInputs = function () {
  13205. if (this._offsetX) {
  13206. var camera = this.camera;
  13207. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  13208. if (this._pointerPressed.length > 1) {
  13209. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  13210. }
  13211. else {
  13212. var speed = camera._computeLocalCameraSpeed();
  13213. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  13214. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  13215. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  13216. }
  13217. }
  13218. };
  13219. FreeCameraTouchInput.prototype.getTypeName = function () {
  13220. return "FreeCameraTouchInput";
  13221. };
  13222. FreeCameraTouchInput.prototype.getSimpleName = function () {
  13223. return "touch";
  13224. };
  13225. __decorate([
  13226. BABYLON.serialize()
  13227. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  13228. __decorate([
  13229. BABYLON.serialize()
  13230. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  13231. return FreeCameraTouchInput;
  13232. })();
  13233. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  13234. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  13235. })(BABYLON || (BABYLON = {}));
  13236. var BABYLON;
  13237. (function (BABYLON) {
  13238. var FreeCameraDeviceOrientationInput = (function () {
  13239. function FreeCameraDeviceOrientationInput() {
  13240. var _this = this;
  13241. this._screenOrientationAngle = 0;
  13242. this._screenQuaternion = new BABYLON.Quaternion();
  13243. this._alpha = 0;
  13244. this._beta = 0;
  13245. this._gamma = 0;
  13246. this._orientationChanged = function () {
  13247. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  13248. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  13249. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  13250. };
  13251. this._deviceOrientation = function (evt) {
  13252. _this._alpha = evt.alpha;
  13253. _this._beta = evt.beta;
  13254. _this._gamma = evt.gamma;
  13255. };
  13256. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  13257. this._orientationChanged();
  13258. }
  13259. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  13260. get: function () {
  13261. return this._camera;
  13262. },
  13263. set: function (camera) {
  13264. this._camera = camera;
  13265. if (!this._camera.rotationQuaternion)
  13266. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  13267. },
  13268. enumerable: true,
  13269. configurable: true
  13270. });
  13271. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13272. window.addEventListener("orientationchange", this._orientationChanged);
  13273. window.addEventListener("deviceorientation", this._deviceOrientation);
  13274. };
  13275. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  13276. window.removeEventListener("orientationchange", this._orientationChanged);
  13277. window.removeEventListener("deviceorientation", this._deviceOrientation);
  13278. };
  13279. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  13280. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  13281. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  13282. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  13283. //Mirror on XY Plane
  13284. this._camera.rotationQuaternion.z *= -1;
  13285. this._camera.rotationQuaternion.w *= -1;
  13286. };
  13287. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  13288. return "FreeCameraDeviceOrientationInput";
  13289. };
  13290. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  13291. return "deviceOrientation";
  13292. };
  13293. return FreeCameraDeviceOrientationInput;
  13294. })();
  13295. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  13296. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  13297. })(BABYLON || (BABYLON = {}));
  13298. var BABYLON;
  13299. (function (BABYLON) {
  13300. var FreeCameraGamepadInput = (function () {
  13301. function FreeCameraGamepadInput() {
  13302. this.gamepadAngularSensibility = 200;
  13303. this.gamepadMoveSensibility = 40;
  13304. }
  13305. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13306. var _this = this;
  13307. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13308. };
  13309. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  13310. if (this._gamepads) {
  13311. this._gamepads.dispose();
  13312. }
  13313. this.gamepad = null;
  13314. };
  13315. FreeCameraGamepadInput.prototype.checkInputs = function () {
  13316. if (this.gamepad) {
  13317. var camera = this.camera;
  13318. var LSValues = this.gamepad.leftStick;
  13319. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  13320. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13321. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  13322. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  13323. var RSValues = this.gamepad.rightStick;
  13324. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  13325. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  13326. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  13327. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  13328. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  13329. var speed = camera._computeLocalCameraSpeed() * 50.0;
  13330. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  13331. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  13332. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  13333. }
  13334. };
  13335. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13336. // Only the first gamepad can control the camera
  13337. if (gamepad.index === 0) {
  13338. this.gamepad = gamepad;
  13339. }
  13340. };
  13341. FreeCameraGamepadInput.prototype.getTypeName = function () {
  13342. return "FreeCameraGamepadInput";
  13343. };
  13344. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  13345. return "gamepad";
  13346. };
  13347. __decorate([
  13348. BABYLON.serialize()
  13349. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  13350. __decorate([
  13351. BABYLON.serialize()
  13352. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13353. return FreeCameraGamepadInput;
  13354. })();
  13355. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  13356. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  13357. })(BABYLON || (BABYLON = {}));
  13358. var BABYLON;
  13359. (function (BABYLON) {
  13360. var ArcRotateCameraKeyboardMoveInput = (function () {
  13361. function ArcRotateCameraKeyboardMoveInput() {
  13362. this._keys = [];
  13363. this.keysUp = [38];
  13364. this.keysDown = [40];
  13365. this.keysLeft = [37];
  13366. this.keysRight = [39];
  13367. }
  13368. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13369. var _this = this;
  13370. element.tabIndex = 1;
  13371. this._onKeyDown = function (evt) {
  13372. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13373. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13374. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13375. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13376. var index = _this._keys.indexOf(evt.keyCode);
  13377. if (index === -1) {
  13378. _this._keys.push(evt.keyCode);
  13379. }
  13380. if (evt.preventDefault) {
  13381. if (!noPreventDefault) {
  13382. evt.preventDefault();
  13383. }
  13384. }
  13385. }
  13386. };
  13387. this._onKeyUp = function (evt) {
  13388. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13389. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13390. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13391. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13392. var index = _this._keys.indexOf(evt.keyCode);
  13393. if (index >= 0) {
  13394. _this._keys.splice(index, 1);
  13395. }
  13396. if (evt.preventDefault) {
  13397. if (!noPreventDefault) {
  13398. evt.preventDefault();
  13399. }
  13400. }
  13401. }
  13402. };
  13403. this._onLostFocus = function () {
  13404. _this._keys = [];
  13405. };
  13406. element.addEventListener("keydown", this._onKeyDown, false);
  13407. element.addEventListener("keyup", this._onKeyUp, false);
  13408. BABYLON.Tools.RegisterTopRootEvents([
  13409. { name: "blur", handler: this._onLostFocus }
  13410. ]);
  13411. };
  13412. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13413. if (element) {
  13414. element.removeEventListener("keydown", this._onKeyDown);
  13415. element.removeEventListener("keyup", this._onKeyUp);
  13416. }
  13417. BABYLON.Tools.UnregisterTopRootEvents([
  13418. { name: "blur", handler: this._onLostFocus }
  13419. ]);
  13420. this._keys = [];
  13421. this._onKeyDown = null;
  13422. this._onKeyUp = null;
  13423. this._onLostFocus = null;
  13424. };
  13425. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13426. if (this._onKeyDown) {
  13427. var camera = this.camera;
  13428. for (var index = 0; index < this._keys.length; index++) {
  13429. var keyCode = this._keys[index];
  13430. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13431. camera.inertialAlphaOffset -= 0.01;
  13432. }
  13433. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13434. camera.inertialBetaOffset -= 0.01;
  13435. }
  13436. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13437. camera.inertialAlphaOffset += 0.01;
  13438. }
  13439. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13440. camera.inertialBetaOffset += 0.01;
  13441. }
  13442. }
  13443. }
  13444. };
  13445. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13446. return "ArcRotateCameraKeyboardMoveInput";
  13447. };
  13448. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13449. return "keyboard";
  13450. };
  13451. __decorate([
  13452. BABYLON.serialize()
  13453. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13454. __decorate([
  13455. BABYLON.serialize()
  13456. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13457. __decorate([
  13458. BABYLON.serialize()
  13459. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13460. __decorate([
  13461. BABYLON.serialize()
  13462. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13463. return ArcRotateCameraKeyboardMoveInput;
  13464. })();
  13465. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  13466. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  13467. })(BABYLON || (BABYLON = {}));
  13468. var BABYLON;
  13469. (function (BABYLON) {
  13470. var ArcRotateCameraMouseWheelInput = (function () {
  13471. function ArcRotateCameraMouseWheelInput() {
  13472. this.wheelPrecision = 3.0;
  13473. }
  13474. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  13475. var _this = this;
  13476. this._wheel = function (p, s) {
  13477. //sanity check - this should be a PointerWheel event.
  13478. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  13479. return;
  13480. var event = p.event;
  13481. var delta = 0;
  13482. if (event.wheelDelta) {
  13483. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  13484. }
  13485. else if (event.detail) {
  13486. delta = -event.detail / _this.wheelPrecision;
  13487. }
  13488. if (delta)
  13489. _this.camera.inertialRadiusOffset += delta;
  13490. if (event.preventDefault) {
  13491. if (!noPreventDefault) {
  13492. event.preventDefault();
  13493. }
  13494. }
  13495. };
  13496. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  13497. };
  13498. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  13499. if (this._observer && element) {
  13500. this.camera.getScene().onPointerObservable.remove(this._observer);
  13501. this._observer = null;
  13502. this._wheel = null;
  13503. }
  13504. };
  13505. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  13506. return "ArcRotateCameraMouseWheelInput";
  13507. };
  13508. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  13509. return "mousewheel";
  13510. };
  13511. __decorate([
  13512. BABYLON.serialize()
  13513. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  13514. return ArcRotateCameraMouseWheelInput;
  13515. })();
  13516. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  13517. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  13518. })(BABYLON || (BABYLON = {}));
  13519. var BABYLON;
  13520. (function (BABYLON) {
  13521. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13522. var ArcRotateCameraPointersInput = (function () {
  13523. function ArcRotateCameraPointersInput() {
  13524. this.angularSensibilityX = 1000.0;
  13525. this.angularSensibilityY = 1000.0;
  13526. this.pinchPrecision = 6.0;
  13527. this.panningSensibility = 50.0;
  13528. this._isPanClick = false;
  13529. this.pinchInwards = true;
  13530. }
  13531. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  13532. var _this = this;
  13533. var engine = this.camera.getEngine();
  13534. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  13535. var pointA, pointB;
  13536. var previousPinchDistance = 0;
  13537. this._pointerInput = function (p, s) {
  13538. var evt = p.event;
  13539. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13540. try {
  13541. evt.srcElement.setPointerCapture(evt.pointerId);
  13542. }
  13543. catch (e) {
  13544. }
  13545. // Manage panning with pan button click
  13546. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  13547. // manage pointers
  13548. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  13549. if (pointA === undefined) {
  13550. pointA = cacheSoloPointer;
  13551. }
  13552. else if (pointB === undefined) {
  13553. pointB = cacheSoloPointer;
  13554. }
  13555. if (!noPreventDefault) {
  13556. evt.preventDefault();
  13557. element.focus();
  13558. }
  13559. }
  13560. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13561. try {
  13562. evt.srcElement.releasePointerCapture(evt.pointerId);
  13563. }
  13564. catch (e) {
  13565. }
  13566. cacheSoloPointer = null;
  13567. previousPinchDistance = 0;
  13568. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  13569. //but emptying completly pointers collection is required to fix a bug on iPhone :
  13570. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  13571. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  13572. pointA = pointB = undefined;
  13573. if (!noPreventDefault) {
  13574. evt.preventDefault();
  13575. }
  13576. }
  13577. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13578. if (!noPreventDefault) {
  13579. evt.preventDefault();
  13580. }
  13581. // One button down
  13582. if (pointA && pointB === undefined) {
  13583. if (_this.panningSensibility !== 0 &&
  13584. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  13585. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  13586. _this.camera
  13587. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  13588. _this.camera
  13589. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  13590. }
  13591. else {
  13592. var offsetX = evt.clientX - cacheSoloPointer.x;
  13593. var offsetY = evt.clientY - cacheSoloPointer.y;
  13594. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  13595. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  13596. }
  13597. cacheSoloPointer.x = evt.clientX;
  13598. cacheSoloPointer.y = evt.clientY;
  13599. }
  13600. else if (pointA && pointB) {
  13601. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  13602. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  13603. ed.x = evt.clientX;
  13604. ed.y = evt.clientY;
  13605. var direction = _this.pinchInwards ? 1 : -1;
  13606. var distX = pointA.x - pointB.x;
  13607. var distY = pointA.y - pointB.y;
  13608. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  13609. if (previousPinchDistance === 0) {
  13610. previousPinchDistance = pinchSquaredDistance;
  13611. return;
  13612. }
  13613. if (pinchSquaredDistance !== previousPinchDistance) {
  13614. _this.camera
  13615. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  13616. (_this.pinchPrecision *
  13617. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  13618. direction);
  13619. previousPinchDistance = pinchSquaredDistance;
  13620. }
  13621. }
  13622. }
  13623. };
  13624. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13625. this._onContextMenu = function (evt) {
  13626. evt.preventDefault();
  13627. };
  13628. if (!this.camera._useCtrlForPanning) {
  13629. element.addEventListener("contextmenu", this._onContextMenu, false);
  13630. }
  13631. this._onLostFocus = function () {
  13632. //this._keys = [];
  13633. pointA = pointB = undefined;
  13634. previousPinchDistance = 0;
  13635. cacheSoloPointer = null;
  13636. };
  13637. this._onMouseMove = function (evt) {
  13638. if (!engine.isPointerLock) {
  13639. return;
  13640. }
  13641. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13642. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13643. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  13644. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  13645. if (!noPreventDefault) {
  13646. evt.preventDefault();
  13647. }
  13648. };
  13649. this._onGestureStart = function (e) {
  13650. if (window.MSGesture === undefined) {
  13651. return;
  13652. }
  13653. if (!_this._MSGestureHandler) {
  13654. _this._MSGestureHandler = new MSGesture();
  13655. _this._MSGestureHandler.target = element;
  13656. }
  13657. _this._MSGestureHandler.addPointer(e.pointerId);
  13658. };
  13659. this._onGesture = function (e) {
  13660. _this.camera.radius *= e.scale;
  13661. if (e.preventDefault) {
  13662. if (!noPreventDefault) {
  13663. e.stopPropagation();
  13664. e.preventDefault();
  13665. }
  13666. }
  13667. };
  13668. element.addEventListener("mousemove", this._onMouseMove, false);
  13669. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  13670. element.addEventListener("MSGestureChange", this._onGesture, false);
  13671. element.addEventListener("keydown", this._onKeyDown, false);
  13672. element.addEventListener("keyup", this._onKeyUp, false);
  13673. BABYLON.Tools.RegisterTopRootEvents([
  13674. { name: "blur", handler: this._onLostFocus }
  13675. ]);
  13676. };
  13677. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  13678. if (element && this._observer) {
  13679. this.camera.getScene().onPointerObservable.remove(this._observer);
  13680. this._observer = null;
  13681. element.removeEventListener("contextmenu", this._onContextMenu);
  13682. element.removeEventListener("mousemove", this._onMouseMove);
  13683. element.removeEventListener("MSPointerDown", this._onGestureStart);
  13684. element.removeEventListener("MSGestureChange", this._onGesture);
  13685. element.removeEventListener("keydown", this._onKeyDown);
  13686. element.removeEventListener("keyup", this._onKeyUp);
  13687. this._isPanClick = false;
  13688. this.pinchInwards = true;
  13689. this._onKeyDown = null;
  13690. this._onKeyUp = null;
  13691. this._onMouseMove = null;
  13692. this._onGestureStart = null;
  13693. this._onGesture = null;
  13694. this._MSGestureHandler = null;
  13695. this._onLostFocus = null;
  13696. this._onContextMenu = null;
  13697. }
  13698. BABYLON.Tools.UnregisterTopRootEvents([
  13699. { name: "blur", handler: this._onLostFocus }
  13700. ]);
  13701. };
  13702. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  13703. return "ArcRotateCameraPointersInput";
  13704. };
  13705. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  13706. return "pointers";
  13707. };
  13708. __decorate([
  13709. BABYLON.serialize()
  13710. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  13711. __decorate([
  13712. BABYLON.serialize()
  13713. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  13714. __decorate([
  13715. BABYLON.serialize()
  13716. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  13717. __decorate([
  13718. BABYLON.serialize()
  13719. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  13720. return ArcRotateCameraPointersInput;
  13721. })();
  13722. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  13723. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  13724. })(BABYLON || (BABYLON = {}));
  13725. var BABYLON;
  13726. (function (BABYLON) {
  13727. var ArcRotateCameraGamepadInput = (function () {
  13728. function ArcRotateCameraGamepadInput() {
  13729. this.gamepadRotationSensibility = 80;
  13730. this.gamepadMoveSensibility = 40;
  13731. }
  13732. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13733. var _this = this;
  13734. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13735. };
  13736. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  13737. if (this._gamepads) {
  13738. this._gamepads.dispose();
  13739. }
  13740. this.gamepad = null;
  13741. };
  13742. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  13743. if (this.gamepad) {
  13744. var camera = this.camera;
  13745. var RSValues = this.gamepad.rightStick;
  13746. if (RSValues.x != 0) {
  13747. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  13748. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  13749. camera.inertialAlphaOffset += normalizedRX;
  13750. }
  13751. }
  13752. if (RSValues.y != 0) {
  13753. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  13754. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  13755. camera.inertialBetaOffset += normalizedRY;
  13756. }
  13757. }
  13758. var LSValues = this.gamepad.leftStick;
  13759. if (LSValues.y != 0) {
  13760. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13761. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  13762. this.camera.inertialRadiusOffset -= normalizedLY;
  13763. }
  13764. }
  13765. }
  13766. };
  13767. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13768. // Only the first gamepad can control the camera
  13769. if (gamepad.index === 0) {
  13770. this.gamepad = gamepad;
  13771. }
  13772. };
  13773. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  13774. return "ArcRotateCameraGamepadInput";
  13775. };
  13776. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  13777. return "gamepad";
  13778. };
  13779. __decorate([
  13780. BABYLON.serialize()
  13781. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  13782. __decorate([
  13783. BABYLON.serialize()
  13784. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13785. return ArcRotateCameraGamepadInput;
  13786. })();
  13787. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  13788. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  13789. })(BABYLON || (BABYLON = {}));
  13790. var BABYLON;
  13791. (function (BABYLON) {
  13792. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  13793. function ArcRotateCameraVRDeviceOrientationInput() {
  13794. this.alphaCorrection = 1;
  13795. this.betaCorrection = 1;
  13796. this.gammaCorrection = 1;
  13797. this._alpha = 0;
  13798. this._beta = 0;
  13799. this._gamma = 0;
  13800. this._dirty = false;
  13801. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  13802. }
  13803. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13804. this.camera.attachControl(element, noPreventDefault);
  13805. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  13806. };
  13807. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  13808. var camera = this.camera;
  13809. this._alpha = +evt.alpha | 0;
  13810. this._beta = +evt.beta | 0;
  13811. this._gamma = +evt.gamma | 0;
  13812. this._dirty = true;
  13813. };
  13814. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  13815. if (this._dirty) {
  13816. this._dirty = false;
  13817. if (this._gamma < 0) {
  13818. this._gamma = 180 + this._gamma;
  13819. }
  13820. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  13821. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  13822. }
  13823. };
  13824. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  13825. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  13826. };
  13827. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  13828. return "ArcRotateCameraVRDeviceOrientationInput";
  13829. };
  13830. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  13831. return "VRDeviceOrientation";
  13832. };
  13833. return ArcRotateCameraVRDeviceOrientationInput;
  13834. })();
  13835. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  13836. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  13837. })(BABYLON || (BABYLON = {}));
  13838. var BABYLON;
  13839. (function (BABYLON) {
  13840. var TargetCamera = (function (_super) {
  13841. __extends(TargetCamera, _super);
  13842. function TargetCamera(name, position, scene) {
  13843. _super.call(this, name, position, scene);
  13844. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13845. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13846. this.rotation = new BABYLON.Vector3(0, 0, 0);
  13847. this.speed = 2.0;
  13848. this.noRotationConstraint = false;
  13849. this.lockedTarget = null;
  13850. this._currentTarget = BABYLON.Vector3.Zero();
  13851. this._viewMatrix = BABYLON.Matrix.Zero();
  13852. this._camMatrix = BABYLON.Matrix.Zero();
  13853. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  13854. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  13855. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  13856. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  13857. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  13858. this._lookAtTemp = BABYLON.Matrix.Zero();
  13859. this._tempMatrix = BABYLON.Matrix.Zero();
  13860. }
  13861. TargetCamera.prototype.getFrontPosition = function (distance) {
  13862. var direction = this.getTarget().subtract(this.position);
  13863. direction.normalize();
  13864. direction.scaleInPlace(distance);
  13865. return this.globalPosition.add(direction);
  13866. };
  13867. TargetCamera.prototype._getLockedTargetPosition = function () {
  13868. if (!this.lockedTarget) {
  13869. return null;
  13870. }
  13871. return this.lockedTarget.position || this.lockedTarget;
  13872. };
  13873. // Cache
  13874. TargetCamera.prototype._initCache = function () {
  13875. _super.prototype._initCache.call(this);
  13876. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13877. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13878. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13879. };
  13880. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  13881. if (!ignoreParentClass) {
  13882. _super.prototype._updateCache.call(this);
  13883. }
  13884. var lockedTargetPosition = this._getLockedTargetPosition();
  13885. if (!lockedTargetPosition) {
  13886. this._cache.lockedTarget = null;
  13887. }
  13888. else {
  13889. if (!this._cache.lockedTarget) {
  13890. this._cache.lockedTarget = lockedTargetPosition.clone();
  13891. }
  13892. else {
  13893. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  13894. }
  13895. }
  13896. this._cache.rotation.copyFrom(this.rotation);
  13897. if (this.rotationQuaternion)
  13898. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13899. };
  13900. // Synchronized
  13901. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  13902. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  13903. return false;
  13904. }
  13905. var lockedTargetPosition = this._getLockedTargetPosition();
  13906. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  13907. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  13908. };
  13909. // Methods
  13910. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  13911. var engine = this.getEngine();
  13912. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  13913. };
  13914. // Target
  13915. TargetCamera.prototype.setTarget = function (target) {
  13916. this.upVector.normalize();
  13917. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  13918. this._camMatrix.invert();
  13919. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  13920. var vDir = target.subtract(this.position);
  13921. if (vDir.x >= 0.0) {
  13922. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  13923. }
  13924. else {
  13925. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  13926. }
  13927. this.rotation.z = 0;
  13928. if (isNaN(this.rotation.x)) {
  13929. this.rotation.x = 0;
  13930. }
  13931. if (isNaN(this.rotation.y)) {
  13932. this.rotation.y = 0;
  13933. }
  13934. if (isNaN(this.rotation.z)) {
  13935. this.rotation.z = 0;
  13936. }
  13937. if (this.rotationQuaternion) {
  13938. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  13939. }
  13940. };
  13941. TargetCamera.prototype.getTarget = function () {
  13942. return this._currentTarget;
  13943. };
  13944. TargetCamera.prototype._decideIfNeedsToMove = function () {
  13945. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13946. };
  13947. TargetCamera.prototype._updatePosition = function () {
  13948. this.position.addInPlace(this.cameraDirection);
  13949. };
  13950. TargetCamera.prototype._checkInputs = function () {
  13951. var needToMove = this._decideIfNeedsToMove();
  13952. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  13953. // Move
  13954. if (needToMove) {
  13955. this._updatePosition();
  13956. }
  13957. // Rotate
  13958. if (needToRotate) {
  13959. this.rotation.x += this.cameraRotation.x;
  13960. this.rotation.y += this.cameraRotation.y;
  13961. if (!this.noRotationConstraint) {
  13962. var limit = (Math.PI / 2) * 0.95;
  13963. if (this.rotation.x > limit)
  13964. this.rotation.x = limit;
  13965. if (this.rotation.x < -limit)
  13966. this.rotation.x = -limit;
  13967. }
  13968. }
  13969. // Inertia
  13970. if (needToMove) {
  13971. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  13972. this.cameraDirection.x = 0;
  13973. }
  13974. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  13975. this.cameraDirection.y = 0;
  13976. }
  13977. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  13978. this.cameraDirection.z = 0;
  13979. }
  13980. this.cameraDirection.scaleInPlace(this.inertia);
  13981. }
  13982. if (needToRotate) {
  13983. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  13984. this.cameraRotation.x = 0;
  13985. }
  13986. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  13987. this.cameraRotation.y = 0;
  13988. }
  13989. this.cameraRotation.scaleInPlace(this.inertia);
  13990. }
  13991. _super.prototype._checkInputs.call(this);
  13992. };
  13993. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  13994. if (this.rotationQuaternion) {
  13995. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  13996. //update the up vector!
  13997. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  13998. }
  13999. else {
  14000. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  14001. }
  14002. };
  14003. TargetCamera.prototype._getViewMatrix = function () {
  14004. if (!this.lockedTarget) {
  14005. // Compute
  14006. this._updateCameraRotationMatrix();
  14007. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  14008. // Computing target and final matrix
  14009. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  14010. }
  14011. else {
  14012. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  14013. }
  14014. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14015. return this._viewMatrix;
  14016. };
  14017. /**
  14018. * @override
  14019. * Override Camera.createRigCamera
  14020. */
  14021. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14022. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  14023. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  14024. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  14025. if (!this.rotationQuaternion) {
  14026. this.rotationQuaternion = new BABYLON.Quaternion();
  14027. }
  14028. rigCamera._cameraRigParams = {};
  14029. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  14030. }
  14031. return rigCamera;
  14032. }
  14033. return null;
  14034. };
  14035. /**
  14036. * @override
  14037. * Override Camera._updateRigCameras
  14038. */
  14039. TargetCamera.prototype._updateRigCameras = function () {
  14040. var camLeft = this._rigCameras[0];
  14041. var camRight = this._rigCameras[1];
  14042. switch (this.cameraRigMode) {
  14043. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14044. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14045. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14046. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14047. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  14048. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  14049. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  14050. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  14051. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  14052. camLeft.setTarget(this.getTarget());
  14053. camRight.setTarget(this.getTarget());
  14054. break;
  14055. case BABYLON.Camera.RIG_MODE_VR:
  14056. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14057. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14058. camLeft.position.copyFrom(this.position);
  14059. camRight.position.copyFrom(this.position);
  14060. break;
  14061. }
  14062. _super.prototype._updateRigCameras.call(this);
  14063. };
  14064. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  14065. if (!this._rigCamTransformMatrix) {
  14066. this._rigCamTransformMatrix = new BABYLON.Matrix();
  14067. }
  14068. var target = this.getTarget();
  14069. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  14070. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  14071. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  14072. };
  14073. TargetCamera.prototype.getTypeName = function () {
  14074. return "TargetCamera";
  14075. };
  14076. __decorate([
  14077. BABYLON.serializeAsVector3()
  14078. ], TargetCamera.prototype, "rotation", void 0);
  14079. __decorate([
  14080. BABYLON.serialize()
  14081. ], TargetCamera.prototype, "speed", void 0);
  14082. __decorate([
  14083. BABYLON.serializeAsMeshReference("lockedTargetId")
  14084. ], TargetCamera.prototype, "lockedTarget", void 0);
  14085. return TargetCamera;
  14086. })(BABYLON.Camera);
  14087. BABYLON.TargetCamera = TargetCamera;
  14088. })(BABYLON || (BABYLON = {}));
  14089. var BABYLON;
  14090. (function (BABYLON) {
  14091. var FreeCamera = (function (_super) {
  14092. __extends(FreeCamera, _super);
  14093. function FreeCamera(name, position, scene) {
  14094. var _this = this;
  14095. _super.call(this, name, position, scene);
  14096. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  14097. this.checkCollisions = false;
  14098. this.applyGravity = false;
  14099. this._collider = new BABYLON.Collider();
  14100. this._needMoveForGravity = false;
  14101. this._oldPosition = BABYLON.Vector3.Zero();
  14102. this._diffPosition = BABYLON.Vector3.Zero();
  14103. this._newPosition = BABYLON.Vector3.Zero();
  14104. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14105. if (collidedMesh === void 0) { collidedMesh = null; }
  14106. //TODO move this to the collision coordinator!
  14107. if (_this.getScene().workerCollisions)
  14108. newPosition.multiplyInPlace(_this._collider.radius);
  14109. var updatePosition = function (newPos) {
  14110. _this._newPosition.copyFrom(newPos);
  14111. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  14112. var oldPosition = _this.position.clone();
  14113. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  14114. _this.position.addInPlace(_this._diffPosition);
  14115. if (_this.onCollide && collidedMesh) {
  14116. _this.onCollide(collidedMesh);
  14117. }
  14118. }
  14119. };
  14120. updatePosition(newPosition);
  14121. };
  14122. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  14123. this.inputs.addKeyboard().addMouse();
  14124. }
  14125. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  14126. //-- begin properties for backward compatibility for inputs
  14127. get: function () {
  14128. var mouse = this.inputs.attached["mouse"];
  14129. if (mouse)
  14130. return mouse.angularSensibility;
  14131. },
  14132. set: function (value) {
  14133. var mouse = this.inputs.attached["mouse"];
  14134. if (mouse)
  14135. mouse.angularSensibility = value;
  14136. },
  14137. enumerable: true,
  14138. configurable: true
  14139. });
  14140. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  14141. get: function () {
  14142. var keyboard = this.inputs.attached["keyboard"];
  14143. if (keyboard)
  14144. return keyboard.keysUp;
  14145. },
  14146. set: function (value) {
  14147. var keyboard = this.inputs.attached["keyboard"];
  14148. if (keyboard)
  14149. keyboard.keysUp = value;
  14150. },
  14151. enumerable: true,
  14152. configurable: true
  14153. });
  14154. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  14155. get: function () {
  14156. var keyboard = this.inputs.attached["keyboard"];
  14157. if (keyboard)
  14158. return keyboard.keysDown;
  14159. },
  14160. set: function (value) {
  14161. var keyboard = this.inputs.attached["keyboard"];
  14162. if (keyboard)
  14163. keyboard.keysDown = value;
  14164. },
  14165. enumerable: true,
  14166. configurable: true
  14167. });
  14168. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  14169. get: function () {
  14170. var keyboard = this.inputs.attached["keyboard"];
  14171. if (keyboard)
  14172. return keyboard.keysLeft;
  14173. },
  14174. set: function (value) {
  14175. var keyboard = this.inputs.attached["keyboard"];
  14176. if (keyboard)
  14177. keyboard.keysLeft = value;
  14178. },
  14179. enumerable: true,
  14180. configurable: true
  14181. });
  14182. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  14183. get: function () {
  14184. var keyboard = this.inputs.attached["keyboard"];
  14185. if (keyboard)
  14186. return keyboard.keysRight;
  14187. },
  14188. set: function (value) {
  14189. var keyboard = this.inputs.attached["keyboard"];
  14190. if (keyboard)
  14191. keyboard.keysRight = value;
  14192. },
  14193. enumerable: true,
  14194. configurable: true
  14195. });
  14196. // Controls
  14197. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  14198. this.inputs.attachElement(element, noPreventDefault);
  14199. };
  14200. FreeCamera.prototype.detachControl = function (element) {
  14201. this.inputs.detachElement(element);
  14202. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14203. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14204. };
  14205. FreeCamera.prototype._collideWithWorld = function (velocity) {
  14206. var globalPosition;
  14207. if (this.parent) {
  14208. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  14209. }
  14210. else {
  14211. globalPosition = this.position;
  14212. }
  14213. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  14214. this._collider.radius = this.ellipsoid;
  14215. //no need for clone, as long as gravity is not on.
  14216. var actualVelocity = velocity;
  14217. //add gravity to the velocity to prevent the dual-collision checking
  14218. if (this.applyGravity) {
  14219. //this prevents mending with cameraDirection, a global variable of the free camera class.
  14220. actualVelocity = velocity.add(this.getScene().gravity);
  14221. }
  14222. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14223. };
  14224. FreeCamera.prototype._checkInputs = function () {
  14225. if (!this._localDirection) {
  14226. this._localDirection = BABYLON.Vector3.Zero();
  14227. this._transformedDirection = BABYLON.Vector3.Zero();
  14228. }
  14229. this.inputs.checkInputs();
  14230. _super.prototype._checkInputs.call(this);
  14231. };
  14232. FreeCamera.prototype._decideIfNeedsToMove = function () {
  14233. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14234. };
  14235. FreeCamera.prototype._updatePosition = function () {
  14236. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  14237. this._collideWithWorld(this.cameraDirection);
  14238. }
  14239. else {
  14240. this.position.addInPlace(this.cameraDirection);
  14241. }
  14242. };
  14243. FreeCamera.prototype.dispose = function () {
  14244. this.inputs.clear();
  14245. _super.prototype.dispose.call(this);
  14246. };
  14247. FreeCamera.prototype.getTypeName = function () {
  14248. return "FreeCamera";
  14249. };
  14250. __decorate([
  14251. BABYLON.serializeAsVector3()
  14252. ], FreeCamera.prototype, "ellipsoid", void 0);
  14253. __decorate([
  14254. BABYLON.serialize()
  14255. ], FreeCamera.prototype, "checkCollisions", void 0);
  14256. __decorate([
  14257. BABYLON.serialize()
  14258. ], FreeCamera.prototype, "applyGravity", void 0);
  14259. return FreeCamera;
  14260. })(BABYLON.TargetCamera);
  14261. BABYLON.FreeCamera = FreeCamera;
  14262. })(BABYLON || (BABYLON = {}));
  14263. var BABYLON;
  14264. (function (BABYLON) {
  14265. var FreeCameraInputsManager = (function (_super) {
  14266. __extends(FreeCameraInputsManager, _super);
  14267. function FreeCameraInputsManager(camera) {
  14268. _super.call(this, camera);
  14269. }
  14270. FreeCameraInputsManager.prototype.addKeyboard = function () {
  14271. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  14272. return this;
  14273. };
  14274. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  14275. if (touchEnabled === void 0) { touchEnabled = true; }
  14276. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  14277. return this;
  14278. };
  14279. FreeCameraInputsManager.prototype.addGamepad = function () {
  14280. this.add(new BABYLON.FreeCameraGamepadInput());
  14281. return this;
  14282. };
  14283. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  14284. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  14285. return this;
  14286. };
  14287. FreeCameraInputsManager.prototype.addTouch = function () {
  14288. this.add(new BABYLON.FreeCameraTouchInput());
  14289. return this;
  14290. };
  14291. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  14292. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  14293. return this;
  14294. };
  14295. return FreeCameraInputsManager;
  14296. })(BABYLON.CameraInputsManager);
  14297. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  14298. })(BABYLON || (BABYLON = {}));
  14299. var BABYLON;
  14300. (function (BABYLON) {
  14301. var FollowCamera = (function (_super) {
  14302. __extends(FollowCamera, _super);
  14303. function FollowCamera(name, position, scene, target) {
  14304. _super.call(this, name, position, scene);
  14305. this.radius = 12;
  14306. this.rotationOffset = 0;
  14307. this.heightOffset = 4;
  14308. this.cameraAcceleration = 0.05;
  14309. this.maxCameraSpeed = 20;
  14310. this.target = target;
  14311. }
  14312. FollowCamera.prototype.getRadians = function (degrees) {
  14313. return degrees * Math.PI / 180;
  14314. };
  14315. FollowCamera.prototype.follow = function (cameraTarget) {
  14316. if (!cameraTarget)
  14317. return;
  14318. var yRotation;
  14319. if (cameraTarget.rotationQuaternion) {
  14320. var rotMatrix = new BABYLON.Matrix();
  14321. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  14322. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  14323. }
  14324. else {
  14325. yRotation = cameraTarget.rotation.y;
  14326. }
  14327. var radians = this.getRadians(this.rotationOffset) + yRotation;
  14328. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  14329. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  14330. var dx = targetX - this.position.x;
  14331. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  14332. var dz = (targetZ) - this.position.z;
  14333. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  14334. var vy = dy * this.cameraAcceleration;
  14335. var vz = dz * this.cameraAcceleration * 2;
  14336. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  14337. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14338. }
  14339. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  14340. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14341. }
  14342. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  14343. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14344. }
  14345. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  14346. this.setTarget(cameraTarget.position);
  14347. };
  14348. FollowCamera.prototype._checkInputs = function () {
  14349. _super.prototype._checkInputs.call(this);
  14350. this.follow(this.target);
  14351. };
  14352. FollowCamera.prototype.getTypeName = function () {
  14353. return "FollowCamera";
  14354. };
  14355. __decorate([
  14356. BABYLON.serialize()
  14357. ], FollowCamera.prototype, "radius", void 0);
  14358. __decorate([
  14359. BABYLON.serialize()
  14360. ], FollowCamera.prototype, "rotationOffset", void 0);
  14361. __decorate([
  14362. BABYLON.serialize()
  14363. ], FollowCamera.prototype, "heightOffset", void 0);
  14364. __decorate([
  14365. BABYLON.serialize()
  14366. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  14367. __decorate([
  14368. BABYLON.serialize()
  14369. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  14370. __decorate([
  14371. BABYLON.serializeAsMeshReference("lockedTargetId")
  14372. ], FollowCamera.prototype, "target", void 0);
  14373. return FollowCamera;
  14374. })(BABYLON.TargetCamera);
  14375. BABYLON.FollowCamera = FollowCamera;
  14376. var ArcFollowCamera = (function (_super) {
  14377. __extends(ArcFollowCamera, _super);
  14378. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  14379. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14380. this.alpha = alpha;
  14381. this.beta = beta;
  14382. this.radius = radius;
  14383. this.target = target;
  14384. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  14385. this.follow();
  14386. }
  14387. ArcFollowCamera.prototype.follow = function () {
  14388. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  14389. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  14390. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  14391. this.position = this.target.position.add(this._cartesianCoordinates);
  14392. this.setTarget(this.target.position);
  14393. };
  14394. ArcFollowCamera.prototype._checkInputs = function () {
  14395. _super.prototype._checkInputs.call(this);
  14396. this.follow();
  14397. };
  14398. ArcFollowCamera.prototype.getTypeName = function () {
  14399. return "ArcFollowCamera";
  14400. };
  14401. return ArcFollowCamera;
  14402. })(BABYLON.TargetCamera);
  14403. BABYLON.ArcFollowCamera = ArcFollowCamera;
  14404. })(BABYLON || (BABYLON = {}));
  14405. var BABYLON;
  14406. (function (BABYLON) {
  14407. // We're mainly based on the logic defined into the FreeCamera code
  14408. var TouchCamera = (function (_super) {
  14409. __extends(TouchCamera, _super);
  14410. //-- end properties for backward compatibility for inputs
  14411. function TouchCamera(name, position, scene) {
  14412. _super.call(this, name, position, scene);
  14413. this.inputs.addTouch();
  14414. this._setupInputs();
  14415. }
  14416. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  14417. //-- Begin properties for backward compatibility for inputs
  14418. get: function () {
  14419. var touch = this.inputs.attached["touch"];
  14420. if (touch)
  14421. return touch.touchAngularSensibility;
  14422. },
  14423. set: function (value) {
  14424. var touch = this.inputs.attached["touch"];
  14425. if (touch)
  14426. touch.touchAngularSensibility = value;
  14427. },
  14428. enumerable: true,
  14429. configurable: true
  14430. });
  14431. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  14432. get: function () {
  14433. var touch = this.inputs.attached["touch"];
  14434. if (touch)
  14435. return touch.touchMoveSensibility;
  14436. },
  14437. set: function (value) {
  14438. var touch = this.inputs.attached["touch"];
  14439. if (touch)
  14440. touch.touchMoveSensibility = value;
  14441. },
  14442. enumerable: true,
  14443. configurable: true
  14444. });
  14445. TouchCamera.prototype.getTypeName = function () {
  14446. return "TouchCamera";
  14447. };
  14448. TouchCamera.prototype._setupInputs = function () {
  14449. var mouse = this.inputs.attached["mouse"];
  14450. if (mouse) {
  14451. mouse.touchEnabled = false;
  14452. }
  14453. };
  14454. return TouchCamera;
  14455. })(BABYLON.FreeCamera);
  14456. BABYLON.TouchCamera = TouchCamera;
  14457. })(BABYLON || (BABYLON = {}));
  14458. var BABYLON;
  14459. (function (BABYLON) {
  14460. var ArcRotateCamera = (function (_super) {
  14461. __extends(ArcRotateCamera, _super);
  14462. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  14463. var _this = this;
  14464. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14465. this.inertialAlphaOffset = 0;
  14466. this.inertialBetaOffset = 0;
  14467. this.inertialRadiusOffset = 0;
  14468. this.lowerAlphaLimit = null;
  14469. this.upperAlphaLimit = null;
  14470. this.lowerBetaLimit = 0.01;
  14471. this.upperBetaLimit = Math.PI;
  14472. this.lowerRadiusLimit = null;
  14473. this.upperRadiusLimit = null;
  14474. this.inertialPanningX = 0;
  14475. this.inertialPanningY = 0;
  14476. //-- end properties for backward compatibility for inputs
  14477. this.zoomOnFactor = 1;
  14478. this.targetScreenOffset = BABYLON.Vector2.Zero();
  14479. this.allowUpsideDown = true;
  14480. this._viewMatrix = new BABYLON.Matrix();
  14481. // Panning
  14482. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  14483. this.checkCollisions = false;
  14484. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14485. this._collider = new BABYLON.Collider();
  14486. this._previousPosition = BABYLON.Vector3.Zero();
  14487. this._collisionVelocity = BABYLON.Vector3.Zero();
  14488. this._newPosition = BABYLON.Vector3.Zero();
  14489. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14490. if (collidedMesh === void 0) { collidedMesh = null; }
  14491. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  14492. newPosition.multiplyInPlace(_this._collider.radius);
  14493. }
  14494. if (!collidedMesh) {
  14495. _this._previousPosition.copyFrom(_this.position);
  14496. }
  14497. else {
  14498. _this.setPosition(newPosition);
  14499. if (_this.onCollide) {
  14500. _this.onCollide(collidedMesh);
  14501. }
  14502. }
  14503. // Recompute because of constraints
  14504. var cosa = Math.cos(_this.alpha);
  14505. var sina = Math.sin(_this.alpha);
  14506. var cosb = Math.cos(_this.beta);
  14507. var sinb = Math.sin(_this.beta);
  14508. if (sinb === 0) {
  14509. sinb = 0.0001;
  14510. }
  14511. var target = _this._getTargetPosition();
  14512. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  14513. _this.position.copyFrom(_this._newPosition);
  14514. var up = _this.upVector;
  14515. if (_this.allowUpsideDown && _this.beta < 0) {
  14516. up = up.clone();
  14517. up = up.negate();
  14518. }
  14519. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  14520. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  14521. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  14522. _this._collisionTriggered = false;
  14523. };
  14524. if (!target) {
  14525. this.target = BABYLON.Vector3.Zero();
  14526. }
  14527. else {
  14528. this.target = target;
  14529. }
  14530. this.alpha = alpha;
  14531. this.beta = beta;
  14532. this.radius = radius;
  14533. this.getViewMatrix();
  14534. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  14535. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  14536. }
  14537. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  14538. //-- begin properties for backward compatibility for inputs
  14539. get: function () {
  14540. var pointers = this.inputs.attached["pointers"];
  14541. if (pointers)
  14542. return pointers.angularSensibilityX;
  14543. },
  14544. set: function (value) {
  14545. var pointers = this.inputs.attached["pointers"];
  14546. if (pointers) {
  14547. pointers.angularSensibilityX = value;
  14548. }
  14549. },
  14550. enumerable: true,
  14551. configurable: true
  14552. });
  14553. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  14554. get: function () {
  14555. var pointers = this.inputs.attached["pointers"];
  14556. if (pointers)
  14557. return pointers.angularSensibilityY;
  14558. },
  14559. set: function (value) {
  14560. var pointers = this.inputs.attached["pointers"];
  14561. if (pointers) {
  14562. pointers.angularSensibilityY = value;
  14563. }
  14564. },
  14565. enumerable: true,
  14566. configurable: true
  14567. });
  14568. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  14569. get: function () {
  14570. var pointers = this.inputs.attached["pointers"];
  14571. if (pointers)
  14572. return pointers.pinchPrecision;
  14573. },
  14574. set: function (value) {
  14575. var pointers = this.inputs.attached["pointers"];
  14576. if (pointers) {
  14577. pointers.pinchPrecision = value;
  14578. }
  14579. },
  14580. enumerable: true,
  14581. configurable: true
  14582. });
  14583. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  14584. get: function () {
  14585. var pointers = this.inputs.attached["pointers"];
  14586. if (pointers)
  14587. return pointers.panningSensibility;
  14588. },
  14589. set: function (value) {
  14590. var pointers = this.inputs.attached["pointers"];
  14591. if (pointers) {
  14592. pointers.panningSensibility = value;
  14593. }
  14594. },
  14595. enumerable: true,
  14596. configurable: true
  14597. });
  14598. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  14599. get: function () {
  14600. var keyboard = this.inputs.attached["keyboard"];
  14601. if (keyboard)
  14602. return keyboard.keysUp;
  14603. },
  14604. set: function (value) {
  14605. var keyboard = this.inputs.attached["keyboard"];
  14606. if (keyboard)
  14607. keyboard.keysUp = value;
  14608. },
  14609. enumerable: true,
  14610. configurable: true
  14611. });
  14612. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  14613. get: function () {
  14614. var keyboard = this.inputs.attached["keyboard"];
  14615. if (keyboard)
  14616. return keyboard.keysDown;
  14617. },
  14618. set: function (value) {
  14619. var keyboard = this.inputs.attached["keyboard"];
  14620. if (keyboard)
  14621. keyboard.keysDown = value;
  14622. },
  14623. enumerable: true,
  14624. configurable: true
  14625. });
  14626. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  14627. get: function () {
  14628. var keyboard = this.inputs.attached["keyboard"];
  14629. if (keyboard)
  14630. return keyboard.keysLeft;
  14631. },
  14632. set: function (value) {
  14633. var keyboard = this.inputs.attached["keyboard"];
  14634. if (keyboard)
  14635. keyboard.keysLeft = value;
  14636. },
  14637. enumerable: true,
  14638. configurable: true
  14639. });
  14640. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  14641. get: function () {
  14642. var keyboard = this.inputs.attached["keyboard"];
  14643. if (keyboard)
  14644. return keyboard.keysRight;
  14645. },
  14646. set: function (value) {
  14647. var keyboard = this.inputs.attached["keyboard"];
  14648. if (keyboard)
  14649. keyboard.keysRight = value;
  14650. },
  14651. enumerable: true,
  14652. configurable: true
  14653. });
  14654. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  14655. get: function () {
  14656. var mousewheel = this.inputs.attached["mousewheel"];
  14657. if (mousewheel)
  14658. return mousewheel.wheelPrecision;
  14659. },
  14660. set: function (value) {
  14661. var mousewheel = this.inputs.attached["mousewheel"];
  14662. if (mousewheel)
  14663. mousewheel.wheelPrecision = value;
  14664. },
  14665. enumerable: true,
  14666. configurable: true
  14667. });
  14668. // Cache
  14669. ArcRotateCamera.prototype._initCache = function () {
  14670. _super.prototype._initCache.call(this);
  14671. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14672. this._cache.alpha = undefined;
  14673. this._cache.beta = undefined;
  14674. this._cache.radius = undefined;
  14675. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  14676. };
  14677. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  14678. if (!ignoreParentClass) {
  14679. _super.prototype._updateCache.call(this);
  14680. }
  14681. this._cache.target.copyFrom(this._getTargetPosition());
  14682. this._cache.alpha = this.alpha;
  14683. this._cache.beta = this.beta;
  14684. this._cache.radius = this.radius;
  14685. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  14686. };
  14687. ArcRotateCamera.prototype._getTargetPosition = function () {
  14688. if (this.target.getAbsolutePosition) {
  14689. return this.target.getAbsolutePosition();
  14690. }
  14691. return this.target;
  14692. };
  14693. // Synchronized
  14694. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  14695. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  14696. return false;
  14697. return this._cache.target.equals(this.target)
  14698. && this._cache.alpha === this.alpha
  14699. && this._cache.beta === this.beta
  14700. && this._cache.radius === this.radius
  14701. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  14702. };
  14703. // Methods
  14704. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  14705. var _this = this;
  14706. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  14707. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  14708. this._useCtrlForPanning = useCtrlForPanning;
  14709. this._panningMouseButton = panningMouseButton;
  14710. this.inputs.attachElement(element, noPreventDefault);
  14711. this._reset = function () {
  14712. _this.inertialAlphaOffset = 0;
  14713. _this.inertialBetaOffset = 0;
  14714. _this.inertialRadiusOffset = 0;
  14715. };
  14716. };
  14717. ArcRotateCamera.prototype.detachControl = function (element) {
  14718. this.inputs.detachElement(element);
  14719. if (this._reset) {
  14720. this._reset();
  14721. }
  14722. };
  14723. ArcRotateCamera.prototype._checkInputs = function () {
  14724. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  14725. if (this._collisionTriggered) {
  14726. return;
  14727. }
  14728. this.inputs.checkInputs();
  14729. // Inertia
  14730. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  14731. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  14732. this.beta += this.inertialBetaOffset;
  14733. this.radius -= this.inertialRadiusOffset;
  14734. this.inertialAlphaOffset *= this.inertia;
  14735. this.inertialBetaOffset *= this.inertia;
  14736. this.inertialRadiusOffset *= this.inertia;
  14737. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  14738. this.inertialAlphaOffset = 0;
  14739. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  14740. this.inertialBetaOffset = 0;
  14741. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  14742. this.inertialRadiusOffset = 0;
  14743. }
  14744. // Panning inertia
  14745. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  14746. if (!this._localDirection) {
  14747. this._localDirection = BABYLON.Vector3.Zero();
  14748. this._transformedDirection = BABYLON.Vector3.Zero();
  14749. }
  14750. this.inertialPanningX *= this.inertia;
  14751. this.inertialPanningY *= this.inertia;
  14752. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  14753. this.inertialPanningX = 0;
  14754. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  14755. this.inertialPanningY = 0;
  14756. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  14757. this._localDirection.multiplyInPlace(this.panningAxis);
  14758. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  14759. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  14760. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  14761. if (!this.panningAxis.y) {
  14762. this._transformedDirection.y = 0;
  14763. }
  14764. if (!this.target.getAbsolutePosition) {
  14765. this.target.addInPlace(this._transformedDirection);
  14766. }
  14767. }
  14768. // Limits
  14769. this._checkLimits();
  14770. _super.prototype._checkInputs.call(this);
  14771. };
  14772. ArcRotateCamera.prototype._checkLimits = function () {
  14773. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  14774. if (this.allowUpsideDown && this.beta > Math.PI) {
  14775. this.beta = this.beta - (2 * Math.PI);
  14776. }
  14777. }
  14778. else {
  14779. if (this.beta < this.lowerBetaLimit) {
  14780. this.beta = this.lowerBetaLimit;
  14781. }
  14782. }
  14783. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  14784. if (this.allowUpsideDown && this.beta < -Math.PI) {
  14785. this.beta = this.beta + (2 * Math.PI);
  14786. }
  14787. }
  14788. else {
  14789. if (this.beta > this.upperBetaLimit) {
  14790. this.beta = this.upperBetaLimit;
  14791. }
  14792. }
  14793. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  14794. this.alpha = this.lowerAlphaLimit;
  14795. }
  14796. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  14797. this.alpha = this.upperAlphaLimit;
  14798. }
  14799. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  14800. this.radius = this.lowerRadiusLimit;
  14801. }
  14802. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  14803. this.radius = this.upperRadiusLimit;
  14804. }
  14805. };
  14806. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  14807. var radiusv3 = this.position.subtract(this._getTargetPosition());
  14808. this.radius = radiusv3.length();
  14809. // Alpha
  14810. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  14811. if (radiusv3.z < 0) {
  14812. this.alpha = 2 * Math.PI - this.alpha;
  14813. }
  14814. // Beta
  14815. this.beta = Math.acos(radiusv3.y / this.radius);
  14816. this._checkLimits();
  14817. };
  14818. ArcRotateCamera.prototype.setPosition = function (position) {
  14819. if (this.position.equals(position)) {
  14820. return;
  14821. }
  14822. this.position.copyFrom(position);
  14823. this.rebuildAnglesAndRadius();
  14824. };
  14825. ArcRotateCamera.prototype.setTarget = function (target) {
  14826. if (this._getTargetPosition().equals(target)) {
  14827. return;
  14828. }
  14829. this.target = target;
  14830. this.rebuildAnglesAndRadius();
  14831. };
  14832. ArcRotateCamera.prototype._getViewMatrix = function () {
  14833. // Compute
  14834. var cosa = Math.cos(this.alpha);
  14835. var sina = Math.sin(this.alpha);
  14836. var cosb = Math.cos(this.beta);
  14837. var sinb = Math.sin(this.beta);
  14838. if (sinb === 0) {
  14839. sinb = 0.0001;
  14840. }
  14841. var target = this._getTargetPosition();
  14842. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  14843. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  14844. this._collider.radius = this.collisionRadius;
  14845. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  14846. this._collisionTriggered = true;
  14847. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14848. }
  14849. else {
  14850. this.position.copyFrom(this._newPosition);
  14851. var up = this.upVector;
  14852. if (this.allowUpsideDown && this.beta < 0) {
  14853. up = up.clone();
  14854. up = up.negate();
  14855. }
  14856. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  14857. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  14858. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  14859. }
  14860. return this._viewMatrix;
  14861. };
  14862. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  14863. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14864. meshes = meshes || this.getScene().meshes;
  14865. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  14866. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  14867. this.radius = distance * this.zoomOnFactor;
  14868. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  14869. };
  14870. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  14871. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14872. var meshesOrMinMaxVector;
  14873. var distance;
  14874. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  14875. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  14876. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  14877. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  14878. }
  14879. else {
  14880. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  14881. distance = meshesOrMinMaxVectorAndDistance.distance;
  14882. }
  14883. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  14884. if (!doNotUpdateMaxZ) {
  14885. this.maxZ = distance * 2;
  14886. }
  14887. };
  14888. /**
  14889. * @override
  14890. * Override Camera.createRigCamera
  14891. */
  14892. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14893. var alphaShift;
  14894. switch (this.cameraRigMode) {
  14895. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14896. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14897. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14898. case BABYLON.Camera.RIG_MODE_VR:
  14899. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  14900. break;
  14901. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14902. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  14903. break;
  14904. }
  14905. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  14906. rigCam._cameraRigParams = {};
  14907. return rigCam;
  14908. };
  14909. /**
  14910. * @override
  14911. * Override Camera._updateRigCameras
  14912. */
  14913. ArcRotateCamera.prototype._updateRigCameras = function () {
  14914. var camLeft = this._rigCameras[0];
  14915. var camRight = this._rigCameras[1];
  14916. camLeft.beta = camRight.beta = this.beta;
  14917. camLeft.radius = camRight.radius = this.radius;
  14918. switch (this.cameraRigMode) {
  14919. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14920. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14921. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14922. case BABYLON.Camera.RIG_MODE_VR:
  14923. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  14924. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  14925. break;
  14926. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14927. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  14928. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  14929. break;
  14930. }
  14931. _super.prototype._updateRigCameras.call(this);
  14932. };
  14933. ArcRotateCamera.prototype.dispose = function () {
  14934. this.inputs.clear();
  14935. _super.prototype.dispose.call(this);
  14936. };
  14937. ArcRotateCamera.prototype.getTypeName = function () {
  14938. return "ArcRotateCamera";
  14939. };
  14940. __decorate([
  14941. BABYLON.serialize()
  14942. ], ArcRotateCamera.prototype, "alpha", void 0);
  14943. __decorate([
  14944. BABYLON.serialize()
  14945. ], ArcRotateCamera.prototype, "beta", void 0);
  14946. __decorate([
  14947. BABYLON.serialize()
  14948. ], ArcRotateCamera.prototype, "radius", void 0);
  14949. __decorate([
  14950. BABYLON.serializeAsVector3()
  14951. ], ArcRotateCamera.prototype, "target", void 0);
  14952. __decorate([
  14953. BABYLON.serialize()
  14954. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  14955. __decorate([
  14956. BABYLON.serialize()
  14957. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  14958. __decorate([
  14959. BABYLON.serialize()
  14960. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  14961. __decorate([
  14962. BABYLON.serialize()
  14963. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  14964. __decorate([
  14965. BABYLON.serialize()
  14966. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  14967. __decorate([
  14968. BABYLON.serialize()
  14969. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  14970. __decorate([
  14971. BABYLON.serialize()
  14972. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  14973. __decorate([
  14974. BABYLON.serialize()
  14975. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  14976. __decorate([
  14977. BABYLON.serialize()
  14978. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  14979. __decorate([
  14980. BABYLON.serialize()
  14981. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  14982. __decorate([
  14983. BABYLON.serialize()
  14984. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  14985. __decorate([
  14986. BABYLON.serialize()
  14987. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  14988. __decorate([
  14989. BABYLON.serialize()
  14990. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  14991. return ArcRotateCamera;
  14992. })(BABYLON.TargetCamera);
  14993. BABYLON.ArcRotateCamera = ArcRotateCamera;
  14994. })(BABYLON || (BABYLON = {}));
  14995. var BABYLON;
  14996. (function (BABYLON) {
  14997. var ArcRotateCameraInputsManager = (function (_super) {
  14998. __extends(ArcRotateCameraInputsManager, _super);
  14999. function ArcRotateCameraInputsManager(camera) {
  15000. _super.call(this, camera);
  15001. }
  15002. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  15003. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  15004. return this;
  15005. };
  15006. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  15007. this.add(new BABYLON.ArcRotateCameraPointersInput());
  15008. return this;
  15009. };
  15010. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  15011. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  15012. return this;
  15013. };
  15014. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  15015. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  15016. return this;
  15017. };
  15018. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  15019. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  15020. return this;
  15021. };
  15022. return ArcRotateCameraInputsManager;
  15023. })(BABYLON.CameraInputsManager);
  15024. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  15025. })(BABYLON || (BABYLON = {}));
  15026. var BABYLON;
  15027. (function (BABYLON) {
  15028. var RenderingManager = (function () {
  15029. function RenderingManager(scene) {
  15030. this._renderingGroups = new Array();
  15031. this._autoClearDepthStencil = {};
  15032. this._customOpaqueSortCompareFn = {};
  15033. this._customAlphaTestSortCompareFn = {};
  15034. this._customTransparentSortCompareFn = {};
  15035. this._scene = scene;
  15036. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15037. this._autoClearDepthStencil[i] = true;
  15038. }
  15039. }
  15040. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  15041. if (this._scene._activeParticleSystems.length === 0) {
  15042. return;
  15043. }
  15044. // Particles
  15045. var activeCamera = this._scene.activeCamera;
  15046. this._scene._particlesDuration.beginMonitoring();
  15047. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15048. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15049. if (particleSystem.renderingGroupId !== index) {
  15050. continue;
  15051. }
  15052. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15053. continue;
  15054. }
  15055. this._clearDepthStencilBuffer();
  15056. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15057. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15058. }
  15059. }
  15060. this._scene._particlesDuration.endMonitoring(false);
  15061. };
  15062. RenderingManager.prototype._renderSprites = function (index) {
  15063. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  15064. return;
  15065. }
  15066. // Sprites
  15067. var activeCamera = this._scene.activeCamera;
  15068. this._scene._spritesDuration.beginMonitoring();
  15069. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  15070. var spriteManager = this._scene.spriteManagers[id];
  15071. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15072. this._clearDepthStencilBuffer();
  15073. spriteManager.render();
  15074. }
  15075. }
  15076. this._scene._spritesDuration.endMonitoring(false);
  15077. };
  15078. RenderingManager.prototype._clearDepthStencilBuffer = function () {
  15079. if (this._depthStencilBufferAlreadyCleaned) {
  15080. return;
  15081. }
  15082. this._scene.getEngine().clear(0, false, true, true);
  15083. this._depthStencilBufferAlreadyCleaned = true;
  15084. };
  15085. RenderingManager.prototype._renderSpritesAndParticles = function () {
  15086. if (this._currentRenderSprites) {
  15087. this._renderSprites(this._currentIndex);
  15088. }
  15089. if (this._currentRenderParticles) {
  15090. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  15091. }
  15092. };
  15093. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15094. this._currentActiveMeshes = activeMeshes;
  15095. this._currentRenderParticles = renderParticles;
  15096. this._currentRenderSprites = renderSprites;
  15097. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15098. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15099. var renderingGroup = this._renderingGroups[index];
  15100. var needToStepBack = false;
  15101. this._currentIndex = index;
  15102. if (renderingGroup) {
  15103. if (this._autoClearDepthStencil[index]) {
  15104. this._clearDepthStencilBuffer();
  15105. }
  15106. if (!renderingGroup.onBeforeTransparentRendering) {
  15107. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  15108. }
  15109. if (!renderingGroup.render(customRenderFunction)) {
  15110. this._renderingGroups.splice(index, 1);
  15111. needToStepBack = true;
  15112. this._renderSpritesAndParticles();
  15113. }
  15114. }
  15115. else {
  15116. this._renderSpritesAndParticles();
  15117. }
  15118. if (needToStepBack) {
  15119. index--;
  15120. }
  15121. }
  15122. };
  15123. RenderingManager.prototype.reset = function () {
  15124. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15125. var renderingGroup = this._renderingGroups[index];
  15126. if (renderingGroup) {
  15127. renderingGroup.prepare();
  15128. }
  15129. }
  15130. };
  15131. RenderingManager.prototype.dispatch = function (subMesh) {
  15132. var mesh = subMesh.getMesh();
  15133. var renderingGroupId = mesh.renderingGroupId || 0;
  15134. if (!this._renderingGroups[renderingGroupId]) {
  15135. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15136. }
  15137. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15138. };
  15139. /**
  15140. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15141. * This allowed control for front to back rendering or reversly depending of the special needs.
  15142. *
  15143. * @param renderingGroupId The rendering group id corresponding to its index
  15144. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15145. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15146. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15147. */
  15148. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15149. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15150. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15151. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15152. if (this._renderingGroups[renderingGroupId]) {
  15153. var group = this._renderingGroups[renderingGroupId];
  15154. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15155. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15156. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15157. }
  15158. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15159. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15160. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15161. };
  15162. /**
  15163. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15164. *
  15165. * @param renderingGroupId The rendering group id corresponding to its index
  15166. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15167. */
  15168. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  15169. this._autoClearDepthStencil[renderingGroupId] = autoClearDepthStencil;
  15170. };
  15171. /**
  15172. * The max id used for rendering groups (not included)
  15173. */
  15174. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15175. /**
  15176. * The min id used for rendering groups (included)
  15177. */
  15178. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15179. return RenderingManager;
  15180. })();
  15181. BABYLON.RenderingManager = RenderingManager;
  15182. })(BABYLON || (BABYLON = {}));
  15183. var BABYLON;
  15184. (function (BABYLON) {
  15185. var RenderingGroup = (function () {
  15186. /**
  15187. * Creates a new rendering group.
  15188. * @param index The rendering group index
  15189. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15190. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15191. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15192. */
  15193. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15194. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15195. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15196. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15197. this.index = index;
  15198. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15199. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15200. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15201. this._scene = scene;
  15202. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15203. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15204. this.transparentSortCompareFn = transparentSortCompareFn;
  15205. }
  15206. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15207. /**
  15208. * Set the opaque sort comparison function.
  15209. * If null the sub meshes will be render in the order they were created
  15210. */
  15211. set: function (value) {
  15212. this._opaqueSortCompareFn = value;
  15213. if (value) {
  15214. this._renderOpaque = this.renderOpaqueSorted;
  15215. }
  15216. else {
  15217. this._renderOpaque = RenderingGroup.renderUnsorted;
  15218. }
  15219. },
  15220. enumerable: true,
  15221. configurable: true
  15222. });
  15223. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15224. /**
  15225. * Set the alpha test sort comparison function.
  15226. * If null the sub meshes will be render in the order they were created
  15227. */
  15228. set: function (value) {
  15229. this._alphaTestSortCompareFn = value;
  15230. if (value) {
  15231. this._renderAlphaTest = this.renderAlphaTestSorted;
  15232. }
  15233. else {
  15234. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15235. }
  15236. },
  15237. enumerable: true,
  15238. configurable: true
  15239. });
  15240. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15241. /**
  15242. * Set the transparent sort comparison function.
  15243. * If null the sub meshes will be render in the order they were created
  15244. */
  15245. set: function (value) {
  15246. if (value) {
  15247. this._transparentSortCompareFn = value;
  15248. }
  15249. else {
  15250. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15251. }
  15252. this._renderTransparent = this.renderTransparentSorted;
  15253. },
  15254. enumerable: true,
  15255. configurable: true
  15256. });
  15257. /**
  15258. * Render all the sub meshes contained in the group.
  15259. * @param customRenderFunction Used to override the default render behaviour of the group.
  15260. * @returns true if rendered some submeshes.
  15261. */
  15262. RenderingGroup.prototype.render = function (customRenderFunction) {
  15263. if (customRenderFunction) {
  15264. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15265. return true;
  15266. }
  15267. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  15268. if (this.onBeforeTransparentRendering) {
  15269. this.onBeforeTransparentRendering();
  15270. }
  15271. return false;
  15272. }
  15273. var engine = this._scene.getEngine();
  15274. // Opaque
  15275. this._renderOpaque(this._opaqueSubMeshes);
  15276. // Alpha test
  15277. engine.setAlphaTesting(true);
  15278. this._renderAlphaTest(this._alphaTestSubMeshes);
  15279. engine.setAlphaTesting(false);
  15280. if (this.onBeforeTransparentRendering) {
  15281. this.onBeforeTransparentRendering();
  15282. }
  15283. // Transparent
  15284. this._renderTransparent(this._transparentSubMeshes);
  15285. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15286. return true;
  15287. };
  15288. /**
  15289. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15290. * @param subMeshes The submeshes to render
  15291. */
  15292. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15293. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15294. };
  15295. /**
  15296. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15297. * @param subMeshes The submeshes to render
  15298. */
  15299. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15300. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15301. };
  15302. /**
  15303. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15304. * @param subMeshes The submeshes to render
  15305. */
  15306. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15307. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15308. };
  15309. /**
  15310. * Renders the submeshes in a specified order.
  15311. * @param subMeshes The submeshes to sort before render
  15312. * @param sortCompareFn The comparison function use to sort
  15313. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15314. * @param transparent Specifies to activate blending if true
  15315. */
  15316. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15317. var subIndex = 0;
  15318. var subMesh;
  15319. for (; subIndex < subMeshes.length; subIndex++) {
  15320. subMesh = subMeshes.data[subIndex];
  15321. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15322. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15323. }
  15324. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15325. sortedArray.sort(sortCompareFn);
  15326. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15327. subMesh = sortedArray[subIndex];
  15328. subMesh.render(transparent);
  15329. }
  15330. };
  15331. /**
  15332. * Renders the submeshes in the order they were dispatched (no sort applied).
  15333. * @param subMeshes The submeshes to render
  15334. */
  15335. RenderingGroup.renderUnsorted = function (subMeshes) {
  15336. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15337. var submesh = subMeshes.data[subIndex];
  15338. submesh.render(false);
  15339. }
  15340. };
  15341. /**
  15342. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15343. * are rendered back to front if in the same alpha index.
  15344. *
  15345. * @param a The first submesh
  15346. * @param b The second submesh
  15347. * @returns The result of the comparison
  15348. */
  15349. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15350. // Alpha index first
  15351. if (a._alphaIndex > b._alphaIndex) {
  15352. return 1;
  15353. }
  15354. if (a._alphaIndex < b._alphaIndex) {
  15355. return -1;
  15356. }
  15357. // Then distance to camera
  15358. return RenderingGroup.backToFrontSortCompare(a, b);
  15359. };
  15360. /**
  15361. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15362. * are rendered back to front.
  15363. *
  15364. * @param a The first submesh
  15365. * @param b The second submesh
  15366. * @returns The result of the comparison
  15367. */
  15368. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15369. // Then distance to camera
  15370. if (a._distanceToCamera < b._distanceToCamera) {
  15371. return 1;
  15372. }
  15373. if (a._distanceToCamera > b._distanceToCamera) {
  15374. return -1;
  15375. }
  15376. return 0;
  15377. };
  15378. /**
  15379. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15380. * are rendered front to back (prevent overdraw).
  15381. *
  15382. * @param a The first submesh
  15383. * @param b The second submesh
  15384. * @returns The result of the comparison
  15385. */
  15386. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15387. // Then distance to camera
  15388. if (a._distanceToCamera < b._distanceToCamera) {
  15389. return -1;
  15390. }
  15391. if (a._distanceToCamera > b._distanceToCamera) {
  15392. return 1;
  15393. }
  15394. return 0;
  15395. };
  15396. /**
  15397. * Resets the different lists of submeshes to prepare a new frame.
  15398. */
  15399. RenderingGroup.prototype.prepare = function () {
  15400. this._opaqueSubMeshes.reset();
  15401. this._transparentSubMeshes.reset();
  15402. this._alphaTestSubMeshes.reset();
  15403. };
  15404. /**
  15405. * Inserts the submesh in its correct queue depending on its material.
  15406. * @param subMesh The submesh to dispatch
  15407. */
  15408. RenderingGroup.prototype.dispatch = function (subMesh) {
  15409. var material = subMesh.getMaterial();
  15410. var mesh = subMesh.getMesh();
  15411. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15412. this._transparentSubMeshes.push(subMesh);
  15413. }
  15414. else if (material.needAlphaTesting()) {
  15415. this._alphaTestSubMeshes.push(subMesh);
  15416. }
  15417. else {
  15418. this._opaqueSubMeshes.push(subMesh); // Opaque
  15419. }
  15420. };
  15421. return RenderingGroup;
  15422. })();
  15423. BABYLON.RenderingGroup = RenderingGroup;
  15424. })(BABYLON || (BABYLON = {}));
  15425. var BABYLON;
  15426. (function (BABYLON) {
  15427. var PointerEventTypes = (function () {
  15428. function PointerEventTypes() {
  15429. }
  15430. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15431. get: function () {
  15432. return PointerEventTypes._POINTERDOWN;
  15433. },
  15434. enumerable: true,
  15435. configurable: true
  15436. });
  15437. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15438. get: function () {
  15439. return PointerEventTypes._POINTERUP;
  15440. },
  15441. enumerable: true,
  15442. configurable: true
  15443. });
  15444. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15445. get: function () {
  15446. return PointerEventTypes._POINTERMOVE;
  15447. },
  15448. enumerable: true,
  15449. configurable: true
  15450. });
  15451. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15452. get: function () {
  15453. return PointerEventTypes._POINTERWHEEL;
  15454. },
  15455. enumerable: true,
  15456. configurable: true
  15457. });
  15458. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15459. get: function () {
  15460. return PointerEventTypes._POINTERPICK;
  15461. },
  15462. enumerable: true,
  15463. configurable: true
  15464. });
  15465. PointerEventTypes._POINTERDOWN = 0x01;
  15466. PointerEventTypes._POINTERUP = 0x02;
  15467. PointerEventTypes._POINTERMOVE = 0x04;
  15468. PointerEventTypes._POINTERWHEEL = 0x08;
  15469. PointerEventTypes._POINTERPICK = 0x10;
  15470. return PointerEventTypes;
  15471. })();
  15472. BABYLON.PointerEventTypes = PointerEventTypes;
  15473. var PointerInfoBase = (function () {
  15474. function PointerInfoBase(type, event) {
  15475. this.type = type;
  15476. this.event = event;
  15477. }
  15478. return PointerInfoBase;
  15479. })();
  15480. BABYLON.PointerInfoBase = PointerInfoBase;
  15481. /**
  15482. * This class is used to store pointer related info for the onPrePointerObservable event.
  15483. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15484. */
  15485. var PointerInfoPre = (function (_super) {
  15486. __extends(PointerInfoPre, _super);
  15487. function PointerInfoPre(type, event, localX, localY) {
  15488. _super.call(this, type, event);
  15489. this.skipOnPointerObservable = false;
  15490. this.localPosition = new BABYLON.Vector2(localX, localY);
  15491. }
  15492. return PointerInfoPre;
  15493. })(PointerInfoBase);
  15494. BABYLON.PointerInfoPre = PointerInfoPre;
  15495. /**
  15496. * This type contains all the data related to a pointer event in Babylon.js.
  15497. * 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.
  15498. */
  15499. var PointerInfo = (function (_super) {
  15500. __extends(PointerInfo, _super);
  15501. function PointerInfo(type, event, pickInfo) {
  15502. _super.call(this, type, event);
  15503. this.pickInfo = pickInfo;
  15504. }
  15505. return PointerInfo;
  15506. })(PointerInfoBase);
  15507. BABYLON.PointerInfo = PointerInfo;
  15508. /**
  15509. * Represents a scene to be rendered by the engine.
  15510. * @see http://doc.babylonjs.com/page.php?p=21911
  15511. */
  15512. var Scene = (function () {
  15513. /**
  15514. * @constructor
  15515. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15516. */
  15517. function Scene(engine) {
  15518. // Members
  15519. this.autoClear = true;
  15520. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15521. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15522. this.forceWireframe = false;
  15523. this.forcePointsCloud = false;
  15524. this.forceShowBoundingBoxes = false;
  15525. this.animationsEnabled = true;
  15526. this.constantlyUpdateMeshUnderPointer = false;
  15527. this.hoverCursor = "pointer";
  15528. // Events
  15529. /**
  15530. * An event triggered when the scene is disposed.
  15531. * @type {BABYLON.Observable}
  15532. */
  15533. this.onDisposeObservable = new BABYLON.Observable();
  15534. /**
  15535. * An event triggered before rendering the scene
  15536. * @type {BABYLON.Observable}
  15537. */
  15538. this.onBeforeRenderObservable = new BABYLON.Observable();
  15539. /**
  15540. * An event triggered after rendering the scene
  15541. * @type {BABYLON.Observable}
  15542. */
  15543. this.onAfterRenderObservable = new BABYLON.Observable();
  15544. /**
  15545. * An event triggered when the scene is ready
  15546. * @type {BABYLON.Observable}
  15547. */
  15548. this.onReadyObservable = new BABYLON.Observable();
  15549. /**
  15550. * An event triggered before rendering a camera
  15551. * @type {BABYLON.Observable}
  15552. */
  15553. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15554. /**
  15555. * An event triggered after rendering a camera
  15556. * @type {BABYLON.Observable}
  15557. */
  15558. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15559. /**
  15560. * An event triggered when a camera is created
  15561. * @type {BABYLON.Observable}
  15562. */
  15563. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15564. /**
  15565. * An event triggered when a camera is removed
  15566. * @type {BABYLON.Observable}
  15567. */
  15568. this.onCameraRemovedObservable = new BABYLON.Observable();
  15569. /**
  15570. * An event triggered when a light is created
  15571. * @type {BABYLON.Observable}
  15572. */
  15573. this.onNewLightAddedObservable = new BABYLON.Observable();
  15574. /**
  15575. * An event triggered when a light is removed
  15576. * @type {BABYLON.Observable}
  15577. */
  15578. this.onLightRemovedObservable = new BABYLON.Observable();
  15579. /**
  15580. * An event triggered when a geometry is created
  15581. * @type {BABYLON.Observable}
  15582. */
  15583. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15584. /**
  15585. * An event triggered when a geometry is removed
  15586. * @type {BABYLON.Observable}
  15587. */
  15588. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15589. /**
  15590. * An event triggered when a mesh is created
  15591. * @type {BABYLON.Observable}
  15592. */
  15593. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15594. /**
  15595. * An event triggered when a mesh is removed
  15596. * @type {BABYLON.Observable}
  15597. */
  15598. this.onMeshRemovedObservable = new BABYLON.Observable();
  15599. // Animations
  15600. this.animations = [];
  15601. /**
  15602. * 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).
  15603. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15604. */
  15605. this.onPrePointerObservable = new BABYLON.Observable();
  15606. /**
  15607. * Observable event triggered each time an input event is received from the rendering canvas
  15608. */
  15609. this.onPointerObservable = new BABYLON.Observable();
  15610. 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
  15611. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15612. this._startingPointerTime = 0;
  15613. // Fog
  15614. /**
  15615. * is fog enabled on this scene.
  15616. * @type {boolean}
  15617. */
  15618. this.fogEnabled = true;
  15619. this.fogMode = Scene.FOGMODE_NONE;
  15620. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15621. this.fogDensity = 0.1;
  15622. this.fogStart = 0;
  15623. this.fogEnd = 1000.0;
  15624. // Lights
  15625. /**
  15626. * is shadow enabled on this scene.
  15627. * @type {boolean}
  15628. */
  15629. this.shadowsEnabled = true;
  15630. /**
  15631. * is light enabled on this scene.
  15632. * @type {boolean}
  15633. */
  15634. this.lightsEnabled = true;
  15635. /**
  15636. * All of the lights added to this scene.
  15637. * @see BABYLON.Light
  15638. * @type {BABYLON.Light[]}
  15639. */
  15640. this.lights = new Array();
  15641. // Cameras
  15642. /**
  15643. * All of the cameras added to this scene.
  15644. * @see BABYLON.Camera
  15645. * @type {BABYLON.Camera[]}
  15646. */
  15647. this.cameras = new Array();
  15648. this.activeCameras = new Array();
  15649. // Meshes
  15650. /**
  15651. * All of the (abstract) meshes added to this scene.
  15652. * @see BABYLON.AbstractMesh
  15653. * @type {BABYLON.AbstractMesh[]}
  15654. */
  15655. this.meshes = new Array();
  15656. // Geometries
  15657. this._geometries = new Array();
  15658. this.materials = new Array();
  15659. this.multiMaterials = new Array();
  15660. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15661. // Textures
  15662. this.texturesEnabled = true;
  15663. this.textures = new Array();
  15664. // Particles
  15665. this.particlesEnabled = true;
  15666. this.particleSystems = new Array();
  15667. // Sprites
  15668. this.spritesEnabled = true;
  15669. this.spriteManagers = new Array();
  15670. // Layers
  15671. this.layers = new Array();
  15672. // Skeletons
  15673. this.skeletonsEnabled = true;
  15674. this.skeletons = new Array();
  15675. // Lens flares
  15676. this.lensFlaresEnabled = true;
  15677. this.lensFlareSystems = new Array();
  15678. // Collisions
  15679. this.collisionsEnabled = true;
  15680. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15681. // Postprocesses
  15682. this.postProcessesEnabled = true;
  15683. // Customs render targets
  15684. this.renderTargetsEnabled = true;
  15685. this.dumpNextRenderTargets = false;
  15686. this.customRenderTargets = new Array();
  15687. // Imported meshes
  15688. this.importedMeshesFiles = new Array();
  15689. // Probes
  15690. this.probesEnabled = true;
  15691. this.reflectionProbes = new Array();
  15692. this._actionManagers = new Array();
  15693. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15694. // Procedural textures
  15695. this.proceduralTexturesEnabled = true;
  15696. this._proceduralTextures = new Array();
  15697. this.soundTracks = new Array();
  15698. this._audioEnabled = true;
  15699. this._headphone = false;
  15700. // Performance counters
  15701. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15702. this._totalLightsCounter = new BABYLON.PerfCounter();
  15703. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15704. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15705. this._totalVertices = new BABYLON.PerfCounter();
  15706. this._activeIndices = new BABYLON.PerfCounter();
  15707. this._activeParticles = new BABYLON.PerfCounter();
  15708. this._lastFrameDuration = new BABYLON.PerfCounter();
  15709. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15710. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15711. this._particlesDuration = new BABYLON.PerfCounter();
  15712. this._renderDuration = new BABYLON.PerfCounter();
  15713. this._spritesDuration = new BABYLON.PerfCounter();
  15714. this._activeBones = new BABYLON.PerfCounter();
  15715. this._renderId = 0;
  15716. this._executeWhenReadyTimeoutId = -1;
  15717. this._intermediateRendering = false;
  15718. this._toBeDisposed = new BABYLON.SmartArray(256);
  15719. this._pendingData = []; //ANY
  15720. this._activeMeshes = new BABYLON.SmartArray(256);
  15721. this._processedMaterials = new BABYLON.SmartArray(256);
  15722. this._renderTargets = new BABYLON.SmartArray(256);
  15723. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15724. this._activeSkeletons = new BABYLON.SmartArray(32);
  15725. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15726. this._activeAnimatables = new Array();
  15727. this._transformMatrix = BABYLON.Matrix.Zero();
  15728. this._edgesRenderers = new BABYLON.SmartArray(16);
  15729. this._uniqueIdCounter = 0;
  15730. this._engine = engine;
  15731. engine.scenes.push(this);
  15732. this._renderingManager = new BABYLON.RenderingManager(this);
  15733. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15734. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15735. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  15736. if (BABYLON.OutlineRenderer) {
  15737. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15738. }
  15739. this.attachControl();
  15740. if (BABYLON.SoundTrack) {
  15741. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15742. }
  15743. //simplification queue
  15744. if (BABYLON.SimplificationQueue) {
  15745. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15746. }
  15747. //collision coordinator initialization. For now legacy per default.
  15748. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15749. }
  15750. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15751. get: function () {
  15752. return Scene._FOGMODE_NONE;
  15753. },
  15754. enumerable: true,
  15755. configurable: true
  15756. });
  15757. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15758. get: function () {
  15759. return Scene._FOGMODE_EXP;
  15760. },
  15761. enumerable: true,
  15762. configurable: true
  15763. });
  15764. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15765. get: function () {
  15766. return Scene._FOGMODE_EXP2;
  15767. },
  15768. enumerable: true,
  15769. configurable: true
  15770. });
  15771. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15772. get: function () {
  15773. return Scene._FOGMODE_LINEAR;
  15774. },
  15775. enumerable: true,
  15776. configurable: true
  15777. });
  15778. Object.defineProperty(Scene.prototype, "onDispose", {
  15779. set: function (callback) {
  15780. if (this._onDisposeObserver) {
  15781. this.onDisposeObservable.remove(this._onDisposeObserver);
  15782. }
  15783. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15784. },
  15785. enumerable: true,
  15786. configurable: true
  15787. });
  15788. Object.defineProperty(Scene.prototype, "beforeRender", {
  15789. set: function (callback) {
  15790. if (this._onBeforeRenderObserver) {
  15791. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15792. }
  15793. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15794. },
  15795. enumerable: true,
  15796. configurable: true
  15797. });
  15798. Object.defineProperty(Scene.prototype, "afterRender", {
  15799. set: function (callback) {
  15800. if (this._onAfterRenderObserver) {
  15801. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15802. }
  15803. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15804. },
  15805. enumerable: true,
  15806. configurable: true
  15807. });
  15808. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15809. set: function (callback) {
  15810. if (this._onBeforeCameraRenderObserver) {
  15811. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15812. }
  15813. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15814. },
  15815. enumerable: true,
  15816. configurable: true
  15817. });
  15818. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15819. set: function (callback) {
  15820. if (this._onAfterCameraRenderObserver) {
  15821. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15822. }
  15823. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15824. },
  15825. enumerable: true,
  15826. configurable: true
  15827. });
  15828. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15829. get: function () {
  15830. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15831. },
  15832. enumerable: true,
  15833. configurable: true
  15834. });
  15835. Object.defineProperty(Scene.prototype, "debugLayer", {
  15836. // Properties
  15837. get: function () {
  15838. if (!this._debugLayer) {
  15839. this._debugLayer = new BABYLON.DebugLayer(this);
  15840. }
  15841. return this._debugLayer;
  15842. },
  15843. enumerable: true,
  15844. configurable: true
  15845. });
  15846. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15847. get: function () {
  15848. return this._workerCollisions;
  15849. },
  15850. set: function (enabled) {
  15851. enabled = (enabled && !!Worker);
  15852. this._workerCollisions = enabled;
  15853. if (this.collisionCoordinator) {
  15854. this.collisionCoordinator.destroy();
  15855. }
  15856. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15857. this.collisionCoordinator.init(this);
  15858. },
  15859. enumerable: true,
  15860. configurable: true
  15861. });
  15862. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  15863. get: function () {
  15864. return this._selectionOctree;
  15865. },
  15866. enumerable: true,
  15867. configurable: true
  15868. });
  15869. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15870. /**
  15871. * The mesh that is currently under the pointer.
  15872. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15873. */
  15874. get: function () {
  15875. return this._pointerOverMesh;
  15876. },
  15877. enumerable: true,
  15878. configurable: true
  15879. });
  15880. Object.defineProperty(Scene.prototype, "pointerX", {
  15881. /**
  15882. * Current on-screen X position of the pointer
  15883. * @return {number} X position of the pointer
  15884. */
  15885. get: function () {
  15886. return this._pointerX;
  15887. },
  15888. enumerable: true,
  15889. configurable: true
  15890. });
  15891. Object.defineProperty(Scene.prototype, "pointerY", {
  15892. /**
  15893. * Current on-screen Y position of the pointer
  15894. * @return {number} Y position of the pointer
  15895. */
  15896. get: function () {
  15897. return this._pointerY;
  15898. },
  15899. enumerable: true,
  15900. configurable: true
  15901. });
  15902. Scene.prototype.getCachedMaterial = function () {
  15903. return this._cachedMaterial;
  15904. };
  15905. Scene.prototype.getBoundingBoxRenderer = function () {
  15906. return this._boundingBoxRenderer;
  15907. };
  15908. Scene.prototype.getOutlineRenderer = function () {
  15909. return this._outlineRenderer;
  15910. };
  15911. Scene.prototype.getEngine = function () {
  15912. return this._engine;
  15913. };
  15914. Scene.prototype.getTotalVertices = function () {
  15915. return this._totalVertices.current;
  15916. };
  15917. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  15918. get: function () {
  15919. return this._totalVertices;
  15920. },
  15921. enumerable: true,
  15922. configurable: true
  15923. });
  15924. Scene.prototype.getActiveIndices = function () {
  15925. return this._activeIndices.current;
  15926. };
  15927. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  15928. get: function () {
  15929. return this._activeIndices;
  15930. },
  15931. enumerable: true,
  15932. configurable: true
  15933. });
  15934. Scene.prototype.getActiveParticles = function () {
  15935. return this._activeParticles.current;
  15936. };
  15937. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  15938. get: function () {
  15939. return this._activeParticles;
  15940. },
  15941. enumerable: true,
  15942. configurable: true
  15943. });
  15944. Scene.prototype.getActiveBones = function () {
  15945. return this._activeBones.current;
  15946. };
  15947. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  15948. get: function () {
  15949. return this._activeBones;
  15950. },
  15951. enumerable: true,
  15952. configurable: true
  15953. });
  15954. // Stats
  15955. Scene.prototype.getLastFrameDuration = function () {
  15956. return this._lastFrameDuration.current;
  15957. };
  15958. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  15959. get: function () {
  15960. return this._lastFrameDuration;
  15961. },
  15962. enumerable: true,
  15963. configurable: true
  15964. });
  15965. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15966. return this._evaluateActiveMeshesDuration.current;
  15967. };
  15968. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  15969. get: function () {
  15970. return this._evaluateActiveMeshesDuration;
  15971. },
  15972. enumerable: true,
  15973. configurable: true
  15974. });
  15975. Scene.prototype.getActiveMeshes = function () {
  15976. return this._activeMeshes;
  15977. };
  15978. Scene.prototype.getRenderTargetsDuration = function () {
  15979. return this._renderTargetsDuration.current;
  15980. };
  15981. Scene.prototype.getRenderDuration = function () {
  15982. return this._renderDuration.current;
  15983. };
  15984. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  15985. get: function () {
  15986. return this._renderDuration;
  15987. },
  15988. enumerable: true,
  15989. configurable: true
  15990. });
  15991. Scene.prototype.getParticlesDuration = function () {
  15992. return this._particlesDuration.current;
  15993. };
  15994. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  15995. get: function () {
  15996. return this._particlesDuration;
  15997. },
  15998. enumerable: true,
  15999. configurable: true
  16000. });
  16001. Scene.prototype.getSpritesDuration = function () {
  16002. return this._spritesDuration.current;
  16003. };
  16004. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16005. get: function () {
  16006. return this._spritesDuration;
  16007. },
  16008. enumerable: true,
  16009. configurable: true
  16010. });
  16011. Scene.prototype.getAnimationRatio = function () {
  16012. return this._animationRatio;
  16013. };
  16014. Scene.prototype.getRenderId = function () {
  16015. return this._renderId;
  16016. };
  16017. Scene.prototype.incrementRenderId = function () {
  16018. this._renderId++;
  16019. };
  16020. Scene.prototype._updatePointerPosition = function (evt) {
  16021. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16022. this._pointerX = evt.clientX - canvasRect.left;
  16023. this._pointerY = evt.clientY - canvasRect.top;
  16024. this._unTranslatedPointerX = this._pointerX;
  16025. this._unTranslatedPointerY = this._pointerY;
  16026. if (this.cameraToUseForPointers) {
  16027. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16028. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16029. }
  16030. };
  16031. // Pointers handling
  16032. /**
  16033. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16034. * @param attachUp defines if you want to attach events to pointerup
  16035. * @param attachDown defines if you want to attach events to pointerdown
  16036. * @param attachMove defines if you want to attach events to pointermove
  16037. */
  16038. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16039. var _this = this;
  16040. if (attachUp === void 0) { attachUp = true; }
  16041. if (attachDown === void 0) { attachDown = true; }
  16042. if (attachMove === void 0) { attachMove = true; }
  16043. var spritePredicate = function (sprite) {
  16044. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16045. };
  16046. this._onPointerMove = function (evt) {
  16047. _this._updatePointerPosition(evt);
  16048. // PreObservable support
  16049. if (_this.onPrePointerObservable.hasObservers()) {
  16050. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16051. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16052. _this.onPrePointerObservable.notifyObservers(pi, type);
  16053. if (pi.skipOnPointerObservable) {
  16054. return;
  16055. }
  16056. }
  16057. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16058. return;
  16059. }
  16060. var canvas = _this._engine.getRenderingCanvas();
  16061. if (!_this.pointerMovePredicate) {
  16062. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  16063. }
  16064. // Meshes
  16065. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16066. if (pickResult.hit && pickResult.pickedMesh) {
  16067. _this.setPointerOverSprite(null);
  16068. _this.setPointerOverMesh(pickResult.pickedMesh);
  16069. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16070. canvas.style.cursor = _this.hoverCursor;
  16071. }
  16072. else {
  16073. canvas.style.cursor = "";
  16074. }
  16075. }
  16076. else {
  16077. _this.setPointerOverMesh(null);
  16078. // Sprites
  16079. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16080. if (pickResult.hit && pickResult.pickedSprite) {
  16081. canvas.style.cursor = _this.hoverCursor;
  16082. _this.setPointerOverSprite(pickResult.pickedSprite);
  16083. }
  16084. else {
  16085. _this.setPointerOverSprite(null);
  16086. // Restore pointer
  16087. canvas.style.cursor = "";
  16088. }
  16089. }
  16090. if (_this.onPointerMove) {
  16091. _this.onPointerMove(evt, pickResult);
  16092. }
  16093. if (_this.onPointerObservable.hasObservers()) {
  16094. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16095. var pi = new PointerInfo(type, evt, pickResult);
  16096. _this.onPointerObservable.notifyObservers(pi, type);
  16097. }
  16098. };
  16099. this._onPointerDown = function (evt) {
  16100. _this._updatePointerPosition(evt);
  16101. // PreObservable support
  16102. if (_this.onPrePointerObservable.hasObservers()) {
  16103. var type = PointerEventTypes.POINTERDOWN;
  16104. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16105. _this.onPrePointerObservable.notifyObservers(pi, type);
  16106. if (pi.skipOnPointerObservable) {
  16107. return;
  16108. }
  16109. }
  16110. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16111. return;
  16112. }
  16113. _this._startingPointerPosition.x = _this._pointerX;
  16114. _this._startingPointerPosition.y = _this._pointerY;
  16115. _this._startingPointerTime = new Date().getTime();
  16116. if (!_this.pointerDownPredicate) {
  16117. _this.pointerDownPredicate = function (mesh) {
  16118. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  16119. };
  16120. }
  16121. // Meshes
  16122. _this._pickedDownMesh = null;
  16123. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16124. if (pickResult.hit && pickResult.pickedMesh) {
  16125. if (pickResult.pickedMesh.actionManager) {
  16126. _this._pickedDownMesh = pickResult.pickedMesh;
  16127. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  16128. switch (evt.button) {
  16129. case 0:
  16130. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16131. break;
  16132. case 1:
  16133. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16134. break;
  16135. case 2:
  16136. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16137. break;
  16138. }
  16139. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16140. }
  16141. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16142. var that = _this;
  16143. window.setTimeout(function () {
  16144. 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);
  16145. if (pickResult.hit && pickResult.pickedMesh) {
  16146. if (pickResult.pickedMesh.actionManager) {
  16147. 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)) {
  16148. that._startingPointerTime = 0;
  16149. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16150. }
  16151. }
  16152. }
  16153. }, BABYLON.ActionManager.LongPressDelay);
  16154. }
  16155. }
  16156. }
  16157. if (_this.onPointerDown) {
  16158. _this.onPointerDown(evt, pickResult);
  16159. }
  16160. if (_this.onPointerObservable.hasObservers()) {
  16161. var type = PointerEventTypes.POINTERDOWN;
  16162. var pi = new PointerInfo(type, evt, pickResult);
  16163. _this.onPointerObservable.notifyObservers(pi, type);
  16164. }
  16165. // Sprites
  16166. _this._pickedDownSprite = null;
  16167. if (_this.spriteManagers.length > 0) {
  16168. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16169. if (pickResult.hit && pickResult.pickedSprite) {
  16170. if (pickResult.pickedSprite.actionManager) {
  16171. _this._pickedDownSprite = pickResult.pickedSprite;
  16172. switch (evt.button) {
  16173. case 0:
  16174. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16175. break;
  16176. case 1:
  16177. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16178. break;
  16179. case 2:
  16180. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16181. break;
  16182. }
  16183. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16184. }
  16185. }
  16186. }
  16187. };
  16188. this._onPointerUp = function (evt) {
  16189. _this._updatePointerPosition(evt);
  16190. // PreObservable support
  16191. if (_this.onPrePointerObservable.hasObservers()) {
  16192. var type = PointerEventTypes.POINTERUP;
  16193. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16194. _this.onPrePointerObservable.notifyObservers(pi, type);
  16195. if (pi.skipOnPointerObservable) {
  16196. return;
  16197. }
  16198. }
  16199. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16200. return;
  16201. }
  16202. if (!_this.pointerUpPredicate) {
  16203. _this.pointerUpPredicate = function (mesh) {
  16204. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  16205. };
  16206. }
  16207. // Meshes
  16208. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  16209. if (pickResult.hit && pickResult.pickedMesh) {
  16210. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  16211. if (_this.onPointerPick) {
  16212. _this.onPointerPick(evt, pickResult);
  16213. }
  16214. if (_this.onPointerObservable.hasObservers()) {
  16215. var type = PointerEventTypes.POINTERPICK;
  16216. var pi = new PointerInfo(type, evt, pickResult);
  16217. _this.onPointerObservable.notifyObservers(pi, type);
  16218. }
  16219. }
  16220. if (pickResult.pickedMesh.actionManager) {
  16221. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16222. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16223. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16224. }
  16225. }
  16226. }
  16227. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  16228. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  16229. }
  16230. if (_this.onPointerUp) {
  16231. _this.onPointerUp(evt, pickResult);
  16232. }
  16233. if (_this.onPointerObservable.hasObservers()) {
  16234. var type = PointerEventTypes.POINTERUP;
  16235. var pi = new PointerInfo(type, evt, pickResult);
  16236. _this.onPointerObservable.notifyObservers(pi, type);
  16237. }
  16238. _this._startingPointerTime = 0;
  16239. // Sprites
  16240. if (_this.spriteManagers.length > 0) {
  16241. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16242. if (pickResult.hit && pickResult.pickedSprite) {
  16243. if (pickResult.pickedSprite.actionManager) {
  16244. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16245. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16246. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16247. }
  16248. }
  16249. }
  16250. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  16251. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  16252. }
  16253. }
  16254. };
  16255. this._onKeyDown = function (evt) {
  16256. if (_this.actionManager) {
  16257. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16258. }
  16259. };
  16260. this._onKeyUp = function (evt) {
  16261. if (_this.actionManager) {
  16262. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16263. }
  16264. };
  16265. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16266. var canvas = this._engine.getRenderingCanvas();
  16267. if (attachMove) {
  16268. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16269. // Wheel
  16270. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16271. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16272. }
  16273. if (attachDown) {
  16274. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16275. }
  16276. if (attachUp) {
  16277. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16278. }
  16279. canvas.tabIndex = 1;
  16280. canvas.addEventListener("keydown", this._onKeyDown, false);
  16281. canvas.addEventListener("keyup", this._onKeyUp, false);
  16282. };
  16283. Scene.prototype.detachControl = function () {
  16284. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16285. var canvas = this._engine.getRenderingCanvas();
  16286. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16287. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16288. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16289. // Wheel
  16290. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16291. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16292. canvas.removeEventListener("keydown", this._onKeyDown);
  16293. canvas.removeEventListener("keyup", this._onKeyUp);
  16294. };
  16295. // Ready
  16296. Scene.prototype.isReady = function () {
  16297. if (this._pendingData.length > 0) {
  16298. return false;
  16299. }
  16300. var index;
  16301. for (index = 0; index < this._geometries.length; index++) {
  16302. var geometry = this._geometries[index];
  16303. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16304. return false;
  16305. }
  16306. }
  16307. for (index = 0; index < this.meshes.length; index++) {
  16308. var mesh = this.meshes[index];
  16309. if (!mesh.isReady()) {
  16310. return false;
  16311. }
  16312. var mat = mesh.material;
  16313. if (mat) {
  16314. if (!mat.isReady(mesh)) {
  16315. return false;
  16316. }
  16317. }
  16318. }
  16319. return true;
  16320. };
  16321. Scene.prototype.resetCachedMaterial = function () {
  16322. this._cachedMaterial = null;
  16323. };
  16324. Scene.prototype.registerBeforeRender = function (func) {
  16325. this.onBeforeRenderObservable.add(func);
  16326. };
  16327. Scene.prototype.unregisterBeforeRender = function (func) {
  16328. this.onBeforeRenderObservable.removeCallback(func);
  16329. };
  16330. Scene.prototype.registerAfterRender = function (func) {
  16331. this.onAfterRenderObservable.add(func);
  16332. };
  16333. Scene.prototype.unregisterAfterRender = function (func) {
  16334. this.onAfterRenderObservable.removeCallback(func);
  16335. };
  16336. Scene.prototype._addPendingData = function (data) {
  16337. this._pendingData.push(data);
  16338. };
  16339. Scene.prototype._removePendingData = function (data) {
  16340. var index = this._pendingData.indexOf(data);
  16341. if (index !== -1) {
  16342. this._pendingData.splice(index, 1);
  16343. }
  16344. };
  16345. Scene.prototype.getWaitingItemsCount = function () {
  16346. return this._pendingData.length;
  16347. };
  16348. /**
  16349. * Registers a function to be executed when the scene is ready.
  16350. * @param {Function} func - the function to be executed.
  16351. */
  16352. Scene.prototype.executeWhenReady = function (func) {
  16353. var _this = this;
  16354. this.onReadyObservable.add(func);
  16355. if (this._executeWhenReadyTimeoutId !== -1) {
  16356. return;
  16357. }
  16358. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16359. _this._checkIsReady();
  16360. }, 150);
  16361. };
  16362. Scene.prototype._checkIsReady = function () {
  16363. var _this = this;
  16364. if (this.isReady()) {
  16365. this.onReadyObservable.notifyObservers(this);
  16366. this.onReadyObservable.clear();
  16367. this._executeWhenReadyTimeoutId = -1;
  16368. return;
  16369. }
  16370. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16371. _this._checkIsReady();
  16372. }, 150);
  16373. };
  16374. // Animations
  16375. /**
  16376. * Will start the animation sequence of a given target
  16377. * @param target - the target
  16378. * @param {number} from - from which frame should animation start
  16379. * @param {number} to - till which frame should animation run.
  16380. * @param {boolean} [loop] - should the animation loop
  16381. * @param {number} [speedRatio] - the speed in which to run the animation
  16382. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16383. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16384. * @return {BABYLON.Animatable} the animatable object created for this animation
  16385. * @see BABYLON.Animatable
  16386. * @see http://doc.babylonjs.com/page.php?p=22081
  16387. */
  16388. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16389. if (speedRatio === void 0) { speedRatio = 1.0; }
  16390. this.stopAnimation(target);
  16391. if (!animatable) {
  16392. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16393. }
  16394. // Local animations
  16395. if (target.animations) {
  16396. animatable.appendAnimations(target, target.animations);
  16397. }
  16398. // Children animations
  16399. if (target.getAnimatables) {
  16400. var animatables = target.getAnimatables();
  16401. for (var index = 0; index < animatables.length; index++) {
  16402. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16403. }
  16404. }
  16405. animatable.reset();
  16406. return animatable;
  16407. };
  16408. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16409. if (speedRatio === undefined) {
  16410. speedRatio = 1.0;
  16411. }
  16412. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16413. return animatable;
  16414. };
  16415. Scene.prototype.getAnimatableByTarget = function (target) {
  16416. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16417. if (this._activeAnimatables[index].target === target) {
  16418. return this._activeAnimatables[index];
  16419. }
  16420. }
  16421. return null;
  16422. };
  16423. Object.defineProperty(Scene.prototype, "Animatables", {
  16424. get: function () {
  16425. return this._activeAnimatables;
  16426. },
  16427. enumerable: true,
  16428. configurable: true
  16429. });
  16430. /**
  16431. * Will stop the animation of the given target
  16432. * @param target - the target
  16433. * @see beginAnimation
  16434. */
  16435. Scene.prototype.stopAnimation = function (target) {
  16436. var animatable = this.getAnimatableByTarget(target);
  16437. if (animatable) {
  16438. animatable.stop();
  16439. }
  16440. };
  16441. Scene.prototype._animate = function () {
  16442. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16443. return;
  16444. }
  16445. if (!this._animationStartDate) {
  16446. if (this._pendingData.length > 0) {
  16447. return;
  16448. }
  16449. this._animationStartDate = BABYLON.Tools.Now;
  16450. }
  16451. // Getting time
  16452. var now = BABYLON.Tools.Now;
  16453. var delay = now - this._animationStartDate;
  16454. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16455. this._activeAnimatables[index]._animate(delay);
  16456. }
  16457. };
  16458. // Matrix
  16459. Scene.prototype.getViewMatrix = function () {
  16460. return this._viewMatrix;
  16461. };
  16462. Scene.prototype.getProjectionMatrix = function () {
  16463. return this._projectionMatrix;
  16464. };
  16465. Scene.prototype.getTransformMatrix = function () {
  16466. return this._transformMatrix;
  16467. };
  16468. Scene.prototype.setTransformMatrix = function (view, projection) {
  16469. this._viewMatrix = view;
  16470. this._projectionMatrix = projection;
  16471. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16472. // Update frustum
  16473. if (!this._frustumPlanes) {
  16474. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16475. }
  16476. else {
  16477. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16478. }
  16479. };
  16480. // Methods
  16481. Scene.prototype.addMesh = function (newMesh) {
  16482. newMesh.uniqueId = this._uniqueIdCounter++;
  16483. var position = this.meshes.push(newMesh);
  16484. //notify the collision coordinator
  16485. this.collisionCoordinator.onMeshAdded(newMesh);
  16486. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16487. };
  16488. Scene.prototype.removeMesh = function (toRemove) {
  16489. var index = this.meshes.indexOf(toRemove);
  16490. if (index !== -1) {
  16491. // Remove from the scene if mesh found
  16492. this.meshes.splice(index, 1);
  16493. }
  16494. //notify the collision coordinator
  16495. this.collisionCoordinator.onMeshRemoved(toRemove);
  16496. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16497. return index;
  16498. };
  16499. Scene.prototype.removeSkeleton = function (toRemove) {
  16500. var index = this.skeletons.indexOf(toRemove);
  16501. if (index !== -1) {
  16502. // Remove from the scene if mesh found
  16503. this.skeletons.splice(index, 1);
  16504. }
  16505. return index;
  16506. };
  16507. Scene.prototype.removeLight = function (toRemove) {
  16508. var index = this.lights.indexOf(toRemove);
  16509. if (index !== -1) {
  16510. // Remove from the scene if mesh found
  16511. this.lights.splice(index, 1);
  16512. }
  16513. this.onLightRemovedObservable.notifyObservers(toRemove);
  16514. return index;
  16515. };
  16516. Scene.prototype.removeCamera = function (toRemove) {
  16517. var index = this.cameras.indexOf(toRemove);
  16518. if (index !== -1) {
  16519. // Remove from the scene if mesh found
  16520. this.cameras.splice(index, 1);
  16521. }
  16522. // Remove from activeCameras
  16523. var index2 = this.activeCameras.indexOf(toRemove);
  16524. if (index2 !== -1) {
  16525. // Remove from the scene if mesh found
  16526. this.activeCameras.splice(index2, 1);
  16527. }
  16528. // Reset the activeCamera
  16529. if (this.activeCamera === toRemove) {
  16530. if (this.cameras.length > 0) {
  16531. this.activeCamera = this.cameras[0];
  16532. }
  16533. else {
  16534. this.activeCamera = null;
  16535. }
  16536. }
  16537. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16538. return index;
  16539. };
  16540. Scene.prototype.addLight = function (newLight) {
  16541. newLight.uniqueId = this._uniqueIdCounter++;
  16542. var position = this.lights.push(newLight);
  16543. this.onNewLightAddedObservable.notifyObservers(newLight);
  16544. };
  16545. Scene.prototype.addCamera = function (newCamera) {
  16546. newCamera.uniqueId = this._uniqueIdCounter++;
  16547. var position = this.cameras.push(newCamera);
  16548. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16549. };
  16550. /**
  16551. * Switch active camera
  16552. * @param {Camera} newCamera - new active camera
  16553. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16554. */
  16555. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16556. if (attachControl === void 0) { attachControl = true; }
  16557. var canvas = this._engine.getRenderingCanvas();
  16558. this.activeCamera.detachControl(canvas);
  16559. this.activeCamera = newCamera;
  16560. if (attachControl) {
  16561. newCamera.attachControl(canvas);
  16562. }
  16563. };
  16564. /**
  16565. * sets the active camera of the scene using its ID
  16566. * @param {string} id - the camera's ID
  16567. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16568. * @see activeCamera
  16569. */
  16570. Scene.prototype.setActiveCameraByID = function (id) {
  16571. var camera = this.getCameraByID(id);
  16572. if (camera) {
  16573. this.activeCamera = camera;
  16574. return camera;
  16575. }
  16576. return null;
  16577. };
  16578. /**
  16579. * sets the active camera of the scene using its name
  16580. * @param {string} name - the camera's name
  16581. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16582. * @see activeCamera
  16583. */
  16584. Scene.prototype.setActiveCameraByName = function (name) {
  16585. var camera = this.getCameraByName(name);
  16586. if (camera) {
  16587. this.activeCamera = camera;
  16588. return camera;
  16589. }
  16590. return null;
  16591. };
  16592. /**
  16593. * get a material using its id
  16594. * @param {string} the material's ID
  16595. * @return {BABYLON.Material|null} the material or null if none found.
  16596. */
  16597. Scene.prototype.getMaterialByID = function (id) {
  16598. for (var index = 0; index < this.materials.length; index++) {
  16599. if (this.materials[index].id === id) {
  16600. return this.materials[index];
  16601. }
  16602. }
  16603. return null;
  16604. };
  16605. /**
  16606. * get a material using its name
  16607. * @param {string} the material's name
  16608. * @return {BABYLON.Material|null} the material or null if none found.
  16609. */
  16610. Scene.prototype.getMaterialByName = function (name) {
  16611. for (var index = 0; index < this.materials.length; index++) {
  16612. if (this.materials[index].name === name) {
  16613. return this.materials[index];
  16614. }
  16615. }
  16616. return null;
  16617. };
  16618. Scene.prototype.getLensFlareSystemByName = function (name) {
  16619. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16620. if (this.lensFlareSystems[index].name === name) {
  16621. return this.lensFlareSystems[index];
  16622. }
  16623. }
  16624. return null;
  16625. };
  16626. Scene.prototype.getLensFlareSystemByID = function (id) {
  16627. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16628. if (this.lensFlareSystems[index].id === id) {
  16629. return this.lensFlareSystems[index];
  16630. }
  16631. }
  16632. return null;
  16633. };
  16634. Scene.prototype.getCameraByID = function (id) {
  16635. for (var index = 0; index < this.cameras.length; index++) {
  16636. if (this.cameras[index].id === id) {
  16637. return this.cameras[index];
  16638. }
  16639. }
  16640. return null;
  16641. };
  16642. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16643. for (var index = 0; index < this.cameras.length; index++) {
  16644. if (this.cameras[index].uniqueId === uniqueId) {
  16645. return this.cameras[index];
  16646. }
  16647. }
  16648. return null;
  16649. };
  16650. /**
  16651. * get a camera using its name
  16652. * @param {string} the camera's name
  16653. * @return {BABYLON.Camera|null} the camera or null if none found.
  16654. */
  16655. Scene.prototype.getCameraByName = function (name) {
  16656. for (var index = 0; index < this.cameras.length; index++) {
  16657. if (this.cameras[index].name === name) {
  16658. return this.cameras[index];
  16659. }
  16660. }
  16661. return null;
  16662. };
  16663. /**
  16664. * get a bone using its id
  16665. * @param {string} the bone's id
  16666. * @return {BABYLON.Bone|null} the bone or null if not found
  16667. */
  16668. Scene.prototype.getBoneByID = function (id) {
  16669. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16670. var skeleton = this.skeletons[skeletonIndex];
  16671. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16672. if (skeleton.bones[boneIndex].id === id) {
  16673. return skeleton.bones[boneIndex];
  16674. }
  16675. }
  16676. }
  16677. return null;
  16678. };
  16679. /**
  16680. * get a bone using its id
  16681. * @param {string} the bone's name
  16682. * @return {BABYLON.Bone|null} the bone or null if not found
  16683. */
  16684. Scene.prototype.getBoneByName = function (name) {
  16685. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16686. var skeleton = this.skeletons[skeletonIndex];
  16687. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16688. if (skeleton.bones[boneIndex].name === name) {
  16689. return skeleton.bones[boneIndex];
  16690. }
  16691. }
  16692. }
  16693. return null;
  16694. };
  16695. /**
  16696. * get a light node using its name
  16697. * @param {string} the light's name
  16698. * @return {BABYLON.Light|null} the light or null if none found.
  16699. */
  16700. Scene.prototype.getLightByName = function (name) {
  16701. for (var index = 0; index < this.lights.length; index++) {
  16702. if (this.lights[index].name === name) {
  16703. return this.lights[index];
  16704. }
  16705. }
  16706. return null;
  16707. };
  16708. /**
  16709. * get a light node using its ID
  16710. * @param {string} the light's id
  16711. * @return {BABYLON.Light|null} the light or null if none found.
  16712. */
  16713. Scene.prototype.getLightByID = function (id) {
  16714. for (var index = 0; index < this.lights.length; index++) {
  16715. if (this.lights[index].id === id) {
  16716. return this.lights[index];
  16717. }
  16718. }
  16719. return null;
  16720. };
  16721. /**
  16722. * get a light node using its scene-generated unique ID
  16723. * @param {number} the light's unique id
  16724. * @return {BABYLON.Light|null} the light or null if none found.
  16725. */
  16726. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  16727. for (var index = 0; index < this.lights.length; index++) {
  16728. if (this.lights[index].uniqueId === uniqueId) {
  16729. return this.lights[index];
  16730. }
  16731. }
  16732. return null;
  16733. };
  16734. /**
  16735. * get a particle system by id
  16736. * @param id {number} the particle system id
  16737. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16738. */
  16739. Scene.prototype.getParticleSystemByID = function (id) {
  16740. for (var index = 0; index < this.particleSystems.length; index++) {
  16741. if (this.particleSystems[index].id === id) {
  16742. return this.particleSystems[index];
  16743. }
  16744. }
  16745. return null;
  16746. };
  16747. /**
  16748. * get a geometry using its ID
  16749. * @param {string} the geometry's id
  16750. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  16751. */
  16752. Scene.prototype.getGeometryByID = function (id) {
  16753. for (var index = 0; index < this._geometries.length; index++) {
  16754. if (this._geometries[index].id === id) {
  16755. return this._geometries[index];
  16756. }
  16757. }
  16758. return null;
  16759. };
  16760. /**
  16761. * add a new geometry to this scene.
  16762. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  16763. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  16764. * @return {boolean} was the geometry added or not
  16765. */
  16766. Scene.prototype.pushGeometry = function (geometry, force) {
  16767. if (!force && this.getGeometryByID(geometry.id)) {
  16768. return false;
  16769. }
  16770. this._geometries.push(geometry);
  16771. //notify the collision coordinator
  16772. this.collisionCoordinator.onGeometryAdded(geometry);
  16773. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  16774. return true;
  16775. };
  16776. /**
  16777. * Removes an existing geometry
  16778. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  16779. * @return {boolean} was the geometry removed or not
  16780. */
  16781. Scene.prototype.removeGeometry = function (geometry) {
  16782. var index = this._geometries.indexOf(geometry);
  16783. if (index > -1) {
  16784. this._geometries.splice(index, 1);
  16785. //notify the collision coordinator
  16786. this.collisionCoordinator.onGeometryDeleted(geometry);
  16787. this.onGeometryRemovedObservable.notifyObservers(geometry);
  16788. return true;
  16789. }
  16790. return false;
  16791. };
  16792. Scene.prototype.getGeometries = function () {
  16793. return this._geometries;
  16794. };
  16795. /**
  16796. * Get the first added mesh found of a given ID
  16797. * @param {string} id - the id to search for
  16798. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16799. */
  16800. Scene.prototype.getMeshByID = function (id) {
  16801. for (var index = 0; index < this.meshes.length; index++) {
  16802. if (this.meshes[index].id === id) {
  16803. return this.meshes[index];
  16804. }
  16805. }
  16806. return null;
  16807. };
  16808. Scene.prototype.getMeshesByID = function (id) {
  16809. return this.meshes.filter(function (m) {
  16810. return m.id === id;
  16811. });
  16812. };
  16813. /**
  16814. * Get a mesh with its auto-generated unique id
  16815. * @param {number} uniqueId - the unique id to search for
  16816. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16817. */
  16818. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  16819. for (var index = 0; index < this.meshes.length; index++) {
  16820. if (this.meshes[index].uniqueId === uniqueId) {
  16821. return this.meshes[index];
  16822. }
  16823. }
  16824. return null;
  16825. };
  16826. /**
  16827. * Get a the last added mesh found of a given ID
  16828. * @param {string} id - the id to search for
  16829. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16830. */
  16831. Scene.prototype.getLastMeshByID = function (id) {
  16832. for (var index = this.meshes.length - 1; index >= 0; index--) {
  16833. if (this.meshes[index].id === id) {
  16834. return this.meshes[index];
  16835. }
  16836. }
  16837. return null;
  16838. };
  16839. /**
  16840. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  16841. * @param {string} id - the id to search for
  16842. * @return {BABYLON.Node|null} the node found or null if not found at all.
  16843. */
  16844. Scene.prototype.getLastEntryByID = function (id) {
  16845. var index;
  16846. for (index = this.meshes.length - 1; index >= 0; index--) {
  16847. if (this.meshes[index].id === id) {
  16848. return this.meshes[index];
  16849. }
  16850. }
  16851. for (index = this.cameras.length - 1; index >= 0; index--) {
  16852. if (this.cameras[index].id === id) {
  16853. return this.cameras[index];
  16854. }
  16855. }
  16856. for (index = this.lights.length - 1; index >= 0; index--) {
  16857. if (this.lights[index].id === id) {
  16858. return this.lights[index];
  16859. }
  16860. }
  16861. return null;
  16862. };
  16863. Scene.prototype.getNodeByID = function (id) {
  16864. var mesh = this.getMeshByID(id);
  16865. if (mesh) {
  16866. return mesh;
  16867. }
  16868. var light = this.getLightByID(id);
  16869. if (light) {
  16870. return light;
  16871. }
  16872. var camera = this.getCameraByID(id);
  16873. if (camera) {
  16874. return camera;
  16875. }
  16876. var bone = this.getBoneByID(id);
  16877. return bone;
  16878. };
  16879. Scene.prototype.getNodeByName = function (name) {
  16880. var mesh = this.getMeshByName(name);
  16881. if (mesh) {
  16882. return mesh;
  16883. }
  16884. var light = this.getLightByName(name);
  16885. if (light) {
  16886. return light;
  16887. }
  16888. var camera = this.getCameraByName(name);
  16889. if (camera) {
  16890. return camera;
  16891. }
  16892. var bone = this.getBoneByName(name);
  16893. return bone;
  16894. };
  16895. Scene.prototype.getMeshByName = function (name) {
  16896. for (var index = 0; index < this.meshes.length; index++) {
  16897. if (this.meshes[index].name === name) {
  16898. return this.meshes[index];
  16899. }
  16900. }
  16901. return null;
  16902. };
  16903. Scene.prototype.getSoundByName = function (name) {
  16904. var index;
  16905. if (BABYLON.AudioEngine) {
  16906. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  16907. if (this.mainSoundTrack.soundCollection[index].name === name) {
  16908. return this.mainSoundTrack.soundCollection[index];
  16909. }
  16910. }
  16911. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  16912. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  16913. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  16914. return this.soundTracks[sdIndex].soundCollection[index];
  16915. }
  16916. }
  16917. }
  16918. }
  16919. return null;
  16920. };
  16921. Scene.prototype.getLastSkeletonByID = function (id) {
  16922. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  16923. if (this.skeletons[index].id === id) {
  16924. return this.skeletons[index];
  16925. }
  16926. }
  16927. return null;
  16928. };
  16929. Scene.prototype.getSkeletonById = function (id) {
  16930. for (var index = 0; index < this.skeletons.length; index++) {
  16931. if (this.skeletons[index].id === id) {
  16932. return this.skeletons[index];
  16933. }
  16934. }
  16935. return null;
  16936. };
  16937. Scene.prototype.getSkeletonByName = function (name) {
  16938. for (var index = 0; index < this.skeletons.length; index++) {
  16939. if (this.skeletons[index].name === name) {
  16940. return this.skeletons[index];
  16941. }
  16942. }
  16943. return null;
  16944. };
  16945. Scene.prototype.isActiveMesh = function (mesh) {
  16946. return (this._activeMeshes.indexOf(mesh) !== -1);
  16947. };
  16948. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  16949. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  16950. var material = subMesh.getMaterial();
  16951. if (mesh.showSubMeshesBoundingBox) {
  16952. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  16953. }
  16954. if (material) {
  16955. // Render targets
  16956. if (material.getRenderTargetTextures) {
  16957. if (this._processedMaterials.indexOf(material) === -1) {
  16958. this._processedMaterials.push(material);
  16959. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  16960. }
  16961. }
  16962. // Dispatch
  16963. this._activeIndices.addCount(subMesh.indexCount, false);
  16964. this._renderingManager.dispatch(subMesh);
  16965. }
  16966. }
  16967. };
  16968. Scene.prototype._isInIntermediateRendering = function () {
  16969. return this._intermediateRendering;
  16970. };
  16971. Scene.prototype._evaluateActiveMeshes = function () {
  16972. this.activeCamera._activeMeshes.reset();
  16973. this._activeMeshes.reset();
  16974. this._renderingManager.reset();
  16975. this._processedMaterials.reset();
  16976. this._activeParticleSystems.reset();
  16977. this._activeSkeletons.reset();
  16978. this._softwareSkinnedMeshes.reset();
  16979. this._boundingBoxRenderer.reset();
  16980. this._edgesRenderers.reset();
  16981. // Meshes
  16982. var meshes;
  16983. var len;
  16984. if (this._selectionOctree) {
  16985. var selection = this._selectionOctree.select(this._frustumPlanes);
  16986. meshes = selection.data;
  16987. len = selection.length;
  16988. }
  16989. else {
  16990. len = this.meshes.length;
  16991. meshes = this.meshes;
  16992. }
  16993. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  16994. var mesh = meshes[meshIndex];
  16995. if (mesh.isBlocked) {
  16996. continue;
  16997. }
  16998. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  16999. if (!mesh.isReady() || !mesh.isEnabled()) {
  17000. continue;
  17001. }
  17002. mesh.computeWorldMatrix();
  17003. // Intersections
  17004. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17005. this._meshesForIntersections.pushNoDuplicate(mesh);
  17006. }
  17007. // Switch to current LOD
  17008. var meshLOD = mesh.getLOD(this.activeCamera);
  17009. if (!meshLOD) {
  17010. continue;
  17011. }
  17012. mesh._preActivate();
  17013. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17014. this._activeMeshes.push(mesh);
  17015. this.activeCamera._activeMeshes.push(mesh);
  17016. mesh._activate(this._renderId);
  17017. this._activeMesh(mesh, meshLOD);
  17018. }
  17019. }
  17020. // Particle systems
  17021. this._particlesDuration.beginMonitoring();
  17022. var beforeParticlesDate = BABYLON.Tools.Now;
  17023. if (this.particlesEnabled) {
  17024. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17025. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17026. var particleSystem = this.particleSystems[particleIndex];
  17027. if (!particleSystem.isStarted()) {
  17028. continue;
  17029. }
  17030. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17031. this._activeParticleSystems.push(particleSystem);
  17032. particleSystem.animate();
  17033. }
  17034. }
  17035. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17036. }
  17037. this._particlesDuration.endMonitoring(false);
  17038. };
  17039. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17040. if (mesh.skeleton && this.skeletonsEnabled) {
  17041. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17042. mesh.skeleton.prepare();
  17043. }
  17044. if (!mesh.computeBonesUsingShaders) {
  17045. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17046. }
  17047. }
  17048. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17049. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17050. }
  17051. if (sourceMesh._edgesRenderer) {
  17052. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  17053. }
  17054. if (mesh && mesh.subMeshes) {
  17055. // Submeshes Octrees
  17056. var len;
  17057. var subMeshes;
  17058. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17059. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17060. len = intersections.length;
  17061. subMeshes = intersections.data;
  17062. }
  17063. else {
  17064. subMeshes = mesh.subMeshes;
  17065. len = subMeshes.length;
  17066. }
  17067. for (var subIndex = 0; subIndex < len; subIndex++) {
  17068. var subMesh = subMeshes[subIndex];
  17069. this._evaluateSubMesh(subMesh, mesh);
  17070. }
  17071. }
  17072. };
  17073. Scene.prototype.updateTransformMatrix = function (force) {
  17074. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17075. };
  17076. Scene.prototype._renderForCamera = function (camera) {
  17077. var engine = this._engine;
  17078. var startTime = BABYLON.Tools.Now;
  17079. this.activeCamera = camera;
  17080. if (!this.activeCamera)
  17081. throw new Error("Active camera not set");
  17082. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17083. // Viewport
  17084. engine.setViewport(this.activeCamera.viewport);
  17085. // Camera
  17086. this.resetCachedMaterial();
  17087. this._renderId++;
  17088. this.updateTransformMatrix();
  17089. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17090. // Meshes
  17091. this._evaluateActiveMeshesDuration.beginMonitoring();
  17092. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17093. this._evaluateActiveMeshes();
  17094. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17095. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17096. // Software skinning
  17097. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17098. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17099. mesh.applySkeleton(mesh.skeleton);
  17100. }
  17101. // Render targets
  17102. this._renderTargetsDuration.beginMonitoring();
  17103. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17104. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17105. this._intermediateRendering = true;
  17106. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17107. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17108. var renderTarget = this._renderTargets.data[renderIndex];
  17109. if (renderTarget._shouldRender()) {
  17110. this._renderId++;
  17111. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17112. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17113. }
  17114. }
  17115. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17116. this._intermediateRendering = false;
  17117. this._renderId++;
  17118. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17119. }
  17120. this._renderTargetsDuration.endMonitoring(false);
  17121. // Prepare Frame
  17122. this.postProcessManager._prepareFrame();
  17123. this._renderDuration.beginMonitoring();
  17124. // Backgrounds
  17125. var layerIndex;
  17126. var layer;
  17127. if (this.layers.length) {
  17128. engine.setDepthBuffer(false);
  17129. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17130. layer = this.layers[layerIndex];
  17131. if (layer.isBackground) {
  17132. layer.render();
  17133. }
  17134. }
  17135. engine.setDepthBuffer(true);
  17136. }
  17137. // Render
  17138. BABYLON.Tools.StartPerformanceCounter("Main render");
  17139. this._renderingManager.render(null, null, true, true);
  17140. BABYLON.Tools.EndPerformanceCounter("Main render");
  17141. // Bounding boxes
  17142. this._boundingBoxRenderer.render();
  17143. // Edges
  17144. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17145. this._edgesRenderers.data[edgesRendererIndex].render();
  17146. }
  17147. // Lens flares
  17148. if (this.lensFlaresEnabled) {
  17149. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17150. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17151. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17152. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17153. lensFlareSystem.render();
  17154. }
  17155. }
  17156. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17157. }
  17158. // Foregrounds
  17159. if (this.layers.length) {
  17160. engine.setDepthBuffer(false);
  17161. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17162. layer = this.layers[layerIndex];
  17163. if (!layer.isBackground) {
  17164. layer.render();
  17165. }
  17166. }
  17167. engine.setDepthBuffer(true);
  17168. }
  17169. this._renderDuration.endMonitoring(false);
  17170. // Finalize frame
  17171. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17172. // Update camera
  17173. this.activeCamera._updateFromScene();
  17174. // Reset some special arrays
  17175. this._renderTargets.reset();
  17176. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17177. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17178. };
  17179. Scene.prototype._processSubCameras = function (camera) {
  17180. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17181. this._renderForCamera(camera);
  17182. return;
  17183. }
  17184. // rig cameras
  17185. for (var index = 0; index < camera._rigCameras.length; index++) {
  17186. this._renderForCamera(camera._rigCameras[index]);
  17187. }
  17188. this.activeCamera = camera;
  17189. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17190. // Update camera
  17191. this.activeCamera._updateFromScene();
  17192. };
  17193. Scene.prototype._checkIntersections = function () {
  17194. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17195. var sourceMesh = this._meshesForIntersections.data[index];
  17196. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17197. var action = sourceMesh.actionManager.actions[actionIndex];
  17198. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17199. var parameters = action.getTriggerParameter();
  17200. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17201. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17202. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17203. if (areIntersecting && currentIntersectionInProgress === -1) {
  17204. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17205. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17206. sourceMesh._intersectionsInProgress.push(otherMesh);
  17207. }
  17208. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17209. sourceMesh._intersectionsInProgress.push(otherMesh);
  17210. }
  17211. }
  17212. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17213. //They intersected, and now they don't.
  17214. //is this trigger an exit trigger? execute an event.
  17215. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17216. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17217. }
  17218. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17219. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17220. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17221. }
  17222. }
  17223. }
  17224. }
  17225. }
  17226. };
  17227. Scene.prototype.render = function () {
  17228. this._lastFrameDuration.beginMonitoring();
  17229. this._particlesDuration.fetchNewFrame();
  17230. this._spritesDuration.fetchNewFrame();
  17231. this._activeParticles.fetchNewFrame();
  17232. this._renderDuration.fetchNewFrame();
  17233. this._renderTargetsDuration.fetchNewFrame();
  17234. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17235. this._totalVertices.fetchNewFrame();
  17236. this._activeIndices.fetchNewFrame();
  17237. this._activeBones.fetchNewFrame();
  17238. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17239. this._meshesForIntersections.reset();
  17240. this.resetCachedMaterial();
  17241. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17242. // Actions
  17243. if (this.actionManager) {
  17244. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17245. }
  17246. //Simplification Queue
  17247. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17248. this.simplificationQueue.executeNext();
  17249. }
  17250. // Animations
  17251. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17252. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17253. this._animate();
  17254. // Physics
  17255. if (this._physicsEngine) {
  17256. BABYLON.Tools.StartPerformanceCounter("Physics");
  17257. this._physicsEngine._step(deltaTime / 1000.0);
  17258. BABYLON.Tools.EndPerformanceCounter("Physics");
  17259. }
  17260. // Before render
  17261. this.onBeforeRenderObservable.notifyObservers(this);
  17262. // Customs render targets
  17263. this._renderTargetsDuration.beginMonitoring();
  17264. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17265. var engine = this.getEngine();
  17266. var currentActiveCamera = this.activeCamera;
  17267. if (this.renderTargetsEnabled) {
  17268. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17269. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17270. var renderTarget = this.customRenderTargets[customIndex];
  17271. if (renderTarget._shouldRender()) {
  17272. this._renderId++;
  17273. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17274. if (!this.activeCamera)
  17275. throw new Error("Active camera not set");
  17276. // Viewport
  17277. engine.setViewport(this.activeCamera.viewport);
  17278. // Camera
  17279. this.updateTransformMatrix();
  17280. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17281. }
  17282. }
  17283. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17284. this._renderId++;
  17285. }
  17286. if (this.customRenderTargets.length > 0) {
  17287. engine.restoreDefaultFramebuffer();
  17288. }
  17289. this._renderTargetsDuration.endMonitoring();
  17290. this.activeCamera = currentActiveCamera;
  17291. // Procedural textures
  17292. if (this.proceduralTexturesEnabled) {
  17293. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17294. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17295. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17296. if (proceduralTexture._shouldRender()) {
  17297. proceduralTexture.render();
  17298. }
  17299. }
  17300. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17301. }
  17302. // Clear
  17303. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  17304. // Shadows
  17305. if (this.shadowsEnabled) {
  17306. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17307. var light = this.lights[lightIndex];
  17308. var shadowGenerator = light.getShadowGenerator();
  17309. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  17310. this._renderTargets.push(shadowGenerator.getShadowMap());
  17311. }
  17312. }
  17313. }
  17314. // Depth renderer
  17315. if (this._depthRenderer) {
  17316. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17317. }
  17318. // RenderPipeline
  17319. this.postProcessRenderPipelineManager.update();
  17320. // Multi-cameras?
  17321. if (this.activeCameras.length > 0) {
  17322. var currentRenderId = this._renderId;
  17323. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17324. this._renderId = currentRenderId;
  17325. if (cameraIndex > 0) {
  17326. this._engine.clear(0, false, true, true);
  17327. }
  17328. this._processSubCameras(this.activeCameras[cameraIndex]);
  17329. }
  17330. }
  17331. else {
  17332. if (!this.activeCamera) {
  17333. throw new Error("No camera defined");
  17334. }
  17335. this._processSubCameras(this.activeCamera);
  17336. }
  17337. // Intersection checks
  17338. this._checkIntersections();
  17339. // Update the audio listener attached to the camera
  17340. if (BABYLON.AudioEngine) {
  17341. this._updateAudioParameters();
  17342. }
  17343. // After render
  17344. if (this.afterRender) {
  17345. this.afterRender();
  17346. }
  17347. this.onAfterRenderObservable.notifyObservers(this);
  17348. // Cleaning
  17349. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17350. this._toBeDisposed.data[index].dispose();
  17351. this._toBeDisposed[index] = null;
  17352. }
  17353. this._toBeDisposed.reset();
  17354. if (this.dumpNextRenderTargets) {
  17355. this.dumpNextRenderTargets = false;
  17356. }
  17357. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17358. this._lastFrameDuration.endMonitoring();
  17359. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17360. this._totalLightsCounter.addCount(this.lights.length, true);
  17361. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17362. this._totalTexturesCounter.addCount(this.textures.length, true);
  17363. this._activeBones.addCount(0, true);
  17364. this._activeIndices.addCount(0, true);
  17365. this._activeParticles.addCount(0, true);
  17366. };
  17367. Scene.prototype._updateAudioParameters = function () {
  17368. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17369. return;
  17370. }
  17371. var listeningCamera;
  17372. var audioEngine = BABYLON.Engine.audioEngine;
  17373. if (this.activeCameras.length > 0) {
  17374. listeningCamera = this.activeCameras[0];
  17375. }
  17376. else {
  17377. listeningCamera = this.activeCamera;
  17378. }
  17379. if (listeningCamera && audioEngine.canUseWebAudio) {
  17380. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17381. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17382. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17383. cameraDirection.normalize();
  17384. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17385. var i;
  17386. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17387. var sound = this.mainSoundTrack.soundCollection[i];
  17388. if (sound.useCustomAttenuation) {
  17389. sound.updateDistanceFromListener();
  17390. }
  17391. }
  17392. for (i = 0; i < this.soundTracks.length; i++) {
  17393. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17394. sound = this.soundTracks[i].soundCollection[j];
  17395. if (sound.useCustomAttenuation) {
  17396. sound.updateDistanceFromListener();
  17397. }
  17398. }
  17399. }
  17400. }
  17401. };
  17402. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17403. // Audio
  17404. get: function () {
  17405. return this._audioEnabled;
  17406. },
  17407. set: function (value) {
  17408. this._audioEnabled = value;
  17409. if (BABYLON.AudioEngine) {
  17410. if (this._audioEnabled) {
  17411. this._enableAudio();
  17412. }
  17413. else {
  17414. this._disableAudio();
  17415. }
  17416. }
  17417. },
  17418. enumerable: true,
  17419. configurable: true
  17420. });
  17421. Scene.prototype._disableAudio = function () {
  17422. var i;
  17423. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17424. this.mainSoundTrack.soundCollection[i].pause();
  17425. }
  17426. for (i = 0; i < this.soundTracks.length; i++) {
  17427. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17428. this.soundTracks[i].soundCollection[j].pause();
  17429. }
  17430. }
  17431. };
  17432. Scene.prototype._enableAudio = function () {
  17433. var i;
  17434. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17435. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17436. this.mainSoundTrack.soundCollection[i].play();
  17437. }
  17438. }
  17439. for (i = 0; i < this.soundTracks.length; i++) {
  17440. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17441. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17442. this.soundTracks[i].soundCollection[j].play();
  17443. }
  17444. }
  17445. }
  17446. };
  17447. Object.defineProperty(Scene.prototype, "headphone", {
  17448. get: function () {
  17449. return this._headphone;
  17450. },
  17451. set: function (value) {
  17452. this._headphone = value;
  17453. if (BABYLON.AudioEngine) {
  17454. if (this._headphone) {
  17455. this._switchAudioModeForHeadphones();
  17456. }
  17457. else {
  17458. this._switchAudioModeForNormalSpeakers();
  17459. }
  17460. }
  17461. },
  17462. enumerable: true,
  17463. configurable: true
  17464. });
  17465. Scene.prototype._switchAudioModeForHeadphones = function () {
  17466. this.mainSoundTrack.switchPanningModelToHRTF();
  17467. for (var i = 0; i < this.soundTracks.length; i++) {
  17468. this.soundTracks[i].switchPanningModelToHRTF();
  17469. }
  17470. };
  17471. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17472. this.mainSoundTrack.switchPanningModelToEqualPower();
  17473. for (var i = 0; i < this.soundTracks.length; i++) {
  17474. this.soundTracks[i].switchPanningModelToEqualPower();
  17475. }
  17476. };
  17477. Scene.prototype.enableDepthRenderer = function () {
  17478. if (this._depthRenderer) {
  17479. return this._depthRenderer;
  17480. }
  17481. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17482. return this._depthRenderer;
  17483. };
  17484. Scene.prototype.disableDepthRenderer = function () {
  17485. if (!this._depthRenderer) {
  17486. return;
  17487. }
  17488. this._depthRenderer.dispose();
  17489. this._depthRenderer = null;
  17490. };
  17491. Scene.prototype.freezeMaterials = function () {
  17492. for (var i = 0; i < this.materials.length; i++) {
  17493. this.materials[i].freeze();
  17494. }
  17495. };
  17496. Scene.prototype.unfreezeMaterials = function () {
  17497. for (var i = 0; i < this.materials.length; i++) {
  17498. this.materials[i].unfreeze();
  17499. }
  17500. };
  17501. Scene.prototype.dispose = function () {
  17502. this.beforeRender = null;
  17503. this.afterRender = null;
  17504. this.skeletons = [];
  17505. this._boundingBoxRenderer.dispose();
  17506. if (this._depthRenderer) {
  17507. this._depthRenderer.dispose();
  17508. }
  17509. // Debug layer
  17510. if (this._debugLayer) {
  17511. this._debugLayer.hide();
  17512. }
  17513. // Events
  17514. this.onDisposeObservable.notifyObservers(this);
  17515. this.onDisposeObservable.clear();
  17516. this.onBeforeRenderObservable.clear();
  17517. this.onAfterRenderObservable.clear();
  17518. this.detachControl();
  17519. // Release sounds & sounds tracks
  17520. if (BABYLON.AudioEngine) {
  17521. this.disposeSounds();
  17522. }
  17523. // Detach cameras
  17524. var canvas = this._engine.getRenderingCanvas();
  17525. var index;
  17526. for (index = 0; index < this.cameras.length; index++) {
  17527. this.cameras[index].detachControl(canvas);
  17528. }
  17529. // Release lights
  17530. while (this.lights.length) {
  17531. this.lights[0].dispose();
  17532. }
  17533. // Release meshes
  17534. while (this.meshes.length) {
  17535. this.meshes[0].dispose(true);
  17536. }
  17537. // Release cameras
  17538. while (this.cameras.length) {
  17539. this.cameras[0].dispose();
  17540. }
  17541. // Release materials
  17542. while (this.materials.length) {
  17543. this.materials[0].dispose();
  17544. }
  17545. // Release particles
  17546. while (this.particleSystems.length) {
  17547. this.particleSystems[0].dispose();
  17548. }
  17549. // Release sprites
  17550. while (this.spriteManagers.length) {
  17551. this.spriteManagers[0].dispose();
  17552. }
  17553. // Release layers
  17554. while (this.layers.length) {
  17555. this.layers[0].dispose();
  17556. }
  17557. // Release textures
  17558. while (this.textures.length) {
  17559. this.textures[0].dispose();
  17560. }
  17561. // Post-processes
  17562. this.postProcessManager.dispose();
  17563. // Physics
  17564. if (this._physicsEngine) {
  17565. this.disablePhysicsEngine();
  17566. }
  17567. // Remove from engine
  17568. index = this._engine.scenes.indexOf(this);
  17569. if (index > -1) {
  17570. this._engine.scenes.splice(index, 1);
  17571. }
  17572. this._engine.wipeCaches();
  17573. };
  17574. // Release sounds & sounds tracks
  17575. Scene.prototype.disposeSounds = function () {
  17576. this.mainSoundTrack.dispose();
  17577. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  17578. this.soundTracks[scIndex].dispose();
  17579. }
  17580. };
  17581. // Octrees
  17582. Scene.prototype.getWorldExtends = function () {
  17583. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17584. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17585. for (var index = 0; index < this.meshes.length; index++) {
  17586. var mesh = this.meshes[index];
  17587. mesh.computeWorldMatrix(true);
  17588. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  17589. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  17590. BABYLON.Tools.CheckExtends(minBox, min, max);
  17591. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17592. }
  17593. return {
  17594. min: min,
  17595. max: max
  17596. };
  17597. };
  17598. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  17599. if (maxCapacity === void 0) { maxCapacity = 64; }
  17600. if (maxDepth === void 0) { maxDepth = 2; }
  17601. if (!this._selectionOctree) {
  17602. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  17603. }
  17604. var worldExtends = this.getWorldExtends();
  17605. // Update octree
  17606. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  17607. return this._selectionOctree;
  17608. };
  17609. // Picking
  17610. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  17611. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  17612. var engine = this._engine;
  17613. if (!camera) {
  17614. if (!this.activeCamera)
  17615. throw new Error("Active camera not set");
  17616. camera = this.activeCamera;
  17617. }
  17618. var cameraViewport = camera.viewport;
  17619. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17620. // Moving coordinates to local viewport world
  17621. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17622. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17623. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  17624. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  17625. };
  17626. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  17627. var engine = this._engine;
  17628. if (!camera) {
  17629. if (!this.activeCamera)
  17630. throw new Error("Active camera not set");
  17631. camera = this.activeCamera;
  17632. }
  17633. var cameraViewport = camera.viewport;
  17634. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17635. var identity = BABYLON.Matrix.Identity();
  17636. // Moving coordinates to local viewport world
  17637. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17638. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17639. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  17640. };
  17641. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  17642. var pickingInfo = null;
  17643. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17644. var mesh = this.meshes[meshIndex];
  17645. if (predicate) {
  17646. if (!predicate(mesh)) {
  17647. continue;
  17648. }
  17649. }
  17650. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17651. continue;
  17652. }
  17653. var world = mesh.getWorldMatrix();
  17654. var ray = rayFunction(world);
  17655. var result = mesh.intersects(ray, fastCheck);
  17656. if (!result || !result.hit)
  17657. continue;
  17658. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17659. continue;
  17660. pickingInfo = result;
  17661. if (fastCheck) {
  17662. break;
  17663. }
  17664. }
  17665. return pickingInfo || new BABYLON.PickingInfo();
  17666. };
  17667. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  17668. var pickingInfo = null;
  17669. camera = camera || this.activeCamera;
  17670. if (this.spriteManagers.length > 0) {
  17671. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  17672. var spriteManager = this.spriteManagers[spriteIndex];
  17673. if (!spriteManager.isPickable) {
  17674. continue;
  17675. }
  17676. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  17677. if (!result || !result.hit)
  17678. continue;
  17679. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17680. continue;
  17681. pickingInfo = result;
  17682. if (fastCheck) {
  17683. break;
  17684. }
  17685. }
  17686. }
  17687. return pickingInfo || new BABYLON.PickingInfo();
  17688. };
  17689. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  17690. var _this = this;
  17691. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17692. /// <param name="x">X position on screen</param>
  17693. /// <param name="y">Y position on screen</param>
  17694. /// <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>
  17695. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17696. /// <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>
  17697. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  17698. };
  17699. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  17700. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17701. /// <param name="x">X position on screen</param>
  17702. /// <param name="y">Y position on screen</param>
  17703. /// <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>
  17704. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17705. /// <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>
  17706. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  17707. };
  17708. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  17709. var _this = this;
  17710. return this._internalPick(function (world) {
  17711. if (!_this._pickWithRayInverseMatrix) {
  17712. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  17713. }
  17714. world.invertToRef(_this._pickWithRayInverseMatrix);
  17715. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  17716. }, predicate, fastCheck);
  17717. };
  17718. Scene.prototype.setPointerOverMesh = function (mesh) {
  17719. if (this._pointerOverMesh === mesh) {
  17720. return;
  17721. }
  17722. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17723. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17724. }
  17725. this._pointerOverMesh = mesh;
  17726. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17727. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17728. }
  17729. };
  17730. Scene.prototype.getPointerOverMesh = function () {
  17731. return this._pointerOverMesh;
  17732. };
  17733. Scene.prototype.setPointerOverSprite = function (sprite) {
  17734. if (this._pointerOverSprite === sprite) {
  17735. return;
  17736. }
  17737. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17738. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17739. }
  17740. this._pointerOverSprite = sprite;
  17741. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17742. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17743. }
  17744. };
  17745. Scene.prototype.getPointerOverSprite = function () {
  17746. return this._pointerOverSprite;
  17747. };
  17748. // Physics
  17749. Scene.prototype.getPhysicsEngine = function () {
  17750. return this._physicsEngine;
  17751. };
  17752. /**
  17753. * Enables physics to the current scene
  17754. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  17755. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  17756. * @return {boolean} was the physics engine initialized
  17757. */
  17758. Scene.prototype.enablePhysics = function (gravity, plugin) {
  17759. if (this._physicsEngine) {
  17760. return true;
  17761. }
  17762. try {
  17763. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  17764. return true;
  17765. }
  17766. catch (e) {
  17767. BABYLON.Tools.Error(e.message);
  17768. return false;
  17769. }
  17770. };
  17771. Scene.prototype.disablePhysicsEngine = function () {
  17772. if (!this._physicsEngine) {
  17773. return;
  17774. }
  17775. this._physicsEngine.dispose();
  17776. this._physicsEngine = undefined;
  17777. };
  17778. Scene.prototype.isPhysicsEnabled = function () {
  17779. return this._physicsEngine !== undefined;
  17780. };
  17781. /**
  17782. *
  17783. * Sets the gravity of the physics engine (and NOT of the scene)
  17784. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  17785. */
  17786. Scene.prototype.setGravity = function (gravity) {
  17787. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  17788. if (!this._physicsEngine) {
  17789. return;
  17790. }
  17791. this._physicsEngine.setGravity(gravity);
  17792. };
  17793. /**
  17794. * Legacy support, using the new API
  17795. * @Deprecated
  17796. */
  17797. Scene.prototype.createCompoundImpostor = function (parts, options) {
  17798. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  17799. if (parts.parts) {
  17800. options = parts;
  17801. parts = parts.parts;
  17802. }
  17803. var mainMesh = parts[0].mesh;
  17804. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  17805. for (var index = 1; index < parts.length; index++) {
  17806. var mesh = parts[index].mesh;
  17807. if (mesh.parent !== mainMesh) {
  17808. mesh.position = mesh.position.subtract(mainMesh.position);
  17809. mesh.parent = mainMesh;
  17810. }
  17811. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  17812. }
  17813. mainMesh.physicsImpostor.forceUpdate();
  17814. };
  17815. Scene.prototype.deleteCompoundImpostor = function (compound) {
  17816. var mesh = compound.parts[0].mesh;
  17817. mesh.physicsImpostor.dispose();
  17818. mesh.physicsImpostor = null;
  17819. };
  17820. // Misc.
  17821. Scene.prototype.createDefaultCameraOrLight = function () {
  17822. // Light
  17823. if (this.lights.length === 0) {
  17824. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  17825. }
  17826. // Camera
  17827. if (!this.activeCamera) {
  17828. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  17829. // Compute position
  17830. var worldExtends = this.getWorldExtends();
  17831. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  17832. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  17833. camera.setTarget(worldCenter);
  17834. this.activeCamera = camera;
  17835. }
  17836. };
  17837. // Tags
  17838. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  17839. if (tagsQuery === undefined) {
  17840. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  17841. return list;
  17842. }
  17843. var listByTags = [];
  17844. forEach = forEach || (function (item) { return; });
  17845. for (var i in list) {
  17846. var item = list[i];
  17847. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  17848. listByTags.push(item);
  17849. forEach(item);
  17850. }
  17851. }
  17852. return listByTags;
  17853. };
  17854. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  17855. return this._getByTags(this.meshes, tagsQuery, forEach);
  17856. };
  17857. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  17858. return this._getByTags(this.cameras, tagsQuery, forEach);
  17859. };
  17860. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  17861. return this._getByTags(this.lights, tagsQuery, forEach);
  17862. };
  17863. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  17864. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  17865. };
  17866. /**
  17867. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  17868. * This allowed control for front to back rendering or reversly depending of the special needs.
  17869. *
  17870. * @param renderingGroupId The rendering group id corresponding to its index
  17871. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  17872. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  17873. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  17874. */
  17875. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17876. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17877. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17878. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17879. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  17880. };
  17881. /**
  17882. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  17883. *
  17884. * @param renderingGroupId The rendering group id corresponding to its index
  17885. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  17886. */
  17887. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  17888. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  17889. };
  17890. // Statics
  17891. Scene._FOGMODE_NONE = 0;
  17892. Scene._FOGMODE_EXP = 1;
  17893. Scene._FOGMODE_EXP2 = 2;
  17894. Scene._FOGMODE_LINEAR = 3;
  17895. Scene.MinDeltaTime = 1.0;
  17896. Scene.MaxDeltaTime = 1000.0;
  17897. return Scene;
  17898. })();
  17899. BABYLON.Scene = Scene;
  17900. })(BABYLON || (BABYLON = {}));
  17901. var BABYLON;
  17902. (function (BABYLON) {
  17903. var Buffer = (function () {
  17904. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  17905. if (engine instanceof BABYLON.Mesh) {
  17906. this._engine = engine.getScene().getEngine();
  17907. }
  17908. else {
  17909. this._engine = engine;
  17910. }
  17911. this._updatable = updatable;
  17912. this._data = data;
  17913. this._strideSize = stride;
  17914. if (!postponeInternalCreation) {
  17915. this.create();
  17916. }
  17917. this._instanced = instanced;
  17918. }
  17919. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  17920. // a lot of these parameters are ignored as they are overriden by the buffer
  17921. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  17922. };
  17923. // Properties
  17924. Buffer.prototype.isUpdatable = function () {
  17925. return this._updatable;
  17926. };
  17927. Buffer.prototype.getData = function () {
  17928. return this._data;
  17929. };
  17930. Buffer.prototype.getBuffer = function () {
  17931. return this._buffer;
  17932. };
  17933. Buffer.prototype.getStrideSize = function () {
  17934. return this._strideSize;
  17935. };
  17936. Buffer.prototype.getIsInstanced = function () {
  17937. return this._instanced;
  17938. };
  17939. // Methods
  17940. Buffer.prototype.create = function (data) {
  17941. if (!data && this._buffer) {
  17942. return; // nothing to do
  17943. }
  17944. data = data || this._data;
  17945. if (!this._buffer) {
  17946. if (this._updatable) {
  17947. this._buffer = this._engine.createDynamicVertexBuffer(data);
  17948. this._data = data;
  17949. }
  17950. else {
  17951. this._buffer = this._engine.createVertexBuffer(data);
  17952. }
  17953. }
  17954. else if (this._updatable) {
  17955. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  17956. this._data = data;
  17957. }
  17958. };
  17959. Buffer.prototype.update = function (data) {
  17960. this.create(data);
  17961. };
  17962. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  17963. if (!this._buffer) {
  17964. return;
  17965. }
  17966. if (this._updatable) {
  17967. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  17968. this._data = null;
  17969. }
  17970. };
  17971. Buffer.prototype.dispose = function () {
  17972. if (!this._buffer) {
  17973. return;
  17974. }
  17975. if (this._engine._releaseBuffer(this._buffer)) {
  17976. this._buffer = null;
  17977. }
  17978. };
  17979. return Buffer;
  17980. })();
  17981. BABYLON.Buffer = Buffer;
  17982. })(BABYLON || (BABYLON = {}));
  17983. var BABYLON;
  17984. (function (BABYLON) {
  17985. var VertexBuffer = (function () {
  17986. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  17987. if (!stride) {
  17988. // Deduce stride from kind
  17989. switch (kind) {
  17990. case VertexBuffer.PositionKind:
  17991. stride = 3;
  17992. break;
  17993. case VertexBuffer.NormalKind:
  17994. stride = 3;
  17995. break;
  17996. case VertexBuffer.UVKind:
  17997. case VertexBuffer.UV2Kind:
  17998. case VertexBuffer.UV3Kind:
  17999. case VertexBuffer.UV4Kind:
  18000. case VertexBuffer.UV5Kind:
  18001. case VertexBuffer.UV6Kind:
  18002. stride = 2;
  18003. break;
  18004. case VertexBuffer.ColorKind:
  18005. stride = 4;
  18006. break;
  18007. case VertexBuffer.MatricesIndicesKind:
  18008. case VertexBuffer.MatricesIndicesExtraKind:
  18009. stride = 4;
  18010. break;
  18011. case VertexBuffer.MatricesWeightsKind:
  18012. case VertexBuffer.MatricesWeightsExtraKind:
  18013. stride = 4;
  18014. break;
  18015. }
  18016. }
  18017. if (data instanceof BABYLON.Buffer) {
  18018. if (!stride) {
  18019. stride = data.getStrideSize();
  18020. }
  18021. this._buffer = data;
  18022. this._ownsBuffer = false;
  18023. }
  18024. else {
  18025. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18026. this._ownsBuffer = true;
  18027. }
  18028. this._stride = stride;
  18029. this._offset = offset ? offset : 0;
  18030. this._size = size ? size : stride;
  18031. this._kind = kind;
  18032. }
  18033. VertexBuffer.prototype.getKind = function () {
  18034. return this._kind;
  18035. };
  18036. // Properties
  18037. VertexBuffer.prototype.isUpdatable = function () {
  18038. return this._buffer.isUpdatable();
  18039. };
  18040. VertexBuffer.prototype.getData = function () {
  18041. return this._buffer.getData();
  18042. };
  18043. VertexBuffer.prototype.getBuffer = function () {
  18044. return this._buffer.getBuffer();
  18045. };
  18046. VertexBuffer.prototype.getStrideSize = function () {
  18047. return this._stride;
  18048. };
  18049. VertexBuffer.prototype.getOffset = function () {
  18050. return this._offset;
  18051. };
  18052. VertexBuffer.prototype.getSize = function () {
  18053. return this._size;
  18054. };
  18055. VertexBuffer.prototype.getIsInstanced = function () {
  18056. return this._buffer.getIsInstanced();
  18057. };
  18058. // Methods
  18059. VertexBuffer.prototype.create = function (data) {
  18060. return this._buffer.create(data);
  18061. };
  18062. VertexBuffer.prototype.update = function (data) {
  18063. return this._buffer.update(data);
  18064. };
  18065. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18066. return this._buffer.updateDirectly(data, offset);
  18067. };
  18068. VertexBuffer.prototype.dispose = function () {
  18069. if (this._ownsBuffer) {
  18070. this._buffer.dispose();
  18071. }
  18072. };
  18073. Object.defineProperty(VertexBuffer, "PositionKind", {
  18074. get: function () {
  18075. return VertexBuffer._PositionKind;
  18076. },
  18077. enumerable: true,
  18078. configurable: true
  18079. });
  18080. Object.defineProperty(VertexBuffer, "NormalKind", {
  18081. get: function () {
  18082. return VertexBuffer._NormalKind;
  18083. },
  18084. enumerable: true,
  18085. configurable: true
  18086. });
  18087. Object.defineProperty(VertexBuffer, "UVKind", {
  18088. get: function () {
  18089. return VertexBuffer._UVKind;
  18090. },
  18091. enumerable: true,
  18092. configurable: true
  18093. });
  18094. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18095. get: function () {
  18096. return VertexBuffer._UV2Kind;
  18097. },
  18098. enumerable: true,
  18099. configurable: true
  18100. });
  18101. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18102. get: function () {
  18103. return VertexBuffer._UV3Kind;
  18104. },
  18105. enumerable: true,
  18106. configurable: true
  18107. });
  18108. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18109. get: function () {
  18110. return VertexBuffer._UV4Kind;
  18111. },
  18112. enumerable: true,
  18113. configurable: true
  18114. });
  18115. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18116. get: function () {
  18117. return VertexBuffer._UV5Kind;
  18118. },
  18119. enumerable: true,
  18120. configurable: true
  18121. });
  18122. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18123. get: function () {
  18124. return VertexBuffer._UV6Kind;
  18125. },
  18126. enumerable: true,
  18127. configurable: true
  18128. });
  18129. Object.defineProperty(VertexBuffer, "ColorKind", {
  18130. get: function () {
  18131. return VertexBuffer._ColorKind;
  18132. },
  18133. enumerable: true,
  18134. configurable: true
  18135. });
  18136. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18137. get: function () {
  18138. return VertexBuffer._MatricesIndicesKind;
  18139. },
  18140. enumerable: true,
  18141. configurable: true
  18142. });
  18143. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18144. get: function () {
  18145. return VertexBuffer._MatricesWeightsKind;
  18146. },
  18147. enumerable: true,
  18148. configurable: true
  18149. });
  18150. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18151. get: function () {
  18152. return VertexBuffer._MatricesIndicesExtraKind;
  18153. },
  18154. enumerable: true,
  18155. configurable: true
  18156. });
  18157. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18158. get: function () {
  18159. return VertexBuffer._MatricesWeightsExtraKind;
  18160. },
  18161. enumerable: true,
  18162. configurable: true
  18163. });
  18164. // Enums
  18165. VertexBuffer._PositionKind = "position";
  18166. VertexBuffer._NormalKind = "normal";
  18167. VertexBuffer._UVKind = "uv";
  18168. VertexBuffer._UV2Kind = "uv2";
  18169. VertexBuffer._UV3Kind = "uv3";
  18170. VertexBuffer._UV4Kind = "uv4";
  18171. VertexBuffer._UV5Kind = "uv5";
  18172. VertexBuffer._UV6Kind = "uv6";
  18173. VertexBuffer._ColorKind = "color";
  18174. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18175. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18176. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18177. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18178. return VertexBuffer;
  18179. })();
  18180. BABYLON.VertexBuffer = VertexBuffer;
  18181. })(BABYLON || (BABYLON = {}));
  18182. var BABYLON;
  18183. (function (BABYLON) {
  18184. /**
  18185. * Creates an instance based on a source mesh.
  18186. */
  18187. var InstancedMesh = (function (_super) {
  18188. __extends(InstancedMesh, _super);
  18189. function InstancedMesh(name, source) {
  18190. _super.call(this, name, source.getScene());
  18191. source.instances.push(this);
  18192. this._sourceMesh = source;
  18193. this.position.copyFrom(source.position);
  18194. this.rotation.copyFrom(source.rotation);
  18195. this.scaling.copyFrom(source.scaling);
  18196. if (source.rotationQuaternion) {
  18197. this.rotationQuaternion = source.rotationQuaternion.clone();
  18198. }
  18199. this.infiniteDistance = source.infiniteDistance;
  18200. this.setPivotMatrix(source.getPivotMatrix());
  18201. this.refreshBoundingInfo();
  18202. this._syncSubMeshes();
  18203. }
  18204. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  18205. // Methods
  18206. get: function () {
  18207. return this._sourceMesh.receiveShadows;
  18208. },
  18209. enumerable: true,
  18210. configurable: true
  18211. });
  18212. Object.defineProperty(InstancedMesh.prototype, "material", {
  18213. get: function () {
  18214. return this._sourceMesh.material;
  18215. },
  18216. enumerable: true,
  18217. configurable: true
  18218. });
  18219. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  18220. get: function () {
  18221. return this._sourceMesh.visibility;
  18222. },
  18223. enumerable: true,
  18224. configurable: true
  18225. });
  18226. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  18227. get: function () {
  18228. return this._sourceMesh.skeleton;
  18229. },
  18230. enumerable: true,
  18231. configurable: true
  18232. });
  18233. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  18234. get: function () {
  18235. return this._sourceMesh.renderingGroupId;
  18236. },
  18237. enumerable: true,
  18238. configurable: true
  18239. });
  18240. InstancedMesh.prototype.getTotalVertices = function () {
  18241. return this._sourceMesh.getTotalVertices();
  18242. };
  18243. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  18244. get: function () {
  18245. return this._sourceMesh;
  18246. },
  18247. enumerable: true,
  18248. configurable: true
  18249. });
  18250. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18251. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  18252. };
  18253. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  18254. return this._sourceMesh.isVerticesDataPresent(kind);
  18255. };
  18256. InstancedMesh.prototype.getIndices = function () {
  18257. return this._sourceMesh.getIndices();
  18258. };
  18259. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  18260. get: function () {
  18261. return this._sourceMesh._positions;
  18262. },
  18263. enumerable: true,
  18264. configurable: true
  18265. });
  18266. InstancedMesh.prototype.refreshBoundingInfo = function () {
  18267. var meshBB = this._sourceMesh.getBoundingInfo();
  18268. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  18269. this._updateBoundingInfo();
  18270. };
  18271. InstancedMesh.prototype._preActivate = function () {
  18272. if (this._currentLOD) {
  18273. this._currentLOD._preActivate();
  18274. }
  18275. };
  18276. InstancedMesh.prototype._activate = function (renderId) {
  18277. if (this._currentLOD) {
  18278. this._currentLOD._registerInstanceForRenderId(this, renderId);
  18279. }
  18280. };
  18281. InstancedMesh.prototype.getLOD = function (camera) {
  18282. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  18283. if (this._currentLOD === this.sourceMesh) {
  18284. return this;
  18285. }
  18286. return this._currentLOD;
  18287. };
  18288. InstancedMesh.prototype._syncSubMeshes = function () {
  18289. this.releaseSubMeshes();
  18290. if (this._sourceMesh.subMeshes) {
  18291. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  18292. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  18293. }
  18294. }
  18295. };
  18296. InstancedMesh.prototype._generatePointsArray = function () {
  18297. return this._sourceMesh._generatePointsArray();
  18298. };
  18299. // Clone
  18300. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18301. var result = this._sourceMesh.createInstance(name);
  18302. // Deep copy
  18303. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  18304. // Bounding info
  18305. this.refreshBoundingInfo();
  18306. // Parent
  18307. if (newParent) {
  18308. result.parent = newParent;
  18309. }
  18310. if (!doNotCloneChildren) {
  18311. // Children
  18312. for (var index = 0; index < this.getScene().meshes.length; index++) {
  18313. var mesh = this.getScene().meshes[index];
  18314. if (mesh.parent === this) {
  18315. mesh.clone(mesh.name, result);
  18316. }
  18317. }
  18318. }
  18319. result.computeWorldMatrix(true);
  18320. return result;
  18321. };
  18322. // Dispoe
  18323. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  18324. // Remove from mesh
  18325. var index = this._sourceMesh.instances.indexOf(this);
  18326. this._sourceMesh.instances.splice(index, 1);
  18327. _super.prototype.dispose.call(this, doNotRecurse);
  18328. };
  18329. return InstancedMesh;
  18330. })(BABYLON.AbstractMesh);
  18331. BABYLON.InstancedMesh = InstancedMesh;
  18332. })(BABYLON || (BABYLON = {}));
  18333. var BABYLON;
  18334. (function (BABYLON) {
  18335. var _InstancesBatch = (function () {
  18336. function _InstancesBatch() {
  18337. this.mustReturn = false;
  18338. this.visibleInstances = new Array();
  18339. this.renderSelf = new Array();
  18340. }
  18341. return _InstancesBatch;
  18342. })();
  18343. BABYLON._InstancesBatch = _InstancesBatch;
  18344. var Mesh = (function (_super) {
  18345. __extends(Mesh, _super);
  18346. /**
  18347. * @constructor
  18348. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  18349. * @param {Scene} scene The scene to add this mesh to.
  18350. * @param {Node} parent The parent of this mesh, if it has one
  18351. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  18352. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  18353. * When false, achieved by calling a clone(), also passing False.
  18354. * This will make creation of children, recursive.
  18355. */
  18356. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  18357. if (parent === void 0) { parent = null; }
  18358. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  18359. _super.call(this, name, scene);
  18360. // Events
  18361. /**
  18362. * An event triggered before rendering the mesh
  18363. * @type {BABYLON.Observable}
  18364. */
  18365. this.onBeforeRenderObservable = new BABYLON.Observable();
  18366. /**
  18367. * An event triggered after rendering the mesh
  18368. * @type {BABYLON.Observable}
  18369. */
  18370. this.onAfterRenderObservable = new BABYLON.Observable();
  18371. /**
  18372. * An event triggered before drawing the mesh
  18373. * @type {BABYLON.Observable}
  18374. */
  18375. this.onBeforeDrawObservable = new BABYLON.Observable();
  18376. // Members
  18377. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18378. this.instances = new Array();
  18379. this._LODLevels = new Array();
  18380. this._visibleInstances = {};
  18381. this._renderIdForInstances = new Array();
  18382. this._batchCache = new _InstancesBatch();
  18383. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  18384. this._sideOrientation = Mesh._DEFAULTSIDE;
  18385. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  18386. if (source) {
  18387. // Geometry
  18388. if (source._geometry) {
  18389. source._geometry.applyToMesh(this);
  18390. }
  18391. // Deep copy
  18392. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  18393. // Pivot
  18394. this.setPivotMatrix(source.getPivotMatrix());
  18395. this.id = name + "." + source.id;
  18396. // Material
  18397. this.material = source.material;
  18398. var index;
  18399. if (!doNotCloneChildren) {
  18400. // Children
  18401. for (index = 0; index < scene.meshes.length; index++) {
  18402. var mesh = scene.meshes[index];
  18403. if (mesh.parent === source) {
  18404. // doNotCloneChildren is always going to be False
  18405. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  18406. }
  18407. }
  18408. }
  18409. // Physics clone
  18410. var physicsEngine = this.getScene().getPhysicsEngine();
  18411. if (clonePhysicsImpostor && physicsEngine) {
  18412. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  18413. if (impostor) {
  18414. this.physicsImpostor = impostor.clone(this);
  18415. }
  18416. }
  18417. // Particles
  18418. for (index = 0; index < scene.particleSystems.length; index++) {
  18419. var system = scene.particleSystems[index];
  18420. if (system.emitter === source) {
  18421. system.clone(system.name, this);
  18422. }
  18423. }
  18424. this.computeWorldMatrix(true);
  18425. }
  18426. // Parent
  18427. if (parent !== null) {
  18428. this.parent = parent;
  18429. }
  18430. }
  18431. Object.defineProperty(Mesh, "FRONTSIDE", {
  18432. /**
  18433. * Mesh side orientation : usually the external or front surface
  18434. */
  18435. get: function () {
  18436. return Mesh._FRONTSIDE;
  18437. },
  18438. enumerable: true,
  18439. configurable: true
  18440. });
  18441. Object.defineProperty(Mesh, "BACKSIDE", {
  18442. /**
  18443. * Mesh side orientation : usually the internal or back surface
  18444. */
  18445. get: function () {
  18446. return Mesh._BACKSIDE;
  18447. },
  18448. enumerable: true,
  18449. configurable: true
  18450. });
  18451. Object.defineProperty(Mesh, "DOUBLESIDE", {
  18452. /**
  18453. * Mesh side orientation : both internal and external or front and back surfaces
  18454. */
  18455. get: function () {
  18456. return Mesh._DOUBLESIDE;
  18457. },
  18458. enumerable: true,
  18459. configurable: true
  18460. });
  18461. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  18462. /**
  18463. * Mesh side orientation : by default, `FRONTSIDE`
  18464. */
  18465. get: function () {
  18466. return Mesh._DEFAULTSIDE;
  18467. },
  18468. enumerable: true,
  18469. configurable: true
  18470. });
  18471. Object.defineProperty(Mesh, "NO_CAP", {
  18472. /**
  18473. * Mesh cap setting : no cap
  18474. */
  18475. get: function () {
  18476. return Mesh._NO_CAP;
  18477. },
  18478. enumerable: true,
  18479. configurable: true
  18480. });
  18481. Object.defineProperty(Mesh, "CAP_START", {
  18482. /**
  18483. * Mesh cap setting : one cap at the beginning of the mesh
  18484. */
  18485. get: function () {
  18486. return Mesh._CAP_START;
  18487. },
  18488. enumerable: true,
  18489. configurable: true
  18490. });
  18491. Object.defineProperty(Mesh, "CAP_END", {
  18492. /**
  18493. * Mesh cap setting : one cap at the end of the mesh
  18494. */
  18495. get: function () {
  18496. return Mesh._CAP_END;
  18497. },
  18498. enumerable: true,
  18499. configurable: true
  18500. });
  18501. Object.defineProperty(Mesh, "CAP_ALL", {
  18502. /**
  18503. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  18504. */
  18505. get: function () {
  18506. return Mesh._CAP_ALL;
  18507. },
  18508. enumerable: true,
  18509. configurable: true
  18510. });
  18511. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  18512. set: function (callback) {
  18513. if (this._onBeforeDrawObserver) {
  18514. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  18515. }
  18516. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  18517. },
  18518. enumerable: true,
  18519. configurable: true
  18520. });
  18521. // Methods
  18522. /**
  18523. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18524. */
  18525. Mesh.prototype.toString = function (fullDetails) {
  18526. var ret = _super.prototype.toString.call(this, fullDetails);
  18527. ret += ", n vertices: " + this.getTotalVertices();
  18528. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  18529. if (this.animations) {
  18530. for (var i = 0; i < this.animations.length; i++) {
  18531. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18532. }
  18533. }
  18534. if (fullDetails) {
  18535. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  18536. }
  18537. return ret;
  18538. };
  18539. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  18540. get: function () {
  18541. return this._LODLevels.length > 0;
  18542. },
  18543. enumerable: true,
  18544. configurable: true
  18545. });
  18546. Mesh.prototype._sortLODLevels = function () {
  18547. this._LODLevels.sort(function (a, b) {
  18548. if (a.distance < b.distance) {
  18549. return 1;
  18550. }
  18551. if (a.distance > b.distance) {
  18552. return -1;
  18553. }
  18554. return 0;
  18555. });
  18556. };
  18557. /**
  18558. * Add a mesh as LOD level triggered at the given distance.
  18559. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18560. * @param {number} distance The distance from the center of the object to show this level
  18561. * @param {Mesh} mesh The mesh to be added as LOD level
  18562. * @return {Mesh} This mesh (for chaining)
  18563. */
  18564. Mesh.prototype.addLODLevel = function (distance, mesh) {
  18565. if (mesh && mesh._masterMesh) {
  18566. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  18567. return this;
  18568. }
  18569. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  18570. this._LODLevels.push(level);
  18571. if (mesh) {
  18572. mesh._masterMesh = this;
  18573. }
  18574. this._sortLODLevels();
  18575. return this;
  18576. };
  18577. /**
  18578. * Returns the LOD level mesh at the passed distance or null if not found.
  18579. * It is related to the method `addLODLevel(distance, mesh)`.
  18580. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18581. */
  18582. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  18583. for (var index = 0; index < this._LODLevels.length; index++) {
  18584. var level = this._LODLevels[index];
  18585. if (level.distance === distance) {
  18586. return level.mesh;
  18587. }
  18588. }
  18589. return null;
  18590. };
  18591. /**
  18592. * Remove a mesh from the LOD array
  18593. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18594. * @param {Mesh} mesh The mesh to be removed.
  18595. * @return {Mesh} This mesh (for chaining)
  18596. */
  18597. Mesh.prototype.removeLODLevel = function (mesh) {
  18598. for (var index = 0; index < this._LODLevels.length; index++) {
  18599. if (this._LODLevels[index].mesh === mesh) {
  18600. this._LODLevels.splice(index, 1);
  18601. if (mesh) {
  18602. mesh._masterMesh = null;
  18603. }
  18604. }
  18605. }
  18606. this._sortLODLevels();
  18607. return this;
  18608. };
  18609. /**
  18610. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  18611. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18612. */
  18613. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  18614. if (!this._LODLevels || this._LODLevels.length === 0) {
  18615. return this;
  18616. }
  18617. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  18618. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  18619. if (this.onLODLevelSelection) {
  18620. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  18621. }
  18622. return this;
  18623. }
  18624. for (var index = 0; index < this._LODLevels.length; index++) {
  18625. var level = this._LODLevels[index];
  18626. if (level.distance < distanceToCamera) {
  18627. if (level.mesh) {
  18628. level.mesh._preActivate();
  18629. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18630. }
  18631. if (this.onLODLevelSelection) {
  18632. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  18633. }
  18634. return level.mesh;
  18635. }
  18636. }
  18637. if (this.onLODLevelSelection) {
  18638. this.onLODLevelSelection(distanceToCamera, this, this);
  18639. }
  18640. return this;
  18641. };
  18642. Object.defineProperty(Mesh.prototype, "geometry", {
  18643. /**
  18644. * Returns the mesh internal Geometry object.
  18645. */
  18646. get: function () {
  18647. return this._geometry;
  18648. },
  18649. enumerable: true,
  18650. configurable: true
  18651. });
  18652. /**
  18653. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  18654. */
  18655. Mesh.prototype.getTotalVertices = function () {
  18656. if (!this._geometry) {
  18657. return 0;
  18658. }
  18659. return this._geometry.getTotalVertices();
  18660. };
  18661. /**
  18662. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  18663. * 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.
  18664. * Returns null if the mesh has no geometry or no vertex buffer.
  18665. * Possible `kind` values :
  18666. * - BABYLON.VertexBuffer.PositionKind
  18667. * - BABYLON.VertexBuffer.UVKind
  18668. * - BABYLON.VertexBuffer.UV2Kind
  18669. * - BABYLON.VertexBuffer.UV3Kind
  18670. * - BABYLON.VertexBuffer.UV4Kind
  18671. * - BABYLON.VertexBuffer.UV5Kind
  18672. * - BABYLON.VertexBuffer.UV6Kind
  18673. * - BABYLON.VertexBuffer.ColorKind
  18674. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18675. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18676. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18677. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18678. */
  18679. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18680. if (!this._geometry) {
  18681. return null;
  18682. }
  18683. return this._geometry.getVerticesData(kind, copyWhenShared);
  18684. };
  18685. /**
  18686. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  18687. * Returns `undefined` if the mesh has no geometry.
  18688. * Possible `kind` values :
  18689. * - BABYLON.VertexBuffer.PositionKind
  18690. * - BABYLON.VertexBuffer.UVKind
  18691. * - BABYLON.VertexBuffer.UV2Kind
  18692. * - BABYLON.VertexBuffer.UV3Kind
  18693. * - BABYLON.VertexBuffer.UV4Kind
  18694. * - BABYLON.VertexBuffer.UV5Kind
  18695. * - BABYLON.VertexBuffer.UV6Kind
  18696. * - BABYLON.VertexBuffer.ColorKind
  18697. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18698. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18699. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18700. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18701. */
  18702. Mesh.prototype.getVertexBuffer = function (kind) {
  18703. if (!this._geometry) {
  18704. return undefined;
  18705. }
  18706. return this._geometry.getVertexBuffer(kind);
  18707. };
  18708. /**
  18709. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  18710. * Possible `kind` values :
  18711. * - BABYLON.VertexBuffer.PositionKind
  18712. * - BABYLON.VertexBuffer.UVKind
  18713. * - BABYLON.VertexBuffer.UV2Kind
  18714. * - BABYLON.VertexBuffer.UV3Kind
  18715. * - BABYLON.VertexBuffer.UV4Kind
  18716. * - BABYLON.VertexBuffer.UV5Kind
  18717. * - BABYLON.VertexBuffer.UV6Kind
  18718. * - BABYLON.VertexBuffer.ColorKind
  18719. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18720. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18721. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18722. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18723. */
  18724. Mesh.prototype.isVerticesDataPresent = function (kind) {
  18725. if (!this._geometry) {
  18726. if (this._delayInfo) {
  18727. return this._delayInfo.indexOf(kind) !== -1;
  18728. }
  18729. return false;
  18730. }
  18731. return this._geometry.isVerticesDataPresent(kind);
  18732. };
  18733. /**
  18734. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  18735. * Possible `kind` values :
  18736. * - BABYLON.VertexBuffer.PositionKind
  18737. * - BABYLON.VertexBuffer.UVKind
  18738. * - BABYLON.VertexBuffer.UV2Kind
  18739. * - BABYLON.VertexBuffer.UV3Kind
  18740. * - BABYLON.VertexBuffer.UV4Kind
  18741. * - BABYLON.VertexBuffer.UV5Kind
  18742. * - BABYLON.VertexBuffer.UV6Kind
  18743. * - BABYLON.VertexBuffer.ColorKind
  18744. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18745. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18746. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18747. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18748. */
  18749. Mesh.prototype.getVerticesDataKinds = function () {
  18750. if (!this._geometry) {
  18751. var result = [];
  18752. if (this._delayInfo) {
  18753. for (var kind in this._delayInfo) {
  18754. result.push(kind);
  18755. }
  18756. }
  18757. return result;
  18758. }
  18759. return this._geometry.getVerticesDataKinds();
  18760. };
  18761. /**
  18762. * Returns a positive integer : the total number of indices in this mesh geometry.
  18763. * Returns zero if the mesh has no geometry.
  18764. */
  18765. Mesh.prototype.getTotalIndices = function () {
  18766. if (!this._geometry) {
  18767. return 0;
  18768. }
  18769. return this._geometry.getTotalIndices();
  18770. };
  18771. /**
  18772. * Returns an array of integers or a Int32Array populated with the mesh indices.
  18773. * 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.
  18774. * Returns an empty array if the mesh has no geometry.
  18775. */
  18776. Mesh.prototype.getIndices = function (copyWhenShared) {
  18777. if (!this._geometry) {
  18778. return [];
  18779. }
  18780. return this._geometry.getIndices(copyWhenShared);
  18781. };
  18782. Object.defineProperty(Mesh.prototype, "isBlocked", {
  18783. get: function () {
  18784. return this._masterMesh !== null && this._masterMesh !== undefined;
  18785. },
  18786. enumerable: true,
  18787. configurable: true
  18788. });
  18789. /**
  18790. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  18791. */
  18792. Mesh.prototype.isReady = function () {
  18793. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18794. return false;
  18795. }
  18796. return _super.prototype.isReady.call(this);
  18797. };
  18798. /**
  18799. * Boolean : true if the mesh has been disposed.
  18800. */
  18801. Mesh.prototype.isDisposed = function () {
  18802. return this._isDisposed;
  18803. };
  18804. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  18805. get: function () {
  18806. return this._sideOrientation;
  18807. },
  18808. /**
  18809. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  18810. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  18811. */
  18812. set: function (sideO) {
  18813. this._sideOrientation = sideO;
  18814. },
  18815. enumerable: true,
  18816. configurable: true
  18817. });
  18818. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  18819. /**
  18820. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  18821. * This property is pertinent only for updatable parametric shapes.
  18822. */
  18823. get: function () {
  18824. return this._areNormalsFrozen;
  18825. },
  18826. enumerable: true,
  18827. configurable: true
  18828. });
  18829. /**
  18830. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18831. * It has no effect at all on other shapes.
  18832. * It prevents the mesh normals from being recomputed on next `positions` array update.
  18833. */
  18834. Mesh.prototype.freezeNormals = function () {
  18835. this._areNormalsFrozen = true;
  18836. };
  18837. /**
  18838. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18839. * It has no effect at all on other shapes.
  18840. * It reactivates the mesh normals computation if it was previously frozen.
  18841. */
  18842. Mesh.prototype.unfreezeNormals = function () {
  18843. this._areNormalsFrozen = false;
  18844. };
  18845. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  18846. /**
  18847. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  18848. */
  18849. set: function (count) {
  18850. this._overridenInstanceCount = count;
  18851. },
  18852. enumerable: true,
  18853. configurable: true
  18854. });
  18855. // Methods
  18856. Mesh.prototype._preActivate = function () {
  18857. var sceneRenderId = this.getScene().getRenderId();
  18858. if (this._preActivateId === sceneRenderId) {
  18859. return;
  18860. }
  18861. this._preActivateId = sceneRenderId;
  18862. this._visibleInstances = null;
  18863. };
  18864. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18865. if (this._visibleInstances) {
  18866. this._visibleInstances.intermediateDefaultRenderId = renderId;
  18867. }
  18868. };
  18869. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  18870. if (!this._visibleInstances) {
  18871. this._visibleInstances = {};
  18872. this._visibleInstances.defaultRenderId = renderId;
  18873. this._visibleInstances.selfDefaultRenderId = this._renderId;
  18874. }
  18875. if (!this._visibleInstances[renderId]) {
  18876. this._visibleInstances[renderId] = new Array();
  18877. }
  18878. this._visibleInstances[renderId].push(instance);
  18879. };
  18880. /**
  18881. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  18882. * This means the mesh underlying bounding box and sphere are recomputed.
  18883. */
  18884. Mesh.prototype.refreshBoundingInfo = function () {
  18885. if (this._boundingInfo.isLocked) {
  18886. return;
  18887. }
  18888. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18889. if (data) {
  18890. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  18891. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18892. }
  18893. if (this.subMeshes) {
  18894. for (var index = 0; index < this.subMeshes.length; index++) {
  18895. this.subMeshes[index].refreshBoundingInfo();
  18896. }
  18897. }
  18898. this._updateBoundingInfo();
  18899. };
  18900. Mesh.prototype._createGlobalSubMesh = function () {
  18901. var totalVertices = this.getTotalVertices();
  18902. if (!totalVertices || !this.getIndices()) {
  18903. return null;
  18904. }
  18905. this.releaseSubMeshes();
  18906. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  18907. };
  18908. Mesh.prototype.subdivide = function (count) {
  18909. if (count < 1) {
  18910. return;
  18911. }
  18912. var totalIndices = this.getTotalIndices();
  18913. var subdivisionSize = (totalIndices / count) | 0;
  18914. var offset = 0;
  18915. // Ensure that subdivisionSize is a multiple of 3
  18916. while (subdivisionSize % 3 !== 0) {
  18917. subdivisionSize++;
  18918. }
  18919. this.releaseSubMeshes();
  18920. for (var index = 0; index < count; index++) {
  18921. if (offset >= totalIndices) {
  18922. break;
  18923. }
  18924. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  18925. offset += subdivisionSize;
  18926. }
  18927. this.synchronizeInstances();
  18928. };
  18929. /**
  18930. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18931. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18932. * The `data` are either a numeric array either a Float32Array.
  18933. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18934. * 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).
  18935. * Note that a new underlying VertexBuffer object is created each call.
  18936. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18937. *
  18938. * Possible `kind` values :
  18939. * - BABYLON.VertexBuffer.PositionKind
  18940. * - BABYLON.VertexBuffer.UVKind
  18941. * - BABYLON.VertexBuffer.UV2Kind
  18942. * - BABYLON.VertexBuffer.UV3Kind
  18943. * - BABYLON.VertexBuffer.UV4Kind
  18944. * - BABYLON.VertexBuffer.UV5Kind
  18945. * - BABYLON.VertexBuffer.UV6Kind
  18946. * - BABYLON.VertexBuffer.ColorKind
  18947. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18948. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18949. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18950. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18951. */
  18952. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18953. if (!this._geometry) {
  18954. var vertexData = new BABYLON.VertexData();
  18955. vertexData.set(data, kind);
  18956. var scene = this.getScene();
  18957. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  18958. }
  18959. else {
  18960. this._geometry.setVerticesData(kind, data, updatable, stride);
  18961. }
  18962. };
  18963. Mesh.prototype.setVerticesBuffer = function (buffer) {
  18964. if (!this._geometry) {
  18965. var scene = this.getScene();
  18966. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  18967. }
  18968. this._geometry.setVerticesBuffer(buffer);
  18969. };
  18970. /**
  18971. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18972. * If the mesh has no geometry, it is simply returned as it is.
  18973. * The `data` are either a numeric array either a Float32Array.
  18974. * No new underlying VertexBuffer object is created.
  18975. * 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.
  18976. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18977. *
  18978. * Possible `kind` values :
  18979. * - BABYLON.VertexBuffer.PositionKind
  18980. * - BABYLON.VertexBuffer.UVKind
  18981. * - BABYLON.VertexBuffer.UV2Kind
  18982. * - BABYLON.VertexBuffer.UV3Kind
  18983. * - BABYLON.VertexBuffer.UV4Kind
  18984. * - BABYLON.VertexBuffer.UV5Kind
  18985. * - BABYLON.VertexBuffer.UV6Kind
  18986. * - BABYLON.VertexBuffer.ColorKind
  18987. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18988. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18989. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18990. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18991. */
  18992. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18993. if (!this._geometry) {
  18994. return;
  18995. }
  18996. if (!makeItUnique) {
  18997. this._geometry.updateVerticesData(kind, data, updateExtends);
  18998. }
  18999. else {
  19000. this.makeGeometryUnique();
  19001. this.updateVerticesData(kind, data, updateExtends, false);
  19002. }
  19003. };
  19004. /**
  19005. * Deprecated since BabylonJS v2.3
  19006. */
  19007. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  19008. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  19009. if (!this._geometry) {
  19010. return;
  19011. }
  19012. if (!makeItUnique) {
  19013. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  19014. }
  19015. else {
  19016. this.makeGeometryUnique();
  19017. this.updateVerticesDataDirectly(kind, data, offset, false);
  19018. }
  19019. };
  19020. /**
  19021. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  19022. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  19023. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  19024. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  19025. */
  19026. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  19027. if (computeNormals === void 0) { computeNormals = true; }
  19028. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19029. positionFunction(positions);
  19030. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19031. if (computeNormals) {
  19032. var indices = this.getIndices();
  19033. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19034. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19035. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19036. }
  19037. };
  19038. Mesh.prototype.makeGeometryUnique = function () {
  19039. if (!this._geometry) {
  19040. return;
  19041. }
  19042. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  19043. geometry.applyToMesh(this);
  19044. };
  19045. /**
  19046. * Sets the mesh indices.
  19047. * Expects an array populated with integers or a Int32Array.
  19048. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19049. * This method creates a new index buffer each call.
  19050. */
  19051. Mesh.prototype.setIndices = function (indices, totalVertices) {
  19052. if (!this._geometry) {
  19053. var vertexData = new BABYLON.VertexData();
  19054. vertexData.indices = indices;
  19055. var scene = this.getScene();
  19056. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  19057. }
  19058. else {
  19059. this._geometry.setIndices(indices, totalVertices);
  19060. }
  19061. };
  19062. /**
  19063. * Invert the geometry to move from a right handed system to a left handed one.
  19064. */
  19065. Mesh.prototype.toLeftHanded = function () {
  19066. if (!this._geometry) {
  19067. return;
  19068. }
  19069. this._geometry.toLeftHanded();
  19070. };
  19071. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  19072. var engine = this.getScene().getEngine();
  19073. // Wireframe
  19074. var indexToBind;
  19075. if (this._unIndexed) {
  19076. indexToBind = null;
  19077. }
  19078. else {
  19079. switch (fillMode) {
  19080. case BABYLON.Material.PointFillMode:
  19081. indexToBind = null;
  19082. break;
  19083. case BABYLON.Material.WireFrameFillMode:
  19084. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  19085. break;
  19086. default:
  19087. case BABYLON.Material.TriangleFillMode:
  19088. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  19089. break;
  19090. }
  19091. }
  19092. // VBOs
  19093. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  19094. };
  19095. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  19096. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19097. return;
  19098. }
  19099. this.onBeforeDrawObservable.notifyObservers(this);
  19100. var engine = this.getScene().getEngine();
  19101. // Draw order
  19102. switch (fillMode) {
  19103. case BABYLON.Material.PointFillMode:
  19104. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19105. break;
  19106. case BABYLON.Material.WireFrameFillMode:
  19107. if (this._unIndexed) {
  19108. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19109. }
  19110. else {
  19111. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  19112. }
  19113. break;
  19114. default:
  19115. if (this._unIndexed) {
  19116. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19117. }
  19118. else {
  19119. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  19120. }
  19121. }
  19122. };
  19123. /**
  19124. * Registers for this mesh a javascript function called just before the rendering process.
  19125. * This function is passed the current mesh and doesn't return anything.
  19126. */
  19127. Mesh.prototype.registerBeforeRender = function (func) {
  19128. this.onBeforeRenderObservable.add(func);
  19129. };
  19130. /**
  19131. * Disposes a previously registered javascript function called before the rendering.
  19132. * This function is passed the current mesh and doesn't return anything.
  19133. */
  19134. Mesh.prototype.unregisterBeforeRender = function (func) {
  19135. this.onBeforeRenderObservable.removeCallback(func);
  19136. };
  19137. /**
  19138. * Registers for this mesh a javascript function called just after the rendering is complete.
  19139. * This function is passed the current mesh and doesn't return anything.
  19140. */
  19141. Mesh.prototype.registerAfterRender = function (func) {
  19142. this.onAfterRenderObservable.add(func);
  19143. };
  19144. /**
  19145. * Disposes a previously registered javascript function called after the rendering.
  19146. * This function is passed the current mesh and doesn't return anything.
  19147. */
  19148. Mesh.prototype.unregisterAfterRender = function (func) {
  19149. this.onAfterRenderObservable.removeCallback(func);
  19150. };
  19151. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  19152. var scene = this.getScene();
  19153. this._batchCache.mustReturn = false;
  19154. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  19155. this._batchCache.visibleInstances[subMeshId] = null;
  19156. if (this._visibleInstances) {
  19157. var currentRenderId = scene.getRenderId();
  19158. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  19159. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  19160. var selfRenderId = this._renderId;
  19161. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  19162. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  19163. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  19164. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  19165. }
  19166. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  19167. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  19168. this._batchCache.mustReturn = true;
  19169. return this._batchCache;
  19170. }
  19171. if (currentRenderId !== selfRenderId) {
  19172. this._batchCache.renderSelf[subMeshId] = false;
  19173. }
  19174. }
  19175. this._renderIdForInstances[subMeshId] = currentRenderId;
  19176. }
  19177. return this._batchCache;
  19178. };
  19179. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  19180. var visibleInstances = batch.visibleInstances[subMesh._id];
  19181. var matricesCount = visibleInstances.length + 1;
  19182. var bufferSize = matricesCount * 16 * 4;
  19183. var currentInstancesBufferSize = this._instancesBufferSize;
  19184. var instancesBuffer = this._instancesBuffer;
  19185. while (this._instancesBufferSize < bufferSize) {
  19186. this._instancesBufferSize *= 2;
  19187. }
  19188. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  19189. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  19190. }
  19191. var offset = 0;
  19192. var instancesCount = 0;
  19193. var world = this.getWorldMatrix();
  19194. if (batch.renderSelf[subMesh._id]) {
  19195. world.copyToArray(this._instancesData, offset);
  19196. offset += 16;
  19197. instancesCount++;
  19198. }
  19199. if (visibleInstances) {
  19200. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  19201. var instance = visibleInstances[instanceIndex];
  19202. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  19203. offset += 16;
  19204. instancesCount++;
  19205. }
  19206. }
  19207. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  19208. if (instancesBuffer) {
  19209. instancesBuffer.dispose();
  19210. }
  19211. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  19212. this._instancesBuffer = instancesBuffer;
  19213. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  19214. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  19215. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  19216. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  19217. }
  19218. else {
  19219. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  19220. }
  19221. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  19222. this._draw(subMesh, fillMode, instancesCount);
  19223. engine.unbindInstanceAttributes();
  19224. };
  19225. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  19226. var scene = this.getScene();
  19227. var engine = scene.getEngine();
  19228. if (hardwareInstancedRendering) {
  19229. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  19230. }
  19231. else {
  19232. if (batch.renderSelf[subMesh._id]) {
  19233. // Draw
  19234. if (onBeforeDraw) {
  19235. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  19236. }
  19237. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  19238. }
  19239. if (batch.visibleInstances[subMesh._id]) {
  19240. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  19241. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  19242. // World
  19243. var world = instance.getWorldMatrix();
  19244. if (onBeforeDraw) {
  19245. onBeforeDraw(true, world, effectiveMaterial);
  19246. }
  19247. // Draw
  19248. this._draw(subMesh, fillMode);
  19249. }
  19250. }
  19251. }
  19252. };
  19253. /**
  19254. * Triggers the draw call for the mesh.
  19255. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  19256. */
  19257. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  19258. var scene = this.getScene();
  19259. // Managing instances
  19260. var batch = this._getInstancesRenderList(subMesh._id);
  19261. if (batch.mustReturn) {
  19262. return;
  19263. }
  19264. // Checking geometry state
  19265. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19266. return;
  19267. }
  19268. var callbackIndex;
  19269. this.onBeforeRenderObservable.notifyObservers(this);
  19270. var engine = scene.getEngine();
  19271. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  19272. // Material
  19273. var effectiveMaterial = subMesh.getMaterial();
  19274. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  19275. return;
  19276. }
  19277. // Outline - step 1
  19278. var savedDepthWrite = engine.getDepthWrite();
  19279. if (this.renderOutline) {
  19280. engine.setDepthWrite(false);
  19281. scene.getOutlineRenderer().render(subMesh, batch);
  19282. engine.setDepthWrite(savedDepthWrite);
  19283. }
  19284. effectiveMaterial._preBind();
  19285. var effect = effectiveMaterial.getEffect();
  19286. // Bind
  19287. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  19288. this._bind(subMesh, effect, fillMode);
  19289. var world = this.getWorldMatrix();
  19290. effectiveMaterial.bind(world, this);
  19291. // Alpha mode
  19292. if (enableAlphaMode) {
  19293. engine.setAlphaMode(effectiveMaterial.alphaMode);
  19294. }
  19295. // Draw
  19296. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw);
  19297. // Unbind
  19298. effectiveMaterial.unbind();
  19299. // Outline - step 2
  19300. if (this.renderOutline && savedDepthWrite) {
  19301. engine.setDepthWrite(true);
  19302. engine.setColorWrite(false);
  19303. scene.getOutlineRenderer().render(subMesh, batch);
  19304. engine.setColorWrite(true);
  19305. }
  19306. // Overlay
  19307. if (this.renderOverlay) {
  19308. var currentMode = engine.getAlphaMode();
  19309. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19310. scene.getOutlineRenderer().render(subMesh, batch, true);
  19311. engine.setAlphaMode(currentMode);
  19312. }
  19313. this.onAfterRenderObservable.notifyObservers(this);
  19314. };
  19315. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  19316. if (isInstance) {
  19317. effectiveMaterial.bindOnlyWorldMatrix(world);
  19318. }
  19319. };
  19320. /**
  19321. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  19322. */
  19323. Mesh.prototype.getEmittedParticleSystems = function () {
  19324. var results = new Array();
  19325. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19326. var particleSystem = this.getScene().particleSystems[index];
  19327. if (particleSystem.emitter === this) {
  19328. results.push(particleSystem);
  19329. }
  19330. }
  19331. return results;
  19332. };
  19333. /**
  19334. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  19335. */
  19336. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  19337. var results = new Array();
  19338. var descendants = this.getDescendants();
  19339. descendants.push(this);
  19340. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19341. var particleSystem = this.getScene().particleSystems[index];
  19342. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  19343. results.push(particleSystem);
  19344. }
  19345. }
  19346. return results;
  19347. };
  19348. Mesh.prototype._checkDelayState = function () {
  19349. var scene = this.getScene();
  19350. if (this._geometry) {
  19351. this._geometry.load(scene);
  19352. }
  19353. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19354. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19355. this._queueLoad(this, scene);
  19356. }
  19357. };
  19358. Mesh.prototype._queueLoad = function (mesh, scene) {
  19359. var _this = this;
  19360. scene._addPendingData(mesh);
  19361. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  19362. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19363. if (data instanceof ArrayBuffer) {
  19364. _this._delayLoadingFunction(data, _this);
  19365. }
  19366. else {
  19367. _this._delayLoadingFunction(JSON.parse(data), _this);
  19368. }
  19369. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19370. scene._removePendingData(_this);
  19371. }, function () { }, scene.database, getBinaryData);
  19372. };
  19373. /**
  19374. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  19375. */
  19376. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  19377. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19378. return false;
  19379. }
  19380. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  19381. return false;
  19382. }
  19383. this._checkDelayState();
  19384. return true;
  19385. };
  19386. /**
  19387. * Sets the mesh material by the material or multiMaterial `id` property.
  19388. * The material `id` is a string identifying the material or the multiMaterial.
  19389. * This method returns nothing.
  19390. */
  19391. Mesh.prototype.setMaterialByID = function (id) {
  19392. var materials = this.getScene().materials;
  19393. var index;
  19394. for (index = 0; index < materials.length; index++) {
  19395. if (materials[index].id === id) {
  19396. this.material = materials[index];
  19397. return;
  19398. }
  19399. }
  19400. // Multi
  19401. var multiMaterials = this.getScene().multiMaterials;
  19402. for (index = 0; index < multiMaterials.length; index++) {
  19403. if (multiMaterials[index].id === id) {
  19404. this.material = multiMaterials[index];
  19405. return;
  19406. }
  19407. }
  19408. };
  19409. /**
  19410. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  19411. */
  19412. Mesh.prototype.getAnimatables = function () {
  19413. var results = [];
  19414. if (this.material) {
  19415. results.push(this.material);
  19416. }
  19417. if (this.skeleton) {
  19418. results.push(this.skeleton);
  19419. }
  19420. return results;
  19421. };
  19422. /**
  19423. * Modifies the mesh geometry according to the passed transformation matrix.
  19424. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  19425. * The mesh normals are modified accordingly the same transformation.
  19426. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19427. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19428. */
  19429. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  19430. // Position
  19431. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19432. return;
  19433. }
  19434. var submeshes = this.subMeshes.splice(0);
  19435. this._resetPointsArrayCache();
  19436. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19437. var temp = [];
  19438. var index;
  19439. for (index = 0; index < data.length; index += 3) {
  19440. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  19441. }
  19442. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  19443. // Normals
  19444. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19445. return;
  19446. }
  19447. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19448. temp = [];
  19449. for (index = 0; index < data.length; index += 3) {
  19450. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  19451. }
  19452. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  19453. // flip faces?
  19454. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  19455. this.flipFaces();
  19456. }
  19457. // Restore submeshes
  19458. this.releaseSubMeshes();
  19459. this.subMeshes = submeshes;
  19460. };
  19461. /**
  19462. * Modifies the mesh geometry according to its own current World Matrix.
  19463. * The mesh World Matrix is then reset.
  19464. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  19465. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19466. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19467. */
  19468. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  19469. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  19470. this.scaling.copyFromFloats(1, 1, 1);
  19471. this.position.copyFromFloats(0, 0, 0);
  19472. this.rotation.copyFromFloats(0, 0, 0);
  19473. //only if quaternion is already set
  19474. if (this.rotationQuaternion) {
  19475. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  19476. }
  19477. this._worldMatrix = BABYLON.Matrix.Identity();
  19478. };
  19479. // Cache
  19480. Mesh.prototype._resetPointsArrayCache = function () {
  19481. this._positions = null;
  19482. };
  19483. Mesh.prototype._generatePointsArray = function () {
  19484. if (this._positions)
  19485. return true;
  19486. this._positions = [];
  19487. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19488. if (!data) {
  19489. return false;
  19490. }
  19491. for (var index = 0; index < data.length; index += 3) {
  19492. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  19493. }
  19494. return true;
  19495. };
  19496. /**
  19497. * Returns a new Mesh object generated from the current mesh properties.
  19498. * This method must not get confused with createInstance().
  19499. * The parameter `name` is a string, the name given to the new mesh.
  19500. * The optional parameter `newParent` can be any Node object (default `null`).
  19501. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  19502. * 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.
  19503. */
  19504. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  19505. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19506. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  19507. };
  19508. /**
  19509. * Disposes the mesh.
  19510. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  19511. */
  19512. Mesh.prototype.dispose = function (doNotRecurse) {
  19513. if (this._geometry) {
  19514. this._geometry.releaseForMesh(this, true);
  19515. }
  19516. // Instances
  19517. if (this._instancesBuffer) {
  19518. this._instancesBuffer.dispose();
  19519. this._instancesBuffer = null;
  19520. }
  19521. while (this.instances.length) {
  19522. this.instances[0].dispose();
  19523. }
  19524. _super.prototype.dispose.call(this, doNotRecurse);
  19525. };
  19526. /**
  19527. * Modifies the mesh geometry according to a displacement map.
  19528. * 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.
  19529. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19530. * This method returns nothing.
  19531. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  19532. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19533. * 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.
  19534. */
  19535. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  19536. var _this = this;
  19537. var scene = this.getScene();
  19538. var onload = function (img) {
  19539. // Getting height map data
  19540. var canvas = document.createElement("canvas");
  19541. var context = canvas.getContext("2d");
  19542. var heightMapWidth = img.width;
  19543. var heightMapHeight = img.height;
  19544. canvas.width = heightMapWidth;
  19545. canvas.height = heightMapHeight;
  19546. context.drawImage(img, 0, 0);
  19547. // Create VertexData from map data
  19548. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19549. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  19550. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  19551. //execute success callback, if set
  19552. if (onSuccess) {
  19553. onSuccess(_this);
  19554. }
  19555. };
  19556. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19557. };
  19558. /**
  19559. * Modifies the mesh geometry according to a displacementMap buffer.
  19560. * 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.
  19561. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19562. * This method returns nothing.
  19563. * 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.
  19564. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  19565. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19566. */
  19567. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  19568. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  19569. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  19570. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19571. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  19572. return;
  19573. }
  19574. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19575. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19576. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19577. var position = BABYLON.Vector3.Zero();
  19578. var normal = BABYLON.Vector3.Zero();
  19579. var uv = BABYLON.Vector2.Zero();
  19580. for (var index = 0; index < positions.length; index += 3) {
  19581. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  19582. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  19583. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  19584. // Compute height
  19585. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  19586. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  19587. var pos = (u + v * heightMapWidth) * 4;
  19588. var r = buffer[pos] / 255.0;
  19589. var g = buffer[pos + 1] / 255.0;
  19590. var b = buffer[pos + 2] / 255.0;
  19591. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  19592. normal.normalize();
  19593. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  19594. position = position.add(normal);
  19595. position.toArray(positions, index);
  19596. }
  19597. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  19598. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  19599. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19600. };
  19601. /**
  19602. * Modify the mesh to get a flat shading rendering.
  19603. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  19604. * This method returns nothing.
  19605. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  19606. */
  19607. Mesh.prototype.convertToFlatShadedMesh = function () {
  19608. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  19609. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19610. var kinds = this.getVerticesDataKinds();
  19611. var vbs = [];
  19612. var data = [];
  19613. var newdata = [];
  19614. var updatableNormals = false;
  19615. var kindIndex;
  19616. var kind;
  19617. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19618. kind = kinds[kindIndex];
  19619. var vertexBuffer = this.getVertexBuffer(kind);
  19620. if (kind === BABYLON.VertexBuffer.NormalKind) {
  19621. updatableNormals = vertexBuffer.isUpdatable();
  19622. kinds.splice(kindIndex, 1);
  19623. kindIndex--;
  19624. continue;
  19625. }
  19626. vbs[kind] = vertexBuffer;
  19627. data[kind] = vbs[kind].getData();
  19628. newdata[kind] = [];
  19629. }
  19630. // Save previous submeshes
  19631. var previousSubmeshes = this.subMeshes.slice(0);
  19632. var indices = this.getIndices();
  19633. var totalIndices = this.getTotalIndices();
  19634. // Generating unique vertices per face
  19635. var index;
  19636. for (index = 0; index < totalIndices; index++) {
  19637. var vertexIndex = indices[index];
  19638. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19639. kind = kinds[kindIndex];
  19640. var stride = vbs[kind].getStrideSize();
  19641. for (var offset = 0; offset < stride; offset++) {
  19642. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19643. }
  19644. }
  19645. }
  19646. // Updating faces & normal
  19647. var normals = [];
  19648. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  19649. for (index = 0; index < totalIndices; index += 3) {
  19650. indices[index] = index;
  19651. indices[index + 1] = index + 1;
  19652. indices[index + 2] = index + 2;
  19653. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  19654. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  19655. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  19656. var p1p2 = p1.subtract(p2);
  19657. var p3p2 = p3.subtract(p2);
  19658. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  19659. // Store same normals for every vertex
  19660. for (var localIndex = 0; localIndex < 3; localIndex++) {
  19661. normals.push(normal.x);
  19662. normals.push(normal.y);
  19663. normals.push(normal.z);
  19664. }
  19665. }
  19666. this.setIndices(indices);
  19667. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  19668. // Updating vertex buffers
  19669. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19670. kind = kinds[kindIndex];
  19671. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19672. }
  19673. // Updating submeshes
  19674. this.releaseSubMeshes();
  19675. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19676. var previousOne = previousSubmeshes[submeshIndex];
  19677. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19678. }
  19679. this.synchronizeInstances();
  19680. };
  19681. /**
  19682. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  19683. * In other words, more vertices, no more indices and a single bigger VBO.
  19684. * This method returns nothing.
  19685. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  19686. *
  19687. */
  19688. Mesh.prototype.convertToUnIndexedMesh = function () {
  19689. /// <summary>Remove indices by unfolding faces into buffers</summary>
  19690. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19691. var kinds = this.getVerticesDataKinds();
  19692. var vbs = [];
  19693. var data = [];
  19694. var newdata = [];
  19695. var updatableNormals = false;
  19696. var kindIndex;
  19697. var kind;
  19698. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19699. kind = kinds[kindIndex];
  19700. var vertexBuffer = this.getVertexBuffer(kind);
  19701. vbs[kind] = vertexBuffer;
  19702. data[kind] = vbs[kind].getData();
  19703. newdata[kind] = [];
  19704. }
  19705. // Save previous submeshes
  19706. var previousSubmeshes = this.subMeshes.slice(0);
  19707. var indices = this.getIndices();
  19708. var totalIndices = this.getTotalIndices();
  19709. // Generating unique vertices per face
  19710. var index;
  19711. for (index = 0; index < totalIndices; index++) {
  19712. var vertexIndex = indices[index];
  19713. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19714. kind = kinds[kindIndex];
  19715. var stride = vbs[kind].getStrideSize();
  19716. for (var offset = 0; offset < stride; offset++) {
  19717. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19718. }
  19719. }
  19720. }
  19721. // Updating indices
  19722. for (index = 0; index < totalIndices; index += 3) {
  19723. indices[index] = index;
  19724. indices[index + 1] = index + 1;
  19725. indices[index + 2] = index + 2;
  19726. }
  19727. this.setIndices(indices);
  19728. // Updating vertex buffers
  19729. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19730. kind = kinds[kindIndex];
  19731. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19732. }
  19733. // Updating submeshes
  19734. this.releaseSubMeshes();
  19735. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19736. var previousOne = previousSubmeshes[submeshIndex];
  19737. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19738. }
  19739. this._unIndexed = true;
  19740. this.synchronizeInstances();
  19741. };
  19742. /**
  19743. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  19744. * This method returns nothing.
  19745. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  19746. */
  19747. Mesh.prototype.flipFaces = function (flipNormals) {
  19748. if (flipNormals === void 0) { flipNormals = false; }
  19749. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  19750. var i;
  19751. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19752. for (i = 0; i < vertex_data.normals.length; i++) {
  19753. vertex_data.normals[i] *= -1;
  19754. }
  19755. }
  19756. var temp;
  19757. for (i = 0; i < vertex_data.indices.length; i += 3) {
  19758. // reassign indices
  19759. temp = vertex_data.indices[i + 1];
  19760. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  19761. vertex_data.indices[i + 2] = temp;
  19762. }
  19763. vertex_data.applyToMesh(this);
  19764. };
  19765. // Instances
  19766. /**
  19767. * Creates a new InstancedMesh object from the mesh model.
  19768. * An instance shares the same properties and the same material than its model.
  19769. * Only these properties of each instance can then be set individually :
  19770. * - position
  19771. * - rotation
  19772. * - rotationQuaternion
  19773. * - setPivotMatrix
  19774. * - scaling
  19775. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  19776. * Warning : this method is not supported for Line mesh and LineSystem
  19777. */
  19778. Mesh.prototype.createInstance = function (name) {
  19779. return new BABYLON.InstancedMesh(name, this);
  19780. };
  19781. /**
  19782. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  19783. * After this call, all the mesh instances have the same submeshes than the current mesh.
  19784. * This method returns nothing.
  19785. */
  19786. Mesh.prototype.synchronizeInstances = function () {
  19787. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  19788. var instance = this.instances[instanceIndex];
  19789. instance._syncSubMeshes();
  19790. }
  19791. };
  19792. /**
  19793. * Simplify the mesh according to the given array of settings.
  19794. * Function will return immediately and will simplify async. It returns nothing.
  19795. * @param settings a collection of simplification settings.
  19796. * @param parallelProcessing should all levels calculate parallel or one after the other.
  19797. * @param type the type of simplification to run.
  19798. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  19799. */
  19800. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  19801. if (parallelProcessing === void 0) { parallelProcessing = true; }
  19802. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  19803. this.getScene().simplificationQueue.addTask({
  19804. settings: settings,
  19805. parallelProcessing: parallelProcessing,
  19806. mesh: this,
  19807. simplificationType: simplificationType,
  19808. successCallback: successCallback
  19809. });
  19810. };
  19811. /**
  19812. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  19813. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  19814. * This should be used together with the simplification to avoid disappearing triangles.
  19815. * @param successCallback an optional success callback to be called after the optimization finished.
  19816. */
  19817. Mesh.prototype.optimizeIndices = function (successCallback) {
  19818. var _this = this;
  19819. var indices = this.getIndices();
  19820. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19821. var vectorPositions = [];
  19822. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  19823. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  19824. }
  19825. var dupes = [];
  19826. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  19827. var realPos = vectorPositions.length - 1 - iteration;
  19828. var testedPosition = vectorPositions[realPos];
  19829. for (var j = 0; j < realPos; ++j) {
  19830. var againstPosition = vectorPositions[j];
  19831. if (testedPosition.equals(againstPosition)) {
  19832. dupes[realPos] = j;
  19833. break;
  19834. }
  19835. }
  19836. }, function () {
  19837. for (var i = 0; i < indices.length; ++i) {
  19838. indices[i] = dupes[indices[i]] || indices[i];
  19839. }
  19840. //indices are now reordered
  19841. var originalSubMeshes = _this.subMeshes.slice(0);
  19842. _this.setIndices(indices);
  19843. _this.subMeshes = originalSubMeshes;
  19844. if (successCallback) {
  19845. successCallback(_this);
  19846. }
  19847. });
  19848. };
  19849. // Statics
  19850. /**
  19851. * Returns a new Mesh object what is a deep copy of the passed mesh.
  19852. * The parameter `parsedMesh` is the mesh to be copied.
  19853. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19854. */
  19855. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  19856. var mesh = new Mesh(parsedMesh.name, scene);
  19857. mesh.id = parsedMesh.id;
  19858. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19859. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19860. if (parsedMesh.rotationQuaternion) {
  19861. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19862. }
  19863. else if (parsedMesh.rotation) {
  19864. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19865. }
  19866. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19867. if (parsedMesh.localMatrix) {
  19868. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19869. }
  19870. else if (parsedMesh.pivotMatrix) {
  19871. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19872. }
  19873. mesh.setEnabled(parsedMesh.isEnabled);
  19874. mesh.isVisible = parsedMesh.isVisible;
  19875. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19876. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19877. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19878. if (parsedMesh.applyFog !== undefined) {
  19879. mesh.applyFog = parsedMesh.applyFog;
  19880. }
  19881. if (parsedMesh.pickable !== undefined) {
  19882. mesh.isPickable = parsedMesh.pickable;
  19883. }
  19884. if (parsedMesh.alphaIndex !== undefined) {
  19885. mesh.alphaIndex = parsedMesh.alphaIndex;
  19886. }
  19887. mesh.receiveShadows = parsedMesh.receiveShadows;
  19888. mesh.billboardMode = parsedMesh.billboardMode;
  19889. if (parsedMesh.visibility !== undefined) {
  19890. mesh.visibility = parsedMesh.visibility;
  19891. }
  19892. mesh.checkCollisions = parsedMesh.checkCollisions;
  19893. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19894. // freezeWorldMatrix
  19895. if (parsedMesh.freezeWorldMatrix) {
  19896. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  19897. }
  19898. // Parent
  19899. if (parsedMesh.parentId) {
  19900. mesh._waitingParentId = parsedMesh.parentId;
  19901. }
  19902. // Actions
  19903. if (parsedMesh.actions !== undefined) {
  19904. mesh._waitingActions = parsedMesh.actions;
  19905. }
  19906. // Geometry
  19907. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19908. if (parsedMesh.delayLoadingFile) {
  19909. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19910. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19911. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19912. if (parsedMesh._binaryInfo) {
  19913. mesh._binaryInfo = parsedMesh._binaryInfo;
  19914. }
  19915. mesh._delayInfo = [];
  19916. if (parsedMesh.hasUVs) {
  19917. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19918. }
  19919. if (parsedMesh.hasUVs2) {
  19920. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19921. }
  19922. if (parsedMesh.hasUVs3) {
  19923. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19924. }
  19925. if (parsedMesh.hasUVs4) {
  19926. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19927. }
  19928. if (parsedMesh.hasUVs5) {
  19929. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19930. }
  19931. if (parsedMesh.hasUVs6) {
  19932. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19933. }
  19934. if (parsedMesh.hasColors) {
  19935. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19936. }
  19937. if (parsedMesh.hasMatricesIndices) {
  19938. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19939. }
  19940. if (parsedMesh.hasMatricesWeights) {
  19941. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19942. }
  19943. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  19944. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19945. mesh._checkDelayState();
  19946. }
  19947. }
  19948. else {
  19949. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  19950. }
  19951. // Material
  19952. if (parsedMesh.materialId) {
  19953. mesh.setMaterialByID(parsedMesh.materialId);
  19954. }
  19955. else {
  19956. mesh.material = null;
  19957. }
  19958. // Skeleton
  19959. if (parsedMesh.skeletonId > -1) {
  19960. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19961. if (parsedMesh.numBoneInfluencers) {
  19962. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  19963. }
  19964. }
  19965. // Animations
  19966. if (parsedMesh.animations) {
  19967. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19968. var parsedAnimation = parsedMesh.animations[animationIndex];
  19969. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19970. }
  19971. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  19972. }
  19973. if (parsedMesh.autoAnimate) {
  19974. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  19975. }
  19976. // Layer Mask
  19977. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19978. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19979. }
  19980. else {
  19981. mesh.layerMask = 0x0FFFFFFF;
  19982. }
  19983. //(Deprecated) physics
  19984. if (parsedMesh.physicsImpostor) {
  19985. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  19986. mass: parsedMesh.physicsMass,
  19987. friction: parsedMesh.physicsFriction,
  19988. restitution: parsedMesh.physicsRestitution
  19989. }, scene);
  19990. }
  19991. // Instances
  19992. if (parsedMesh.instances) {
  19993. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19994. var parsedInstance = parsedMesh.instances[index];
  19995. var instance = mesh.createInstance(parsedInstance.name);
  19996. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19997. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19998. if (parsedInstance.rotationQuaternion) {
  19999. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20000. }
  20001. else if (parsedInstance.rotation) {
  20002. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20003. }
  20004. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20005. instance.checkCollisions = mesh.checkCollisions;
  20006. if (parsedMesh.animations) {
  20007. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20008. parsedAnimation = parsedMesh.animations[animationIndex];
  20009. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20010. }
  20011. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  20012. }
  20013. }
  20014. }
  20015. return mesh;
  20016. };
  20017. /**
  20018. * Creates a ribbon mesh.
  20019. * Please consider using the same method from the MeshBuilder class instead.
  20020. * 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.
  20021. *
  20022. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20023. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20024. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20025. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20026. * 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.
  20027. * 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.
  20028. * 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
  20029. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20030. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20031. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20032. */
  20033. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  20034. return BABYLON.MeshBuilder.CreateRibbon(name, {
  20035. pathArray: pathArray,
  20036. closeArray: closeArray,
  20037. closePath: closePath,
  20038. offset: offset,
  20039. updatable: updatable,
  20040. sideOrientation: sideOrientation,
  20041. instance: instance
  20042. }, scene);
  20043. };
  20044. /**
  20045. * Creates a plane polygonal mesh. By default, this is a disc.
  20046. * Please consider using the same method from the MeshBuilder class instead.
  20047. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20048. * 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.
  20049. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20050. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20051. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20052. */
  20053. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  20054. var options = {
  20055. radius: radius,
  20056. tessellation: tessellation,
  20057. sideOrientation: sideOrientation,
  20058. updatable: updatable
  20059. };
  20060. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  20061. };
  20062. /**
  20063. * Creates a box mesh.
  20064. * Please consider using the same method from the MeshBuilder class instead.
  20065. * The parameter `size` sets the size (float) of each box side (default 1).
  20066. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20067. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20068. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20069. */
  20070. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  20071. var options = {
  20072. size: size,
  20073. sideOrientation: sideOrientation,
  20074. updatable: updatable
  20075. };
  20076. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  20077. };
  20078. /**
  20079. * Creates a sphere mesh.
  20080. * Please consider using the same method from the MeshBuilder class instead.
  20081. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20082. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20083. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20084. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20085. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20086. */
  20087. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  20088. var options = {
  20089. segments: segments,
  20090. diameterX: diameter,
  20091. diameterY: diameter,
  20092. diameterZ: diameter,
  20093. sideOrientation: sideOrientation,
  20094. updatable: updatable
  20095. };
  20096. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  20097. };
  20098. /**
  20099. * Creates a cylinder or a cone mesh.
  20100. * Please consider using the same method from the MeshBuilder class instead.
  20101. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20102. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20103. * 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.
  20104. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20105. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20106. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20107. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20108. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20109. */
  20110. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  20111. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  20112. if (scene !== undefined) {
  20113. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  20114. updatable = scene;
  20115. }
  20116. scene = subdivisions;
  20117. subdivisions = 1;
  20118. }
  20119. var options = {
  20120. height: height,
  20121. diameterTop: diameterTop,
  20122. diameterBottom: diameterBottom,
  20123. tessellation: tessellation,
  20124. subdivisions: subdivisions,
  20125. sideOrientation: sideOrientation,
  20126. updatable: updatable
  20127. };
  20128. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  20129. };
  20130. // Torus (Code from SharpDX.org)
  20131. /**
  20132. * Creates a torus mesh.
  20133. * Please consider using the same method from the MeshBuilder class instead.
  20134. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20135. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20136. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20137. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20138. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20139. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20140. */
  20141. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  20142. var options = {
  20143. diameter: diameter,
  20144. thickness: thickness,
  20145. tessellation: tessellation,
  20146. sideOrientation: sideOrientation,
  20147. updatable: updatable
  20148. };
  20149. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  20150. };
  20151. /**
  20152. * Creates a torus knot mesh.
  20153. * Please consider using the same method from the MeshBuilder class instead.
  20154. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20155. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20156. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20157. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20158. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20159. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20160. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20161. */
  20162. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  20163. var options = {
  20164. radius: radius,
  20165. tube: tube,
  20166. radialSegments: radialSegments,
  20167. tubularSegments: tubularSegments,
  20168. p: p,
  20169. q: q,
  20170. sideOrientation: sideOrientation,
  20171. updatable: updatable
  20172. };
  20173. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  20174. };
  20175. /**
  20176. * Creates a line mesh.
  20177. * Please consider using the same method from the MeshBuilder class instead.
  20178. * 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.
  20179. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20180. * The parameter `points` is an array successive Vector3.
  20181. * 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
  20182. * When updating an instance, remember that only point positions can change, not the number of points.
  20183. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20184. */
  20185. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  20186. var options = {
  20187. points: points,
  20188. updatable: updatable,
  20189. instance: instance
  20190. };
  20191. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  20192. };
  20193. /**
  20194. * Creates a dashed line mesh.
  20195. * Please consider using the same method from the MeshBuilder class instead.
  20196. * 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.
  20197. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20198. * The parameter `points` is an array successive Vector3.
  20199. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20200. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20201. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20202. * 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
  20203. * When updating an instance, remember that only point positions can change, not the number of points.
  20204. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20205. */
  20206. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  20207. var options = {
  20208. points: points,
  20209. dashSize: dashSize,
  20210. gapSize: gapSize,
  20211. dashNb: dashNb,
  20212. updatable: updatable,
  20213. instance: instance
  20214. };
  20215. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  20216. };
  20217. /**
  20218. * Creates an extruded shape mesh.
  20219. * 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.
  20220. * Please consider using the same method from the MeshBuilder class instead.
  20221. *
  20222. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20223. * 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
  20224. * extruded along the Z axis.
  20225. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20226. * 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.
  20227. * The parameter `scale` (float, default 1) is the value to scale the shape.
  20228. * 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
  20229. * 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
  20230. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20231. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20232. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20233. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20234. */
  20235. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  20236. var options = {
  20237. shape: shape,
  20238. path: path,
  20239. scale: scale,
  20240. rotation: rotation,
  20241. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20242. sideOrientation: sideOrientation,
  20243. instance: instance,
  20244. updatable: updatable
  20245. };
  20246. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  20247. };
  20248. /**
  20249. * Creates an custom extruded shape mesh.
  20250. * 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.
  20251. * Please consider using the same method from the MeshBuilder class instead.
  20252. *
  20253. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20254. * 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
  20255. * extruded along the Z axis.
  20256. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20257. * 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
  20258. * and the distance of this point from the begining of the path :
  20259. * ```javascript
  20260. * var rotationFunction = function(i, distance) {
  20261. * // do things
  20262. * return rotationValue; }
  20263. * ```
  20264. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20265. * 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
  20266. * and the distance of this point from the begining of the path :
  20267. * ```javascript
  20268. * var scaleFunction = function(i, distance) {
  20269. * // do things
  20270. * return scaleValue;}
  20271. * ```
  20272. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20273. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20274. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20275. * 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
  20276. * 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
  20277. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20278. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20279. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20280. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20281. */
  20282. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  20283. var options = {
  20284. shape: shape,
  20285. path: path,
  20286. scaleFunction: scaleFunction,
  20287. rotationFunction: rotationFunction,
  20288. ribbonCloseArray: ribbonCloseArray,
  20289. ribbonClosePath: ribbonClosePath,
  20290. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20291. sideOrientation: sideOrientation,
  20292. instance: instance,
  20293. updatable: updatable
  20294. };
  20295. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  20296. };
  20297. /**
  20298. * Creates lathe mesh.
  20299. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20300. * Please consider using the same method from the MeshBuilder class instead.
  20301. * 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
  20302. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20303. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20304. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20305. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20306. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20307. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20308. */
  20309. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  20310. var options = {
  20311. shape: shape,
  20312. radius: radius,
  20313. tessellation: tessellation,
  20314. sideOrientation: sideOrientation,
  20315. updatable: updatable
  20316. };
  20317. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  20318. };
  20319. /**
  20320. * Creates a plane mesh.
  20321. * Please consider using the same method from the MeshBuilder class instead.
  20322. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20323. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20324. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20325. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20326. */
  20327. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  20328. var options = {
  20329. size: size,
  20330. width: size,
  20331. height: size,
  20332. sideOrientation: sideOrientation,
  20333. updatable: updatable
  20334. };
  20335. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  20336. };
  20337. /**
  20338. * Creates a ground mesh.
  20339. * Please consider using the same method from the MeshBuilder class instead.
  20340. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20341. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20342. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20343. */
  20344. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  20345. var options = {
  20346. width: width,
  20347. height: height,
  20348. subdivisions: subdivisions,
  20349. updatable: updatable
  20350. };
  20351. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  20352. };
  20353. /**
  20354. * Creates a tiled ground mesh.
  20355. * Please consider using the same method from the MeshBuilder class instead.
  20356. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20357. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20358. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20359. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20360. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20361. * numbers of subdivisions on the ground width and height of each tile.
  20362. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20363. */
  20364. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  20365. var options = {
  20366. xmin: xmin,
  20367. zmin: zmin,
  20368. xmax: xmax,
  20369. zmax: zmax,
  20370. subdivisions: subdivisions,
  20371. precision: precision,
  20372. updatable: updatable
  20373. };
  20374. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  20375. };
  20376. /**
  20377. * Creates a ground mesh from a height map.
  20378. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  20379. * Please consider using the same method from the MeshBuilder class instead.
  20380. * The parameter `url` sets the URL of the height map image resource.
  20381. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  20382. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  20383. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  20384. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  20385. * 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).
  20386. * This function is passed the newly built mesh :
  20387. * ```javascript
  20388. * function(mesh) { // do things
  20389. * return; }
  20390. * ```
  20391. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20392. */
  20393. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  20394. var options = {
  20395. width: width,
  20396. height: height,
  20397. subdivisions: subdivisions,
  20398. minHeight: minHeight,
  20399. maxHeight: maxHeight,
  20400. updatable: updatable,
  20401. onReady: onReady
  20402. };
  20403. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  20404. };
  20405. /**
  20406. * Creates a tube mesh.
  20407. * 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.
  20408. * Please consider using the same method from the MeshBuilder class instead.
  20409. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  20410. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  20411. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  20412. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  20413. * 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.
  20414. * It must return a radius value (positive float) :
  20415. * ```javascript
  20416. * var radiusFunction = function(i, distance) {
  20417. * // do things
  20418. * return radius; }
  20419. * ```
  20420. * 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
  20421. * 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
  20422. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20423. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20424. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20425. */
  20426. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  20427. var options = {
  20428. path: path,
  20429. radius: radius,
  20430. tessellation: tessellation,
  20431. radiusFunction: radiusFunction,
  20432. arc: 1,
  20433. cap: cap,
  20434. updatable: updatable,
  20435. sideOrientation: sideOrientation,
  20436. instance: instance
  20437. };
  20438. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  20439. };
  20440. /**
  20441. * Creates a polyhedron mesh.
  20442. * Please consider using the same method from the MeshBuilder class instead.
  20443. * 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
  20444. * to choose the wanted type.
  20445. * The parameter `size` (positive float, default 1) sets the polygon size.
  20446. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  20447. * 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`.
  20448. * 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
  20449. * 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)`).
  20450. * 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
  20451. * 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.
  20452. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20453. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20454. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20455. */
  20456. Mesh.CreatePolyhedron = function (name, options, scene) {
  20457. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  20458. };
  20459. /**
  20460. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  20461. * Please consider using the same method from the MeshBuilder class instead.
  20462. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  20463. * 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`).
  20464. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  20465. * 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.
  20466. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20467. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20468. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20469. */
  20470. Mesh.CreateIcoSphere = function (name, options, scene) {
  20471. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  20472. };
  20473. /**
  20474. * Creates a decal mesh.
  20475. * Please consider using the same method from the MeshBuilder class instead.
  20476. * 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.
  20477. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  20478. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  20479. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  20480. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  20481. */
  20482. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  20483. var options = {
  20484. position: position,
  20485. normal: normal,
  20486. size: size,
  20487. angle: angle
  20488. };
  20489. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  20490. };
  20491. // Skeletons
  20492. /**
  20493. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20494. */
  20495. Mesh.prototype.setPositionsForCPUSkinning = function () {
  20496. var source;
  20497. if (!this._sourcePositions) {
  20498. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20499. this._sourcePositions = new Float32Array(source);
  20500. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  20501. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  20502. }
  20503. }
  20504. return this._sourcePositions;
  20505. };
  20506. /**
  20507. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20508. */
  20509. Mesh.prototype.setNormalsForCPUSkinning = function () {
  20510. var source;
  20511. if (!this._sourceNormals) {
  20512. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20513. this._sourceNormals = new Float32Array(source);
  20514. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  20515. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  20516. }
  20517. }
  20518. return this._sourceNormals;
  20519. };
  20520. /**
  20521. * Update the vertex buffers by applying transformation from the bones
  20522. * @param {skeleton} skeleton to apply
  20523. */
  20524. Mesh.prototype.applySkeleton = function (skeleton) {
  20525. if (!this.geometry) {
  20526. return;
  20527. }
  20528. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  20529. return;
  20530. }
  20531. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  20532. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20533. return this;
  20534. }
  20535. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20536. return this;
  20537. }
  20538. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20539. return this;
  20540. }
  20541. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20542. return this;
  20543. }
  20544. if (!this._sourcePositions) {
  20545. this.setPositionsForCPUSkinning();
  20546. }
  20547. if (!this._sourceNormals) {
  20548. this.setNormalsForCPUSkinning();
  20549. }
  20550. // positionsData checks for not being Float32Array will only pass at most once
  20551. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20552. if (!(positionsData instanceof Float32Array)) {
  20553. positionsData = new Float32Array(positionsData);
  20554. }
  20555. // normalsData checks for not being Float32Array will only pass at most once
  20556. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20557. if (!(normalsData instanceof Float32Array)) {
  20558. normalsData = new Float32Array(normalsData);
  20559. }
  20560. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20561. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20562. var needExtras = this.numBoneInfluencers > 4;
  20563. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  20564. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  20565. var skeletonMatrices = skeleton.getTransformMatrices(this);
  20566. var tempVector3 = BABYLON.Vector3.Zero();
  20567. var finalMatrix = new BABYLON.Matrix();
  20568. var tempMatrix = new BABYLON.Matrix();
  20569. var matWeightIdx = 0;
  20570. var inf;
  20571. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  20572. var weight;
  20573. for (inf = 0; inf < 4; inf++) {
  20574. weight = matricesWeightsData[matWeightIdx + inf];
  20575. if (weight > 0) {
  20576. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20577. finalMatrix.addToSelf(tempMatrix);
  20578. }
  20579. else
  20580. break;
  20581. }
  20582. if (needExtras) {
  20583. for (inf = 0; inf < 4; inf++) {
  20584. weight = matricesWeightsExtraData[matWeightIdx + inf];
  20585. if (weight > 0) {
  20586. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20587. finalMatrix.addToSelf(tempMatrix);
  20588. }
  20589. else
  20590. break;
  20591. }
  20592. }
  20593. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  20594. tempVector3.toArray(positionsData, index);
  20595. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  20596. tempVector3.toArray(normalsData, index);
  20597. finalMatrix.reset();
  20598. }
  20599. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  20600. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  20601. return this;
  20602. };
  20603. // Tools
  20604. /**
  20605. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  20606. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  20607. */
  20608. Mesh.MinMax = function (meshes) {
  20609. var minVector = null;
  20610. var maxVector = null;
  20611. for (var i in meshes) {
  20612. var mesh = meshes[i];
  20613. var boundingBox = mesh.getBoundingInfo().boundingBox;
  20614. if (!minVector) {
  20615. minVector = boundingBox.minimumWorld;
  20616. maxVector = boundingBox.maximumWorld;
  20617. continue;
  20618. }
  20619. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  20620. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  20621. }
  20622. return {
  20623. min: minVector,
  20624. max: maxVector
  20625. };
  20626. };
  20627. /**
  20628. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  20629. */
  20630. Mesh.Center = function (meshesOrMinMaxVector) {
  20631. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  20632. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  20633. };
  20634. /**
  20635. * Merge the array of meshes into a single mesh for performance reasons.
  20636. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  20637. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  20638. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  20639. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  20640. */
  20641. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  20642. if (disposeSource === void 0) { disposeSource = true; }
  20643. var index;
  20644. if (!allow32BitsIndices) {
  20645. var totalVertices = 0;
  20646. // Counting vertices
  20647. for (index = 0; index < meshes.length; index++) {
  20648. if (meshes[index]) {
  20649. totalVertices += meshes[index].getTotalVertices();
  20650. if (totalVertices > 65536) {
  20651. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  20652. return null;
  20653. }
  20654. }
  20655. }
  20656. }
  20657. // Merge
  20658. var vertexData;
  20659. var otherVertexData;
  20660. var source;
  20661. for (index = 0; index < meshes.length; index++) {
  20662. if (meshes[index]) {
  20663. meshes[index].computeWorldMatrix(true);
  20664. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  20665. otherVertexData.transform(meshes[index].getWorldMatrix());
  20666. if (vertexData) {
  20667. vertexData.merge(otherVertexData);
  20668. }
  20669. else {
  20670. vertexData = otherVertexData;
  20671. source = meshes[index];
  20672. }
  20673. }
  20674. }
  20675. if (!meshSubclass) {
  20676. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  20677. }
  20678. vertexData.applyToMesh(meshSubclass);
  20679. // Setting properties
  20680. meshSubclass.material = source.material;
  20681. meshSubclass.checkCollisions = source.checkCollisions;
  20682. // Cleaning
  20683. if (disposeSource) {
  20684. for (index = 0; index < meshes.length; index++) {
  20685. if (meshes[index]) {
  20686. meshes[index].dispose();
  20687. }
  20688. }
  20689. }
  20690. return meshSubclass;
  20691. };
  20692. // Consts
  20693. Mesh._FRONTSIDE = 0;
  20694. Mesh._BACKSIDE = 1;
  20695. Mesh._DOUBLESIDE = 2;
  20696. Mesh._DEFAULTSIDE = 0;
  20697. Mesh._NO_CAP = 0;
  20698. Mesh._CAP_START = 1;
  20699. Mesh._CAP_END = 2;
  20700. Mesh._CAP_ALL = 3;
  20701. return Mesh;
  20702. })(BABYLON.AbstractMesh);
  20703. BABYLON.Mesh = Mesh;
  20704. })(BABYLON || (BABYLON = {}));
  20705. var BABYLON;
  20706. (function (BABYLON) {
  20707. var SubMesh = (function () {
  20708. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  20709. if (createBoundingBox === void 0) { createBoundingBox = true; }
  20710. this.materialIndex = materialIndex;
  20711. this.verticesStart = verticesStart;
  20712. this.verticesCount = verticesCount;
  20713. this.indexStart = indexStart;
  20714. this.indexCount = indexCount;
  20715. this._renderId = 0;
  20716. this._mesh = mesh;
  20717. this._renderingMesh = renderingMesh || mesh;
  20718. mesh.subMeshes.push(this);
  20719. this._trianglePlanes = [];
  20720. this._id = mesh.subMeshes.length - 1;
  20721. if (createBoundingBox) {
  20722. this.refreshBoundingInfo();
  20723. mesh.computeWorldMatrix(true);
  20724. }
  20725. }
  20726. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  20727. get: function () {
  20728. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  20729. },
  20730. enumerable: true,
  20731. configurable: true
  20732. });
  20733. SubMesh.prototype.getBoundingInfo = function () {
  20734. if (this.IsGlobal) {
  20735. return this._mesh.getBoundingInfo();
  20736. }
  20737. return this._boundingInfo;
  20738. };
  20739. SubMesh.prototype.getMesh = function () {
  20740. return this._mesh;
  20741. };
  20742. SubMesh.prototype.getRenderingMesh = function () {
  20743. return this._renderingMesh;
  20744. };
  20745. SubMesh.prototype.getMaterial = function () {
  20746. var rootMaterial = this._renderingMesh.material;
  20747. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  20748. var multiMaterial = rootMaterial;
  20749. return multiMaterial.getSubMaterial(this.materialIndex);
  20750. }
  20751. if (!rootMaterial) {
  20752. return this._mesh.getScene().defaultMaterial;
  20753. }
  20754. return rootMaterial;
  20755. };
  20756. // Methods
  20757. SubMesh.prototype.refreshBoundingInfo = function () {
  20758. this._lastColliderWorldVertices = null;
  20759. if (this.IsGlobal) {
  20760. return;
  20761. }
  20762. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20763. if (!data) {
  20764. this._boundingInfo = this._mesh._boundingInfo;
  20765. return;
  20766. }
  20767. var indices = this._renderingMesh.getIndices();
  20768. var extend;
  20769. //is this the only submesh?
  20770. if (this.indexStart === 0 && this.indexCount === indices.length) {
  20771. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  20772. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  20773. }
  20774. else {
  20775. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  20776. }
  20777. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20778. };
  20779. SubMesh.prototype._checkCollision = function (collider) {
  20780. return this.getBoundingInfo()._checkCollision(collider);
  20781. };
  20782. SubMesh.prototype.updateBoundingInfo = function (world) {
  20783. if (!this.getBoundingInfo()) {
  20784. this.refreshBoundingInfo();
  20785. }
  20786. this.getBoundingInfo().update(world);
  20787. };
  20788. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  20789. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  20790. };
  20791. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20792. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  20793. };
  20794. SubMesh.prototype.render = function (enableAlphaMode) {
  20795. this._renderingMesh.render(this, enableAlphaMode);
  20796. };
  20797. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  20798. if (!this._linesIndexBuffer) {
  20799. var linesIndices = [];
  20800. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  20801. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  20802. }
  20803. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  20804. this.linesIndexCount = linesIndices.length;
  20805. }
  20806. return this._linesIndexBuffer;
  20807. };
  20808. SubMesh.prototype.canIntersects = function (ray) {
  20809. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  20810. };
  20811. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  20812. var intersectInfo = null;
  20813. // LineMesh first as it's also a Mesh...
  20814. if (this._mesh instanceof BABYLON.LinesMesh) {
  20815. var lineMesh = this._mesh;
  20816. // Line test
  20817. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  20818. var p0 = positions[indices[index]];
  20819. var p1 = positions[indices[index + 1]];
  20820. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  20821. if (length < 0) {
  20822. continue;
  20823. }
  20824. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  20825. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  20826. if (fastCheck) {
  20827. break;
  20828. }
  20829. }
  20830. }
  20831. }
  20832. else {
  20833. // Triangles test
  20834. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  20835. var p0 = positions[indices[index]];
  20836. var p1 = positions[indices[index + 1]];
  20837. var p2 = positions[indices[index + 2]];
  20838. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  20839. if (currentIntersectInfo) {
  20840. if (currentIntersectInfo.distance < 0) {
  20841. continue;
  20842. }
  20843. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20844. intersectInfo = currentIntersectInfo;
  20845. intersectInfo.faceId = index / 3;
  20846. if (fastCheck) {
  20847. break;
  20848. }
  20849. }
  20850. }
  20851. }
  20852. }
  20853. return intersectInfo;
  20854. };
  20855. // Clone
  20856. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  20857. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  20858. if (!this.IsGlobal) {
  20859. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  20860. }
  20861. return result;
  20862. };
  20863. // Dispose
  20864. SubMesh.prototype.dispose = function () {
  20865. if (this._linesIndexBuffer) {
  20866. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  20867. this._linesIndexBuffer = null;
  20868. }
  20869. // Remove from mesh
  20870. var index = this._mesh.subMeshes.indexOf(this);
  20871. this._mesh.subMeshes.splice(index, 1);
  20872. };
  20873. // Statics
  20874. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  20875. var minVertexIndex = Number.MAX_VALUE;
  20876. var maxVertexIndex = -Number.MAX_VALUE;
  20877. renderingMesh = renderingMesh || mesh;
  20878. var indices = renderingMesh.getIndices();
  20879. for (var index = startIndex; index < startIndex + indexCount; index++) {
  20880. var vertexIndex = indices[index];
  20881. if (vertexIndex < minVertexIndex)
  20882. minVertexIndex = vertexIndex;
  20883. if (vertexIndex > maxVertexIndex)
  20884. maxVertexIndex = vertexIndex;
  20885. }
  20886. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  20887. };
  20888. return SubMesh;
  20889. })();
  20890. BABYLON.SubMesh = SubMesh;
  20891. })(BABYLON || (BABYLON = {}));
  20892. var BABYLON;
  20893. (function (BABYLON) {
  20894. var MeshBuilder = (function () {
  20895. function MeshBuilder() {
  20896. }
  20897. /**
  20898. * Creates a box mesh.
  20899. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  20900. * The parameter `size` sets the size (float) of each box side (default 1).
  20901. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  20902. * 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).
  20903. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  20904. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20905. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20906. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20907. */
  20908. MeshBuilder.CreateBox = function (name, options, scene) {
  20909. var box = new BABYLON.Mesh(name, scene);
  20910. var vertexData = BABYLON.VertexData.CreateBox(options);
  20911. vertexData.applyToMesh(box, options.updatable);
  20912. return box;
  20913. };
  20914. /**
  20915. * Creates a sphere mesh.
  20916. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  20917. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20918. * 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`).
  20919. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20920. * 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
  20921. * 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).
  20922. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20923. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20924. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20925. */
  20926. MeshBuilder.CreateSphere = function (name, options, scene) {
  20927. var sphere = new BABYLON.Mesh(name, scene);
  20928. var vertexData = BABYLON.VertexData.CreateSphere(options);
  20929. vertexData.applyToMesh(sphere, options.updatable);
  20930. return sphere;
  20931. };
  20932. /**
  20933. * Creates a plane polygonal mesh. By default, this is a disc.
  20934. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  20935. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20936. * 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.
  20937. * 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
  20938. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20939. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20940. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20941. */
  20942. MeshBuilder.CreateDisc = function (name, options, scene) {
  20943. var disc = new BABYLON.Mesh(name, scene);
  20944. var vertexData = BABYLON.VertexData.CreateDisc(options);
  20945. vertexData.applyToMesh(disc, options.updatable);
  20946. return disc;
  20947. };
  20948. /**
  20949. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  20950. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  20951. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  20952. * 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`).
  20953. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  20954. * 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.
  20955. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20956. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20957. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20958. */
  20959. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  20960. var sphere = new BABYLON.Mesh(name, scene);
  20961. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  20962. vertexData.applyToMesh(sphere, options.updatable);
  20963. return sphere;
  20964. };
  20965. ;
  20966. /**
  20967. * Creates a ribbon mesh.
  20968. * 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.
  20969. *
  20970. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20971. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20972. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20973. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20974. * 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.
  20975. * 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.
  20976. * 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
  20977. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20978. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20979. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20980. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20981. */
  20982. MeshBuilder.CreateRibbon = function (name, options, scene) {
  20983. var pathArray = options.pathArray;
  20984. var closeArray = options.closeArray;
  20985. var closePath = options.closePath;
  20986. var offset = options.offset;
  20987. var sideOrientation = options.sideOrientation;
  20988. var instance = options.instance;
  20989. var updatable = options.updatable;
  20990. if (instance) {
  20991. // positionFunction : ribbon case
  20992. // only pathArray and sideOrientation parameters are taken into account for positions update
  20993. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  20994. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  20995. var positionFunction = function (positions) {
  20996. var minlg = pathArray[0].length;
  20997. var i = 0;
  20998. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  20999. for (var si = 1; si <= ns; si++) {
  21000. for (var p = 0; p < pathArray.length; p++) {
  21001. var path = pathArray[p];
  21002. var l = path.length;
  21003. minlg = (minlg < l) ? minlg : l;
  21004. var j = 0;
  21005. while (j < minlg) {
  21006. positions[i] = path[j].x;
  21007. positions[i + 1] = path[j].y;
  21008. positions[i + 2] = path[j].z;
  21009. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  21010. BABYLON.Tmp.Vector3[0].x = path[j].x;
  21011. }
  21012. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  21013. BABYLON.Tmp.Vector3[1].x = path[j].x;
  21014. }
  21015. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  21016. BABYLON.Tmp.Vector3[0].y = path[j].y;
  21017. }
  21018. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  21019. BABYLON.Tmp.Vector3[1].y = path[j].y;
  21020. }
  21021. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  21022. BABYLON.Tmp.Vector3[0].z = path[j].z;
  21023. }
  21024. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  21025. BABYLON.Tmp.Vector3[1].z = path[j].z;
  21026. }
  21027. j++;
  21028. i += 3;
  21029. }
  21030. if (instance._closePath) {
  21031. positions[i] = path[0].x;
  21032. positions[i + 1] = path[0].y;
  21033. positions[i + 2] = path[0].z;
  21034. i += 3;
  21035. }
  21036. }
  21037. }
  21038. };
  21039. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21040. positionFunction(positions);
  21041. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  21042. instance._boundingInfo.update(instance._worldMatrix);
  21043. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21044. if (!(instance.areNormalsFrozen)) {
  21045. var indices = instance.getIndices();
  21046. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21047. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21048. if (instance._closePath) {
  21049. var indexFirst = 0;
  21050. var indexLast = 0;
  21051. for (var p = 0; p < pathArray.length; p++) {
  21052. indexFirst = instance._idx[p] * 3;
  21053. if (p + 1 < pathArray.length) {
  21054. indexLast = (instance._idx[p + 1] - 1) * 3;
  21055. }
  21056. else {
  21057. indexLast = normals.length - 3;
  21058. }
  21059. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  21060. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  21061. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  21062. normals[indexLast] = normals[indexFirst];
  21063. normals[indexLast + 1] = normals[indexFirst + 1];
  21064. normals[indexLast + 2] = normals[indexFirst + 2];
  21065. }
  21066. }
  21067. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21068. }
  21069. return instance;
  21070. }
  21071. else {
  21072. var ribbon = new BABYLON.Mesh(name, scene);
  21073. ribbon.sideOrientation = sideOrientation;
  21074. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  21075. if (closePath) {
  21076. ribbon._idx = vertexData._idx;
  21077. }
  21078. ribbon._closePath = closePath;
  21079. ribbon._closeArray = closeArray;
  21080. vertexData.applyToMesh(ribbon, updatable);
  21081. return ribbon;
  21082. }
  21083. };
  21084. /**
  21085. * Creates a cylinder or a cone mesh.
  21086. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  21087. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21088. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21089. * 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.
  21090. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21091. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21092. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  21093. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  21094. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  21095. * 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).
  21096. * 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
  21097. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  21098. * 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
  21099. * 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.
  21100. * If `enclose` is false, a ring surface is one element.
  21101. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  21102. * 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
  21103. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21104. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21105. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21106. */
  21107. MeshBuilder.CreateCylinder = function (name, options, scene) {
  21108. var cylinder = new BABYLON.Mesh(name, scene);
  21109. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  21110. vertexData.applyToMesh(cylinder, options.updatable);
  21111. return cylinder;
  21112. };
  21113. /**
  21114. * Creates a torus mesh.
  21115. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  21116. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21117. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21118. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21119. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21120. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21121. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21122. */
  21123. MeshBuilder.CreateTorus = function (name, options, scene) {
  21124. var torus = new BABYLON.Mesh(name, scene);
  21125. var vertexData = BABYLON.VertexData.CreateTorus(options);
  21126. vertexData.applyToMesh(torus, options.updatable);
  21127. return torus;
  21128. };
  21129. /**
  21130. * Creates a torus knot mesh.
  21131. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  21132. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21133. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21134. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21135. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21136. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21137. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21138. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21139. */
  21140. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  21141. var torusKnot = new BABYLON.Mesh(name, scene);
  21142. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  21143. vertexData.applyToMesh(torusKnot, options.updatable);
  21144. return torusKnot;
  21145. };
  21146. /**
  21147. * Creates a line system mesh.
  21148. * A line system is a pool of many lines gathered in a single mesh.
  21149. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  21150. * 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.
  21151. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  21152. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  21153. * 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
  21154. * 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
  21155. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  21156. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21157. */
  21158. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  21159. var instance = options.instance;
  21160. var lines = options.lines;
  21161. if (instance) {
  21162. var positionFunction = function (positions) {
  21163. var i = 0;
  21164. for (var l = 0; l < lines.length; l++) {
  21165. var points = lines[l];
  21166. for (var p = 0; p < points.length; p++) {
  21167. positions[i] = points[p].x;
  21168. positions[i + 1] = points[p].y;
  21169. positions[i + 2] = points[p].z;
  21170. i += 3;
  21171. }
  21172. }
  21173. };
  21174. instance.updateMeshPositions(positionFunction, false);
  21175. return instance;
  21176. }
  21177. // line system creation
  21178. var lineSystem = new BABYLON.LinesMesh(name, scene);
  21179. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  21180. vertexData.applyToMesh(lineSystem, options.updatable);
  21181. return lineSystem;
  21182. };
  21183. /**
  21184. * Creates a line mesh.
  21185. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  21186. * 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.
  21187. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21188. * The parameter `points` is an array successive Vector3.
  21189. * 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
  21190. * When updating an instance, remember that only point positions can change, not the number of points.
  21191. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21192. */
  21193. MeshBuilder.CreateLines = function (name, options, scene) {
  21194. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  21195. return lines;
  21196. };
  21197. /**
  21198. * Creates a dashed line mesh.
  21199. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  21200. * 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.
  21201. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21202. * The parameter `points` is an array successive Vector3.
  21203. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21204. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21205. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21206. * 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
  21207. * When updating an instance, remember that only point positions can change, not the number of points.
  21208. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21209. */
  21210. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  21211. var points = options.points;
  21212. var instance = options.instance;
  21213. var gapSize = options.gapSize;
  21214. var dashNb = options.dashNb;
  21215. var dashSize = options.dashSize;
  21216. if (instance) {
  21217. var positionFunction = function (positions) {
  21218. var curvect = BABYLON.Vector3.Zero();
  21219. var nbSeg = positions.length / 6;
  21220. var lg = 0;
  21221. var nb = 0;
  21222. var shft = 0;
  21223. var dashshft = 0;
  21224. var curshft = 0;
  21225. var p = 0;
  21226. var i = 0;
  21227. var j = 0;
  21228. for (i = 0; i < points.length - 1; i++) {
  21229. points[i + 1].subtractToRef(points[i], curvect);
  21230. lg += curvect.length();
  21231. }
  21232. shft = lg / nbSeg;
  21233. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  21234. for (i = 0; i < points.length - 1; i++) {
  21235. points[i + 1].subtractToRef(points[i], curvect);
  21236. nb = Math.floor(curvect.length() / shft);
  21237. curvect.normalize();
  21238. j = 0;
  21239. while (j < nb && p < positions.length) {
  21240. curshft = shft * j;
  21241. positions[p] = points[i].x + curshft * curvect.x;
  21242. positions[p + 1] = points[i].y + curshft * curvect.y;
  21243. positions[p + 2] = points[i].z + curshft * curvect.z;
  21244. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  21245. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  21246. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  21247. p += 6;
  21248. j++;
  21249. }
  21250. }
  21251. while (p < positions.length) {
  21252. positions[p] = points[i].x;
  21253. positions[p + 1] = points[i].y;
  21254. positions[p + 2] = points[i].z;
  21255. p += 3;
  21256. }
  21257. };
  21258. instance.updateMeshPositions(positionFunction, false);
  21259. return instance;
  21260. }
  21261. // dashed lines creation
  21262. var dashedLines = new BABYLON.LinesMesh(name, scene);
  21263. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  21264. vertexData.applyToMesh(dashedLines, options.updatable);
  21265. dashedLines.dashSize = dashSize;
  21266. dashedLines.gapSize = gapSize;
  21267. return dashedLines;
  21268. };
  21269. /**
  21270. * Creates an extruded shape mesh.
  21271. * 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.
  21272. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  21273. *
  21274. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21275. * 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
  21276. * extruded along the Z axis.
  21277. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21278. * 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.
  21279. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21280. * 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
  21281. * 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
  21282. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21283. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21284. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21285. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21286. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21287. */
  21288. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  21289. var path = options.path;
  21290. var shape = options.shape;
  21291. var scale = options.scale || 1;
  21292. var rotation = options.rotation || 0;
  21293. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  21294. var updatable = options.updatable;
  21295. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21296. var instance = options.instance;
  21297. var invertUV = options.invertUV || false;
  21298. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  21299. };
  21300. /**
  21301. * Creates an custom extruded shape mesh.
  21302. * 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.
  21303. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  21304. *
  21305. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21306. * 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
  21307. * extruded along the Z axis.
  21308. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21309. * 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
  21310. * and the distance of this point from the begining of the path :
  21311. * ```javascript
  21312. * var rotationFunction = function(i, distance) {
  21313. * // do things
  21314. * return rotationValue; }
  21315. * ```
  21316. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21317. * 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
  21318. * and the distance of this point from the begining of the path :
  21319. * ```javascript
  21320. * var scaleFunction = function(i, distance) {
  21321. * // do things
  21322. * return scaleValue;}
  21323. * ```
  21324. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21325. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21326. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21327. * 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
  21328. * 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
  21329. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21330. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21331. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21332. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21333. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21334. */
  21335. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  21336. var path = options.path;
  21337. var shape = options.shape;
  21338. var scaleFunction = options.scaleFunction || (function () { return 1; });
  21339. var rotationFunction = options.rotationFunction || (function () { return 0; });
  21340. var ribbonCloseArray = options.ribbonCloseArray || false;
  21341. var ribbonClosePath = options.ribbonClosePath || false;
  21342. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  21343. var updatable = options.updatable;
  21344. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21345. var instance = options.instance;
  21346. var invertUV = options.invertUV || false;
  21347. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  21348. };
  21349. /**
  21350. * Creates lathe mesh.
  21351. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21352. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  21353. *
  21354. * 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
  21355. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21356. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21357. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21358. * 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.
  21359. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  21360. * 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
  21361. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21362. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21363. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21364. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21365. */
  21366. MeshBuilder.CreateLathe = function (name, options, scene) {
  21367. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  21368. var closed = (options.closed === undefined) ? true : options.closed;
  21369. var shape = options.shape;
  21370. var radius = options.radius || 1;
  21371. var tessellation = options.tessellation || 64;
  21372. var updatable = options.updatable;
  21373. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21374. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  21375. var pi2 = Math.PI * 2;
  21376. var paths = new Array();
  21377. var invertUV = options.invertUV || false;
  21378. var i = 0;
  21379. var p = 0;
  21380. var step = pi2 / tessellation * arc;
  21381. var rotated;
  21382. var path = new Array();
  21383. ;
  21384. for (i = 0; i <= tessellation; i++) {
  21385. var path = [];
  21386. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  21387. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  21388. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  21389. }
  21390. for (p = 0; p < shape.length; p++) {
  21391. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  21392. path.push(rotated);
  21393. }
  21394. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  21395. 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));
  21396. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  21397. }
  21398. paths.push(path);
  21399. }
  21400. // lathe ribbon
  21401. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  21402. return lathe;
  21403. };
  21404. /**
  21405. * Creates a plane mesh.
  21406. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  21407. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21408. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  21409. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  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 mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21413. */
  21414. MeshBuilder.CreatePlane = function (name, options, scene) {
  21415. var plane = new BABYLON.Mesh(name, scene);
  21416. var vertexData = BABYLON.VertexData.CreatePlane(options);
  21417. vertexData.applyToMesh(plane, options.updatable);
  21418. if (options.sourcePlane) {
  21419. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  21420. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  21421. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  21422. plane.rotate(vectorProduct, product);
  21423. }
  21424. return plane;
  21425. };
  21426. /**
  21427. * Creates a ground mesh.
  21428. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  21429. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21430. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21431. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21432. */
  21433. MeshBuilder.CreateGround = function (name, options, scene) {
  21434. var ground = new BABYLON.GroundMesh(name, scene);
  21435. ground._setReady(false);
  21436. ground._subdivisions = options.subdivisions || 1;
  21437. ground._width = options.width || 1;
  21438. ground._height = options.height || 1;
  21439. ground._maxX = ground._width / 2;
  21440. ground._maxZ = ground._height / 2;
  21441. ground._minX = -ground._maxX;
  21442. ground._minZ = -ground._maxZ;
  21443. var vertexData = BABYLON.VertexData.CreateGround(options);
  21444. vertexData.applyToMesh(ground, options.updatable);
  21445. ground._setReady(true);
  21446. return ground;
  21447. };
  21448. /**
  21449. * Creates a tiled ground mesh.
  21450. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  21451. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21452. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21453. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21454. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21455. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21456. * numbers of subdivisions on the ground width and height of each tile.
  21457. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21458. */
  21459. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  21460. var tiledGround = new BABYLON.Mesh(name, scene);
  21461. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  21462. vertexData.applyToMesh(tiledGround, options.updatable);
  21463. return tiledGround;
  21464. };
  21465. /**
  21466. * Creates a ground mesh from a height map.
  21467. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21468. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  21469. * The parameter `url` sets the URL of the height map image resource.
  21470. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21471. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21472. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21473. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21474. * 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).
  21475. * This function is passed the newly built mesh :
  21476. * ```javascript
  21477. * function(mesh) { // do things
  21478. * return; }
  21479. * ```
  21480. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21481. */
  21482. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  21483. var width = options.width || 10.0;
  21484. var height = options.height || 10.0;
  21485. var subdivisions = options.subdivisions || 1 | 0;
  21486. var minHeight = options.minHeight || 0.0;
  21487. var maxHeight = options.maxHeight || 10.0;
  21488. var updatable = options.updatable;
  21489. var onReady = options.onReady;
  21490. var ground = new BABYLON.GroundMesh(name, scene);
  21491. ground._subdivisions = subdivisions;
  21492. ground._width = width;
  21493. ground._height = height;
  21494. ground._maxX = ground._width / 2.0;
  21495. ground._maxZ = ground._height / 2.0;
  21496. ground._minX = -ground._maxX;
  21497. ground._minZ = -ground._maxZ;
  21498. ground._setReady(false);
  21499. var onload = function (img) {
  21500. // Getting height map data
  21501. var canvas = document.createElement("canvas");
  21502. var context = canvas.getContext("2d");
  21503. var bufferWidth = img.width;
  21504. var bufferHeight = img.height;
  21505. canvas.width = bufferWidth;
  21506. canvas.height = bufferHeight;
  21507. context.drawImage(img, 0, 0);
  21508. // Create VertexData from map data
  21509. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  21510. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  21511. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  21512. width: width, height: height,
  21513. subdivisions: subdivisions,
  21514. minHeight: minHeight, maxHeight: maxHeight,
  21515. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  21516. });
  21517. vertexData.applyToMesh(ground, updatable);
  21518. ground._setReady(true);
  21519. //execute ready callback, if set
  21520. if (onReady) {
  21521. onReady(ground);
  21522. }
  21523. };
  21524. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  21525. return ground;
  21526. };
  21527. /**
  21528. * Creates a tube mesh.
  21529. * 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.
  21530. *
  21531. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  21532. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21533. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21534. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21535. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21536. * 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.
  21537. * It must return a radius value (positive float) :
  21538. * ```javascript
  21539. * var radiusFunction = function(i, distance) {
  21540. * // do things
  21541. * return radius; }
  21542. * ```
  21543. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  21544. * 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
  21545. * 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
  21546. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21547. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21548. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21549. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21550. */
  21551. MeshBuilder.CreateTube = function (name, options, scene) {
  21552. var path = options.path;
  21553. var radius = options.radius || 1.0;
  21554. var tessellation = options.tessellation || 64 | 0;
  21555. var radiusFunction = options.radiusFunction;
  21556. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  21557. var invertUV = options.invertUV || false;
  21558. var updatable = options.updatable;
  21559. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21560. var instance = options.instance;
  21561. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  21562. // tube geometry
  21563. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  21564. var tangents = path3D.getTangents();
  21565. var normals = path3D.getNormals();
  21566. var distances = path3D.getDistances();
  21567. var pi2 = Math.PI * 2;
  21568. var step = pi2 / tessellation * arc;
  21569. var returnRadius = function () { return radius; };
  21570. var radiusFunctionFinal = radiusFunction || returnRadius;
  21571. var circlePath;
  21572. var rad;
  21573. var normal;
  21574. var rotated;
  21575. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  21576. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  21577. for (var i = 0; i < path.length; i++) {
  21578. rad = radiusFunctionFinal(i, distances[i]); // current radius
  21579. circlePath = Array(); // current circle array
  21580. normal = normals[i]; // current normal
  21581. for (var t = 0; t < tessellation; t++) {
  21582. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  21583. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  21584. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  21585. rotated.scaleInPlace(rad).addInPlace(path[i]);
  21586. circlePath[t] = rotated;
  21587. }
  21588. circlePaths[index] = circlePath;
  21589. index++;
  21590. }
  21591. // cap
  21592. var capPath = function (nbPoints, pathIndex) {
  21593. var pointCap = Array();
  21594. for (var i = 0; i < nbPoints; i++) {
  21595. pointCap.push(path[pathIndex]);
  21596. }
  21597. return pointCap;
  21598. };
  21599. switch (cap) {
  21600. case BABYLON.Mesh.NO_CAP:
  21601. break;
  21602. case BABYLON.Mesh.CAP_START:
  21603. circlePaths[0] = capPath(tessellation, 0);
  21604. circlePaths[1] = circlePaths[2].slice(0);
  21605. break;
  21606. case BABYLON.Mesh.CAP_END:
  21607. circlePaths[index] = circlePaths[index - 1].slice(0);
  21608. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  21609. break;
  21610. case BABYLON.Mesh.CAP_ALL:
  21611. circlePaths[0] = capPath(tessellation, 0);
  21612. circlePaths[1] = circlePaths[2].slice(0);
  21613. circlePaths[index] = circlePaths[index - 1].slice(0);
  21614. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  21615. break;
  21616. default:
  21617. break;
  21618. }
  21619. return circlePaths;
  21620. };
  21621. var path3D;
  21622. var pathArray;
  21623. if (instance) {
  21624. var arc = options.arc || instance.arc;
  21625. path3D = (instance.path3D).update(path);
  21626. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  21627. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  21628. instance.path3D = path3D;
  21629. instance.pathArray = pathArray;
  21630. instance.arc = arc;
  21631. return instance;
  21632. }
  21633. // tube creation
  21634. path3D = new BABYLON.Path3D(path);
  21635. var newPathArray = new Array();
  21636. cap = (cap < 0 || cap > 3) ? 0 : cap;
  21637. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  21638. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  21639. tube.pathArray = pathArray;
  21640. tube.path3D = path3D;
  21641. tube.tessellation = tessellation;
  21642. tube.cap = cap;
  21643. tube.arc = options.arc;
  21644. return tube;
  21645. };
  21646. /**
  21647. * Creates a polyhedron mesh.
  21648. *
  21649. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  21650. * 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
  21651. * to choose the wanted type.
  21652. * The parameter `size` (positive float, default 1) sets the polygon size.
  21653. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21654. * 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`.
  21655. * 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
  21656. * 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)`).
  21657. * 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
  21658. * 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.
  21659. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21660. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21661. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21662. */
  21663. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  21664. var polyhedron = new BABYLON.Mesh(name, scene);
  21665. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  21666. vertexData.applyToMesh(polyhedron, options.updatable);
  21667. return polyhedron;
  21668. };
  21669. /**
  21670. * Creates a decal mesh.
  21671. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  21672. * 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.
  21673. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21674. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21675. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21676. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21677. */
  21678. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  21679. var indices = sourceMesh.getIndices();
  21680. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21681. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21682. var position = options.position || BABYLON.Vector3.Zero();
  21683. var normal = options.normal || BABYLON.Vector3.Up();
  21684. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  21685. var angle = options.angle || 0;
  21686. // Getting correct rotation
  21687. if (!normal) {
  21688. var target = new BABYLON.Vector3(0, 0, 1);
  21689. var camera = sourceMesh.getScene().activeCamera;
  21690. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  21691. normal = camera.globalPosition.subtract(cameraWorldTarget);
  21692. }
  21693. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  21694. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  21695. var pitch = Math.atan2(normal.y, len);
  21696. // Matrix
  21697. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  21698. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  21699. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  21700. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  21701. var vertexData = new BABYLON.VertexData();
  21702. vertexData.indices = [];
  21703. vertexData.positions = [];
  21704. vertexData.normals = [];
  21705. vertexData.uvs = [];
  21706. var currentVertexDataIndex = 0;
  21707. var extractDecalVector3 = function (indexId) {
  21708. var vertexId = indices[indexId];
  21709. var result = new BABYLON.PositionNormalVertex();
  21710. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  21711. // Send vector to decal local world
  21712. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  21713. // Get normal
  21714. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  21715. return result;
  21716. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  21717. var clip = function (vertices, axis) {
  21718. if (vertices.length === 0) {
  21719. return vertices;
  21720. }
  21721. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  21722. var clipVertices = function (v0, v1) {
  21723. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  21724. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  21725. };
  21726. var result = new Array();
  21727. for (var index = 0; index < vertices.length; index += 3) {
  21728. var v1Out;
  21729. var v2Out;
  21730. var v3Out;
  21731. var total = 0;
  21732. var nV1, nV2, nV3, nV4;
  21733. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  21734. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  21735. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  21736. v1Out = d1 > 0;
  21737. v2Out = d2 > 0;
  21738. v3Out = d3 > 0;
  21739. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  21740. switch (total) {
  21741. case 0:
  21742. result.push(vertices[index]);
  21743. result.push(vertices[index + 1]);
  21744. result.push(vertices[index + 2]);
  21745. break;
  21746. case 1:
  21747. if (v1Out) {
  21748. nV1 = vertices[index + 1];
  21749. nV2 = vertices[index + 2];
  21750. nV3 = clipVertices(vertices[index], nV1);
  21751. nV4 = clipVertices(vertices[index], nV2);
  21752. }
  21753. if (v2Out) {
  21754. nV1 = vertices[index];
  21755. nV2 = vertices[index + 2];
  21756. nV3 = clipVertices(vertices[index + 1], nV1);
  21757. nV4 = clipVertices(vertices[index + 1], nV2);
  21758. result.push(nV3);
  21759. result.push(nV2.clone());
  21760. result.push(nV1.clone());
  21761. result.push(nV2.clone());
  21762. result.push(nV3.clone());
  21763. result.push(nV4);
  21764. break;
  21765. }
  21766. if (v3Out) {
  21767. nV1 = vertices[index];
  21768. nV2 = vertices[index + 1];
  21769. nV3 = clipVertices(vertices[index + 2], nV1);
  21770. nV4 = clipVertices(vertices[index + 2], nV2);
  21771. }
  21772. result.push(nV1.clone());
  21773. result.push(nV2.clone());
  21774. result.push(nV3);
  21775. result.push(nV4);
  21776. result.push(nV3.clone());
  21777. result.push(nV2.clone());
  21778. break;
  21779. case 2:
  21780. if (!v1Out) {
  21781. nV1 = vertices[index].clone();
  21782. nV2 = clipVertices(nV1, vertices[index + 1]);
  21783. nV3 = clipVertices(nV1, vertices[index + 2]);
  21784. result.push(nV1);
  21785. result.push(nV2);
  21786. result.push(nV3);
  21787. }
  21788. if (!v2Out) {
  21789. nV1 = vertices[index + 1].clone();
  21790. nV2 = clipVertices(nV1, vertices[index + 2]);
  21791. nV3 = clipVertices(nV1, vertices[index]);
  21792. result.push(nV1);
  21793. result.push(nV2);
  21794. result.push(nV3);
  21795. }
  21796. if (!v3Out) {
  21797. nV1 = vertices[index + 2].clone();
  21798. nV2 = clipVertices(nV1, vertices[index]);
  21799. nV3 = clipVertices(nV1, vertices[index + 1]);
  21800. result.push(nV1);
  21801. result.push(nV2);
  21802. result.push(nV3);
  21803. }
  21804. break;
  21805. case 3:
  21806. break;
  21807. }
  21808. }
  21809. return result;
  21810. };
  21811. for (var index = 0; index < indices.length; index += 3) {
  21812. var faceVertices = new Array();
  21813. faceVertices.push(extractDecalVector3(index));
  21814. faceVertices.push(extractDecalVector3(index + 1));
  21815. faceVertices.push(extractDecalVector3(index + 2));
  21816. // Clip
  21817. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  21818. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  21819. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  21820. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  21821. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  21822. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  21823. if (faceVertices.length === 0) {
  21824. continue;
  21825. }
  21826. // Add UVs and get back to world
  21827. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  21828. var vertex = faceVertices[vIndex];
  21829. //TODO check for Int32Array
  21830. vertexData.indices.push(currentVertexDataIndex);
  21831. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  21832. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  21833. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  21834. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  21835. currentVertexDataIndex++;
  21836. }
  21837. }
  21838. // Return mesh
  21839. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  21840. vertexData.applyToMesh(decal);
  21841. decal.position = position.clone();
  21842. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  21843. return decal;
  21844. };
  21845. // Privates
  21846. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  21847. // extrusion geometry
  21848. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  21849. var tangents = path3D.getTangents();
  21850. var normals = path3D.getNormals();
  21851. var binormals = path3D.getBinormals();
  21852. var distances = path3D.getDistances();
  21853. var angle = 0;
  21854. var returnScale = function () { return scale; };
  21855. var returnRotation = function () { return rotation; };
  21856. var rotate = custom ? rotateFunction : returnRotation;
  21857. var scl = custom ? scaleFunction : returnScale;
  21858. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  21859. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  21860. for (var i = 0; i < curve.length; i++) {
  21861. var shapePath = new Array();
  21862. var angleStep = rotate(i, distances[i]);
  21863. var scaleRatio = scl(i, distances[i]);
  21864. for (var p = 0; p < shape.length; p++) {
  21865. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  21866. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  21867. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  21868. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  21869. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  21870. shapePath[p] = rotated;
  21871. }
  21872. shapePaths[index] = shapePath;
  21873. angle += angleStep;
  21874. index++;
  21875. }
  21876. // cap
  21877. var capPath = function (shapePath) {
  21878. var pointCap = Array();
  21879. var barycenter = BABYLON.Vector3.Zero();
  21880. var i;
  21881. for (i = 0; i < shapePath.length; i++) {
  21882. barycenter.addInPlace(shapePath[i]);
  21883. }
  21884. barycenter.scaleInPlace(1 / shapePath.length);
  21885. for (i = 0; i < shapePath.length; i++) {
  21886. pointCap.push(barycenter);
  21887. }
  21888. return pointCap;
  21889. };
  21890. switch (cap) {
  21891. case BABYLON.Mesh.NO_CAP:
  21892. break;
  21893. case BABYLON.Mesh.CAP_START:
  21894. shapePaths[0] = capPath(shapePaths[2]);
  21895. shapePaths[1] = shapePaths[2].slice(0);
  21896. break;
  21897. case BABYLON.Mesh.CAP_END:
  21898. shapePaths[index] = shapePaths[index - 1];
  21899. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  21900. break;
  21901. case BABYLON.Mesh.CAP_ALL:
  21902. shapePaths[0] = capPath(shapePaths[2]);
  21903. shapePaths[1] = shapePaths[2].slice(0);
  21904. shapePaths[index] = shapePaths[index - 1];
  21905. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  21906. break;
  21907. default:
  21908. break;
  21909. }
  21910. return shapePaths;
  21911. };
  21912. var path3D;
  21913. var pathArray;
  21914. if (instance) {
  21915. path3D = (instance.path3D).update(curve);
  21916. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  21917. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  21918. return instance;
  21919. }
  21920. // extruded shape creation
  21921. path3D = new BABYLON.Path3D(curve);
  21922. var newShapePaths = new Array();
  21923. cap = (cap < 0 || cap > 3) ? 0 : cap;
  21924. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  21925. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  21926. extrudedGeneric.pathArray = pathArray;
  21927. extrudedGeneric.path3D = path3D;
  21928. extrudedGeneric.cap = cap;
  21929. return extrudedGeneric;
  21930. };
  21931. return MeshBuilder;
  21932. })();
  21933. BABYLON.MeshBuilder = MeshBuilder;
  21934. })(BABYLON || (BABYLON = {}));
  21935. var BABYLON;
  21936. (function (BABYLON) {
  21937. var BaseTexture = (function () {
  21938. function BaseTexture(scene) {
  21939. this.hasAlpha = false;
  21940. this.getAlphaFromRGB = false;
  21941. this.level = 1;
  21942. this.coordinatesIndex = 0;
  21943. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  21944. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21945. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21946. this.anisotropicFilteringLevel = 4;
  21947. this.isCube = false;
  21948. this.isRenderTarget = false;
  21949. this.animations = new Array();
  21950. /**
  21951. * An event triggered when the texture is disposed.
  21952. * @type {BABYLON.Observable}
  21953. */
  21954. this.onDisposeObservable = new BABYLON.Observable();
  21955. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21956. this._scene = scene;
  21957. this._scene.textures.push(this);
  21958. }
  21959. BaseTexture.prototype.toString = function () {
  21960. return this.name;
  21961. };
  21962. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  21963. set: function (callback) {
  21964. if (this._onDisposeObserver) {
  21965. this.onDisposeObservable.remove(this._onDisposeObserver);
  21966. }
  21967. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21968. },
  21969. enumerable: true,
  21970. configurable: true
  21971. });
  21972. BaseTexture.prototype.getScene = function () {
  21973. return this._scene;
  21974. };
  21975. BaseTexture.prototype.getTextureMatrix = function () {
  21976. return null;
  21977. };
  21978. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  21979. return null;
  21980. };
  21981. BaseTexture.prototype.getInternalTexture = function () {
  21982. return this._texture;
  21983. };
  21984. BaseTexture.prototype.isReady = function () {
  21985. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21986. return true;
  21987. }
  21988. if (this._texture) {
  21989. return this._texture.isReady;
  21990. }
  21991. return false;
  21992. };
  21993. BaseTexture.prototype.getSize = function () {
  21994. if (this._texture._width) {
  21995. return new BABYLON.Size(this._texture._width, this._texture._height);
  21996. }
  21997. if (this._texture._size) {
  21998. return new BABYLON.Size(this._texture._size, this._texture._size);
  21999. }
  22000. return BABYLON.Size.Zero();
  22001. };
  22002. BaseTexture.prototype.getBaseSize = function () {
  22003. if (!this.isReady() || !this._texture)
  22004. return BABYLON.Size.Zero();
  22005. if (this._texture._size) {
  22006. return new BABYLON.Size(this._texture._size, this._texture._size);
  22007. }
  22008. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  22009. };
  22010. BaseTexture.prototype.scale = function (ratio) {
  22011. };
  22012. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22013. get: function () {
  22014. return false;
  22015. },
  22016. enumerable: true,
  22017. configurable: true
  22018. });
  22019. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  22020. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22021. for (var index = 0; index < texturesCache.length; index++) {
  22022. var texturesCacheEntry = texturesCache[index];
  22023. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22024. texturesCache.splice(index, 1);
  22025. return;
  22026. }
  22027. }
  22028. };
  22029. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22030. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22031. for (var index = 0; index < texturesCache.length; index++) {
  22032. var texturesCacheEntry = texturesCache[index];
  22033. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22034. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22035. texturesCacheEntry.references++;
  22036. return texturesCacheEntry;
  22037. }
  22038. }
  22039. }
  22040. return null;
  22041. };
  22042. BaseTexture.prototype.delayLoad = function () {
  22043. };
  22044. BaseTexture.prototype.clone = function () {
  22045. return null;
  22046. };
  22047. BaseTexture.prototype.releaseInternalTexture = function () {
  22048. if (this._texture) {
  22049. this._scene.getEngine().releaseInternalTexture(this._texture);
  22050. delete this._texture;
  22051. }
  22052. };
  22053. BaseTexture.prototype.dispose = function () {
  22054. // Animations
  22055. this.getScene().stopAnimation(this);
  22056. // Remove from scene
  22057. var index = this._scene.textures.indexOf(this);
  22058. if (index >= 0) {
  22059. this._scene.textures.splice(index, 1);
  22060. }
  22061. if (this._texture === undefined) {
  22062. return;
  22063. }
  22064. // Release
  22065. this.releaseInternalTexture();
  22066. // Callback
  22067. this.onDisposeObservable.notifyObservers(this);
  22068. this.onDisposeObservable.clear();
  22069. };
  22070. BaseTexture.prototype.serialize = function () {
  22071. if (!this.name) {
  22072. return null;
  22073. }
  22074. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22075. // Animations
  22076. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22077. return serializationObject;
  22078. };
  22079. __decorate([
  22080. BABYLON.serialize()
  22081. ], BaseTexture.prototype, "name", void 0);
  22082. __decorate([
  22083. BABYLON.serialize()
  22084. ], BaseTexture.prototype, "hasAlpha", void 0);
  22085. __decorate([
  22086. BABYLON.serialize()
  22087. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  22088. __decorate([
  22089. BABYLON.serialize()
  22090. ], BaseTexture.prototype, "level", void 0);
  22091. __decorate([
  22092. BABYLON.serialize()
  22093. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  22094. __decorate([
  22095. BABYLON.serialize()
  22096. ], BaseTexture.prototype, "coordinatesMode", void 0);
  22097. __decorate([
  22098. BABYLON.serialize()
  22099. ], BaseTexture.prototype, "wrapU", void 0);
  22100. __decorate([
  22101. BABYLON.serialize()
  22102. ], BaseTexture.prototype, "wrapV", void 0);
  22103. __decorate([
  22104. BABYLON.serialize()
  22105. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  22106. __decorate([
  22107. BABYLON.serialize()
  22108. ], BaseTexture.prototype, "isCube", void 0);
  22109. __decorate([
  22110. BABYLON.serialize()
  22111. ], BaseTexture.prototype, "isRenderTarget", void 0);
  22112. return BaseTexture;
  22113. })();
  22114. BABYLON.BaseTexture = BaseTexture;
  22115. })(BABYLON || (BABYLON = {}));
  22116. var BABYLON;
  22117. (function (BABYLON) {
  22118. var Texture = (function (_super) {
  22119. __extends(Texture, _super);
  22120. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  22121. var _this = this;
  22122. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22123. if (onLoad === void 0) { onLoad = null; }
  22124. if (onError === void 0) { onError = null; }
  22125. if (buffer === void 0) { buffer = null; }
  22126. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22127. _super.call(this, scene);
  22128. this.uOffset = 0;
  22129. this.vOffset = 0;
  22130. this.uScale = 1.0;
  22131. this.vScale = 1.0;
  22132. this.uAng = 0;
  22133. this.vAng = 0;
  22134. this.wAng = 0;
  22135. this.name = url;
  22136. this.url = url;
  22137. this._noMipmap = noMipmap;
  22138. this._invertY = invertY;
  22139. this._samplingMode = samplingMode;
  22140. this._buffer = buffer;
  22141. this._deleteBuffer = deleteBuffer;
  22142. if (!url) {
  22143. return;
  22144. }
  22145. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  22146. var load = function () {
  22147. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  22148. _this.onLoadObservable.notifyObservers(true);
  22149. }
  22150. if (onLoad) {
  22151. onLoad();
  22152. }
  22153. };
  22154. if (!this._texture) {
  22155. if (!scene.useDelayedTextureLoading) {
  22156. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, load, onError, this._buffer);
  22157. if (deleteBuffer) {
  22158. delete this._buffer;
  22159. }
  22160. }
  22161. else {
  22162. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22163. this._delayedOnLoad = load;
  22164. this._delayedOnError = onError;
  22165. }
  22166. }
  22167. else {
  22168. BABYLON.Tools.SetImmediate(function () { return load(); });
  22169. }
  22170. }
  22171. Object.defineProperty(Texture.prototype, "noMipmap", {
  22172. get: function () {
  22173. return this._noMipmap;
  22174. },
  22175. enumerable: true,
  22176. configurable: true
  22177. });
  22178. Texture.prototype.delayLoad = function () {
  22179. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22180. return;
  22181. }
  22182. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22183. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22184. if (!this._texture) {
  22185. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  22186. if (this._deleteBuffer) {
  22187. delete this._buffer;
  22188. }
  22189. }
  22190. };
  22191. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22192. if (!this._texture) {
  22193. return;
  22194. }
  22195. this._samplingMode = samplingMode;
  22196. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22197. };
  22198. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22199. x *= this.uScale;
  22200. y *= this.vScale;
  22201. x -= 0.5 * this.uScale;
  22202. y -= 0.5 * this.vScale;
  22203. z -= 0.5;
  22204. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22205. t.x += 0.5 * this.uScale + this.uOffset;
  22206. t.y += 0.5 * this.vScale + this.vOffset;
  22207. t.z += 0.5;
  22208. };
  22209. Texture.prototype.getTextureMatrix = function () {
  22210. if (this.uOffset === this._cachedUOffset &&
  22211. this.vOffset === this._cachedVOffset &&
  22212. this.uScale === this._cachedUScale &&
  22213. this.vScale === this._cachedVScale &&
  22214. this.uAng === this._cachedUAng &&
  22215. this.vAng === this._cachedVAng &&
  22216. this.wAng === this._cachedWAng) {
  22217. return this._cachedTextureMatrix;
  22218. }
  22219. this._cachedUOffset = this.uOffset;
  22220. this._cachedVOffset = this.vOffset;
  22221. this._cachedUScale = this.uScale;
  22222. this._cachedVScale = this.vScale;
  22223. this._cachedUAng = this.uAng;
  22224. this._cachedVAng = this.vAng;
  22225. this._cachedWAng = this.wAng;
  22226. if (!this._cachedTextureMatrix) {
  22227. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22228. this._rowGenerationMatrix = new BABYLON.Matrix();
  22229. this._t0 = BABYLON.Vector3.Zero();
  22230. this._t1 = BABYLON.Vector3.Zero();
  22231. this._t2 = BABYLON.Vector3.Zero();
  22232. }
  22233. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22234. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22235. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22236. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22237. this._t1.subtractInPlace(this._t0);
  22238. this._t2.subtractInPlace(this._t0);
  22239. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22240. this._cachedTextureMatrix.m[0] = this._t1.x;
  22241. this._cachedTextureMatrix.m[1] = this._t1.y;
  22242. this._cachedTextureMatrix.m[2] = this._t1.z;
  22243. this._cachedTextureMatrix.m[4] = this._t2.x;
  22244. this._cachedTextureMatrix.m[5] = this._t2.y;
  22245. this._cachedTextureMatrix.m[6] = this._t2.z;
  22246. this._cachedTextureMatrix.m[8] = this._t0.x;
  22247. this._cachedTextureMatrix.m[9] = this._t0.y;
  22248. this._cachedTextureMatrix.m[10] = this._t0.z;
  22249. return this._cachedTextureMatrix;
  22250. };
  22251. Texture.prototype.getReflectionTextureMatrix = function () {
  22252. if (this.uOffset === this._cachedUOffset &&
  22253. this.vOffset === this._cachedVOffset &&
  22254. this.uScale === this._cachedUScale &&
  22255. this.vScale === this._cachedVScale &&
  22256. this.coordinatesMode === this._cachedCoordinatesMode) {
  22257. return this._cachedTextureMatrix;
  22258. }
  22259. if (!this._cachedTextureMatrix) {
  22260. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22261. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22262. }
  22263. this._cachedCoordinatesMode = this.coordinatesMode;
  22264. switch (this.coordinatesMode) {
  22265. case Texture.PLANAR_MODE:
  22266. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22267. this._cachedTextureMatrix[0] = this.uScale;
  22268. this._cachedTextureMatrix[5] = this.vScale;
  22269. this._cachedTextureMatrix[12] = this.uOffset;
  22270. this._cachedTextureMatrix[13] = this.vOffset;
  22271. break;
  22272. case Texture.PROJECTION_MODE:
  22273. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22274. this._projectionModeMatrix.m[0] = 0.5;
  22275. this._projectionModeMatrix.m[5] = -0.5;
  22276. this._projectionModeMatrix.m[10] = 0.0;
  22277. this._projectionModeMatrix.m[12] = 0.5;
  22278. this._projectionModeMatrix.m[13] = 0.5;
  22279. this._projectionModeMatrix.m[14] = 1.0;
  22280. this._projectionModeMatrix.m[15] = 1.0;
  22281. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22282. break;
  22283. default:
  22284. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22285. break;
  22286. }
  22287. return this._cachedTextureMatrix;
  22288. };
  22289. Texture.prototype.clone = function () {
  22290. var _this = this;
  22291. return BABYLON.SerializationHelper.Clone(function () {
  22292. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22293. }, this);
  22294. };
  22295. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22296. get: function () {
  22297. if (!this._onLoadObservarble) {
  22298. this._onLoadObservarble = new BABYLON.Observable();
  22299. }
  22300. return this._onLoadObservarble;
  22301. },
  22302. enumerable: true,
  22303. configurable: true
  22304. });
  22305. // Statics
  22306. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  22307. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22308. if (onLoad === void 0) { onLoad = null; }
  22309. if (onError === void 0) { onError = null; }
  22310. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  22311. };
  22312. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22313. if (parsedTexture.isCube) {
  22314. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22315. }
  22316. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22317. return null;
  22318. }
  22319. var texture = BABYLON.SerializationHelper.Parse(function () {
  22320. if (parsedTexture.customType) {
  22321. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22322. return customTexture.Parse(parsedTexture, scene, rootUrl);
  22323. }
  22324. else if (parsedTexture.mirrorPlane) {
  22325. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22326. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22327. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22328. return mirrorTexture;
  22329. }
  22330. else if (parsedTexture.isRenderTarget) {
  22331. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22332. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22333. return renderTargetTexture;
  22334. }
  22335. else {
  22336. var texture;
  22337. if (parsedTexture.base64String) {
  22338. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  22339. }
  22340. else {
  22341. texture = new Texture(rootUrl + parsedTexture.name, scene);
  22342. }
  22343. return texture;
  22344. }
  22345. }, parsedTexture, scene);
  22346. // Animations
  22347. if (parsedTexture.animations) {
  22348. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22349. var parsedAnimation = parsedTexture.animations[animationIndex];
  22350. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22351. }
  22352. }
  22353. return texture;
  22354. };
  22355. // Constants
  22356. Texture.NEAREST_SAMPLINGMODE = 1;
  22357. Texture.BILINEAR_SAMPLINGMODE = 2;
  22358. Texture.TRILINEAR_SAMPLINGMODE = 3;
  22359. Texture.EXPLICIT_MODE = 0;
  22360. Texture.SPHERICAL_MODE = 1;
  22361. Texture.PLANAR_MODE = 2;
  22362. Texture.CUBIC_MODE = 3;
  22363. Texture.PROJECTION_MODE = 4;
  22364. Texture.SKYBOX_MODE = 5;
  22365. Texture.INVCUBIC_MODE = 6;
  22366. Texture.EQUIRECTANGULAR_MODE = 7;
  22367. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22368. Texture.CLAMP_ADDRESSMODE = 0;
  22369. Texture.WRAP_ADDRESSMODE = 1;
  22370. Texture.MIRROR_ADDRESSMODE = 2;
  22371. __decorate([
  22372. BABYLON.serialize()
  22373. ], Texture.prototype, "url", void 0);
  22374. __decorate([
  22375. BABYLON.serialize()
  22376. ], Texture.prototype, "uOffset", void 0);
  22377. __decorate([
  22378. BABYLON.serialize()
  22379. ], Texture.prototype, "vOffset", void 0);
  22380. __decorate([
  22381. BABYLON.serialize()
  22382. ], Texture.prototype, "uScale", void 0);
  22383. __decorate([
  22384. BABYLON.serialize()
  22385. ], Texture.prototype, "vScale", void 0);
  22386. __decorate([
  22387. BABYLON.serialize()
  22388. ], Texture.prototype, "uAng", void 0);
  22389. __decorate([
  22390. BABYLON.serialize()
  22391. ], Texture.prototype, "vAng", void 0);
  22392. __decorate([
  22393. BABYLON.serialize()
  22394. ], Texture.prototype, "wAng", void 0);
  22395. return Texture;
  22396. })(BABYLON.BaseTexture);
  22397. BABYLON.Texture = Texture;
  22398. })(BABYLON || (BABYLON = {}));
  22399. var BABYLON;
  22400. (function (BABYLON) {
  22401. var CubeTexture = (function (_super) {
  22402. __extends(CubeTexture, _super);
  22403. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  22404. _super.call(this, scene);
  22405. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  22406. this.name = rootUrl;
  22407. this.url = rootUrl;
  22408. this._noMipmap = noMipmap;
  22409. this.hasAlpha = false;
  22410. if (!rootUrl && !files) {
  22411. return;
  22412. }
  22413. this._texture = this._getFromCache(rootUrl, noMipmap);
  22414. if (!files) {
  22415. if (!extensions) {
  22416. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  22417. }
  22418. files = [];
  22419. for (var index = 0; index < extensions.length; index++) {
  22420. files.push(rootUrl + extensions[index]);
  22421. }
  22422. this._extensions = extensions;
  22423. }
  22424. this._files = files;
  22425. if (!this._texture) {
  22426. if (!scene.useDelayedTextureLoading) {
  22427. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  22428. }
  22429. else {
  22430. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22431. }
  22432. }
  22433. this.isCube = true;
  22434. this._textureMatrix = BABYLON.Matrix.Identity();
  22435. }
  22436. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  22437. return new CubeTexture("", scene, null, noMipmap, files);
  22438. };
  22439. // Methods
  22440. CubeTexture.prototype.delayLoad = function () {
  22441. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22442. return;
  22443. }
  22444. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22445. this._texture = this._getFromCache(this.url, this._noMipmap);
  22446. if (!this._texture) {
  22447. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  22448. }
  22449. };
  22450. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  22451. return this._textureMatrix;
  22452. };
  22453. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  22454. var texture = BABYLON.SerializationHelper.Parse(function () {
  22455. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  22456. }, parsedTexture, scene);
  22457. // Animations
  22458. if (parsedTexture.animations) {
  22459. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22460. var parsedAnimation = parsedTexture.animations[animationIndex];
  22461. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22462. }
  22463. }
  22464. return texture;
  22465. };
  22466. CubeTexture.prototype.clone = function () {
  22467. var _this = this;
  22468. return BABYLON.SerializationHelper.Clone(function () {
  22469. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  22470. }, this);
  22471. };
  22472. return CubeTexture;
  22473. })(BABYLON.BaseTexture);
  22474. BABYLON.CubeTexture = CubeTexture;
  22475. })(BABYLON || (BABYLON = {}));
  22476. var BABYLON;
  22477. (function (BABYLON) {
  22478. var RenderTargetTexture = (function (_super) {
  22479. __extends(RenderTargetTexture, _super);
  22480. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  22481. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  22482. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22483. if (isCube === void 0) { isCube = false; }
  22484. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22485. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  22486. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  22487. _super.call(this, null, scene, !generateMipMaps);
  22488. this.isCube = isCube;
  22489. /**
  22490. * Use this list to define the list of mesh you want to render.
  22491. */
  22492. this.renderList = new Array();
  22493. this.renderParticles = true;
  22494. this.renderSprites = false;
  22495. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  22496. // Events
  22497. /**
  22498. * An event triggered when the texture is unbind.
  22499. * @type {BABYLON.Observable}
  22500. */
  22501. this.onAfterUnbindObservable = new BABYLON.Observable();
  22502. /**
  22503. * An event triggered before rendering the texture
  22504. * @type {BABYLON.Observable}
  22505. */
  22506. this.onBeforeRenderObservable = new BABYLON.Observable();
  22507. /**
  22508. * An event triggered after rendering the texture
  22509. * @type {BABYLON.Observable}
  22510. */
  22511. this.onAfterRenderObservable = new BABYLON.Observable();
  22512. /**
  22513. * An event triggered after the texture clear
  22514. * @type {BABYLON.Observable}
  22515. */
  22516. this.onClearObservable = new BABYLON.Observable();
  22517. this._currentRefreshId = -1;
  22518. this._refreshRate = 1;
  22519. this.name = name;
  22520. this.isRenderTarget = true;
  22521. this._size = size;
  22522. this._generateMipMaps = generateMipMaps;
  22523. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  22524. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  22525. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22526. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22527. }
  22528. if (isCube) {
  22529. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, {
  22530. generateMipMaps: generateMipMaps,
  22531. samplingMode: samplingMode,
  22532. generateDepthBuffer: generateDepthBuffer,
  22533. generateStencilBuffer: generateStencilBuffer
  22534. });
  22535. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  22536. this._textureMatrix = BABYLON.Matrix.Identity();
  22537. }
  22538. else {
  22539. this._texture = scene.getEngine().createRenderTargetTexture(size, {
  22540. generateMipMaps: generateMipMaps,
  22541. type: type,
  22542. samplingMode: samplingMode,
  22543. generateDepthBuffer: generateDepthBuffer,
  22544. generateStencilBuffer: generateStencilBuffer
  22545. });
  22546. }
  22547. // Rendering groups
  22548. this._renderingManager = new BABYLON.RenderingManager(scene);
  22549. }
  22550. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  22551. get: function () {
  22552. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  22553. },
  22554. enumerable: true,
  22555. configurable: true
  22556. });
  22557. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  22558. get: function () {
  22559. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  22560. },
  22561. enumerable: true,
  22562. configurable: true
  22563. });
  22564. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  22565. get: function () {
  22566. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  22567. },
  22568. enumerable: true,
  22569. configurable: true
  22570. });
  22571. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  22572. set: function (callback) {
  22573. if (this._onAfterUnbindObserver) {
  22574. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  22575. }
  22576. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  22577. },
  22578. enumerable: true,
  22579. configurable: true
  22580. });
  22581. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  22582. set: function (callback) {
  22583. if (this._onBeforeRenderObserver) {
  22584. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22585. }
  22586. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22587. },
  22588. enumerable: true,
  22589. configurable: true
  22590. });
  22591. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  22592. set: function (callback) {
  22593. if (this._onAfterRenderObserver) {
  22594. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22595. }
  22596. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22597. },
  22598. enumerable: true,
  22599. configurable: true
  22600. });
  22601. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  22602. set: function (callback) {
  22603. if (this._onClearObserver) {
  22604. this.onClearObservable.remove(this._onClearObserver);
  22605. }
  22606. this._onClearObserver = this.onClearObservable.add(callback);
  22607. },
  22608. enumerable: true,
  22609. configurable: true
  22610. });
  22611. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  22612. this._currentRefreshId = -1;
  22613. };
  22614. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  22615. get: function () {
  22616. return this._refreshRate;
  22617. },
  22618. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  22619. set: function (value) {
  22620. this._refreshRate = value;
  22621. this.resetRefreshCounter();
  22622. },
  22623. enumerable: true,
  22624. configurable: true
  22625. });
  22626. RenderTargetTexture.prototype._shouldRender = function () {
  22627. if (this._currentRefreshId === -1) {
  22628. this._currentRefreshId = 1;
  22629. return true;
  22630. }
  22631. if (this.refreshRate === this._currentRefreshId) {
  22632. this._currentRefreshId = 1;
  22633. return true;
  22634. }
  22635. this._currentRefreshId++;
  22636. return false;
  22637. };
  22638. RenderTargetTexture.prototype.isReady = function () {
  22639. if (!this.getScene().renderTargetsEnabled) {
  22640. return false;
  22641. }
  22642. return _super.prototype.isReady.call(this);
  22643. };
  22644. RenderTargetTexture.prototype.getRenderSize = function () {
  22645. return this._size;
  22646. };
  22647. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  22648. get: function () {
  22649. return true;
  22650. },
  22651. enumerable: true,
  22652. configurable: true
  22653. });
  22654. RenderTargetTexture.prototype.scale = function (ratio) {
  22655. var newSize = this._size * ratio;
  22656. this.resize(newSize, this._generateMipMaps);
  22657. };
  22658. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  22659. if (this.isCube) {
  22660. return this._textureMatrix;
  22661. }
  22662. return _super.prototype.getReflectionTextureMatrix.call(this);
  22663. };
  22664. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  22665. this.releaseInternalTexture();
  22666. if (this.isCube) {
  22667. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  22668. }
  22669. else {
  22670. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  22671. }
  22672. };
  22673. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  22674. var scene = this.getScene();
  22675. if (this.useCameraPostProcesses !== undefined) {
  22676. useCameraPostProcess = this.useCameraPostProcesses;
  22677. }
  22678. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  22679. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  22680. }
  22681. if (this._waitingRenderList) {
  22682. this.renderList = [];
  22683. for (var index = 0; index < this._waitingRenderList.length; index++) {
  22684. var id = this._waitingRenderList[index];
  22685. this.renderList.push(scene.getMeshByID(id));
  22686. }
  22687. delete this._waitingRenderList;
  22688. }
  22689. // Is predicate defined?
  22690. if (this.renderListPredicate) {
  22691. this.renderList.splice(0); // Clear previous renderList
  22692. var sceneMeshes = this.getScene().meshes;
  22693. for (var index = 0; index < sceneMeshes.length; index++) {
  22694. var mesh = sceneMeshes[index];
  22695. if (this.renderListPredicate(mesh)) {
  22696. this.renderList.push(mesh);
  22697. }
  22698. }
  22699. }
  22700. if (this.renderList && this.renderList.length === 0) {
  22701. return;
  22702. }
  22703. // Prepare renderingManager
  22704. this._renderingManager.reset();
  22705. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  22706. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  22707. var sceneRenderId = scene.getRenderId();
  22708. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  22709. var mesh = currentRenderList[meshIndex];
  22710. if (mesh) {
  22711. if (!mesh.isReady()) {
  22712. // Reset _currentRefreshId
  22713. this.resetRefreshCounter();
  22714. continue;
  22715. }
  22716. mesh._preActivateForIntermediateRendering(sceneRenderId);
  22717. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  22718. mesh._activate(sceneRenderId);
  22719. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  22720. var subMesh = mesh.subMeshes[subIndex];
  22721. scene._activeIndices.addCount(subMesh.indexCount, false);
  22722. this._renderingManager.dispatch(subMesh);
  22723. }
  22724. }
  22725. }
  22726. }
  22727. if (this.isCube) {
  22728. for (var face = 0; face < 6; face++) {
  22729. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  22730. scene.incrementRenderId();
  22731. scene.resetCachedMaterial();
  22732. }
  22733. }
  22734. else {
  22735. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  22736. }
  22737. this.onAfterUnbindObservable.notifyObservers(this);
  22738. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  22739. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  22740. }
  22741. scene.resetCachedMaterial();
  22742. };
  22743. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  22744. var scene = this.getScene();
  22745. var engine = scene.getEngine();
  22746. // Bind
  22747. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  22748. if (this.isCube) {
  22749. engine.bindFramebuffer(this._texture, faceIndex);
  22750. }
  22751. else {
  22752. engine.bindFramebuffer(this._texture);
  22753. }
  22754. }
  22755. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  22756. // Clear
  22757. if (this.onClearObservable.hasObservers()) {
  22758. this.onClearObservable.notifyObservers(engine);
  22759. }
  22760. else {
  22761. engine.clear(scene.clearColor, true, true, true);
  22762. }
  22763. if (!this._doNotChangeAspectRatio) {
  22764. scene.updateTransformMatrix(true);
  22765. }
  22766. // Render
  22767. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  22768. if (useCameraPostProcess) {
  22769. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  22770. }
  22771. if (!this._doNotChangeAspectRatio) {
  22772. scene.updateTransformMatrix(true);
  22773. }
  22774. this.onAfterRenderObservable.notifyObservers(faceIndex);
  22775. // Dump ?
  22776. if (dumpForDebug) {
  22777. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  22778. }
  22779. // Unbind
  22780. if (!this.isCube || faceIndex === 5) {
  22781. if (this.isCube) {
  22782. if (faceIndex === 5) {
  22783. engine.generateMipMapsForCubemap(this._texture);
  22784. }
  22785. }
  22786. engine.unBindFramebuffer(this._texture, this.isCube);
  22787. }
  22788. };
  22789. /**
  22790. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22791. * This allowed control for front to back rendering or reversly depending of the special needs.
  22792. *
  22793. * @param renderingGroupId The rendering group id corresponding to its index
  22794. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22795. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22796. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22797. */
  22798. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22799. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22800. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22801. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22802. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  22803. };
  22804. /**
  22805. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22806. *
  22807. * @param renderingGroupId The rendering group id corresponding to its index
  22808. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22809. */
  22810. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  22811. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  22812. };
  22813. RenderTargetTexture.prototype.clone = function () {
  22814. var textureSize = this.getSize();
  22815. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22816. // Base texture
  22817. newTexture.hasAlpha = this.hasAlpha;
  22818. newTexture.level = this.level;
  22819. // RenderTarget Texture
  22820. newTexture.coordinatesMode = this.coordinatesMode;
  22821. newTexture.renderList = this.renderList.slice(0);
  22822. return newTexture;
  22823. };
  22824. RenderTargetTexture.prototype.serialize = function () {
  22825. if (!this.name) {
  22826. return null;
  22827. }
  22828. var serializationObject = _super.prototype.serialize.call(this);
  22829. serializationObject.renderTargetSize = this.getRenderSize();
  22830. serializationObject.renderList = [];
  22831. for (var index = 0; index < this.renderList.length; index++) {
  22832. serializationObject.renderList.push(this.renderList[index].id);
  22833. }
  22834. return serializationObject;
  22835. };
  22836. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  22837. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  22838. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  22839. return RenderTargetTexture;
  22840. })(BABYLON.Texture);
  22841. BABYLON.RenderTargetTexture = RenderTargetTexture;
  22842. })(BABYLON || (BABYLON = {}));
  22843. var BABYLON;
  22844. (function (BABYLON) {
  22845. var ProceduralTexture = (function (_super) {
  22846. __extends(ProceduralTexture, _super);
  22847. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  22848. if (generateMipMaps === void 0) { generateMipMaps = true; }
  22849. if (isCube === void 0) { isCube = false; }
  22850. _super.call(this, null, scene, !generateMipMaps);
  22851. this.isCube = isCube;
  22852. this.isEnabled = true;
  22853. this._currentRefreshId = -1;
  22854. this._refreshRate = 1;
  22855. this._vertexBuffers = {};
  22856. this._uniforms = new Array();
  22857. this._samplers = new Array();
  22858. this._textures = new Array();
  22859. this._floats = new Array();
  22860. this._floatsArrays = {};
  22861. this._colors3 = new Array();
  22862. this._colors4 = new Array();
  22863. this._vectors2 = new Array();
  22864. this._vectors3 = new Array();
  22865. this._matrices = new Array();
  22866. this._fallbackTextureUsed = false;
  22867. scene._proceduralTextures.push(this);
  22868. this.name = name;
  22869. this.isRenderTarget = true;
  22870. this._size = size;
  22871. this._generateMipMaps = generateMipMaps;
  22872. this.setFragment(fragment);
  22873. this._fallbackTexture = fallbackTexture;
  22874. var engine = scene.getEngine();
  22875. if (isCube) {
  22876. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  22877. this.setFloat("face", 0);
  22878. }
  22879. else {
  22880. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  22881. }
  22882. // VBO
  22883. var vertices = [];
  22884. vertices.push(1, 1);
  22885. vertices.push(-1, 1);
  22886. vertices.push(-1, -1);
  22887. vertices.push(1, -1);
  22888. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  22889. // Indices
  22890. var indices = [];
  22891. indices.push(0);
  22892. indices.push(1);
  22893. indices.push(2);
  22894. indices.push(0);
  22895. indices.push(2);
  22896. indices.push(3);
  22897. this._indexBuffer = engine.createIndexBuffer(indices);
  22898. }
  22899. ProceduralTexture.prototype.reset = function () {
  22900. if (this._effect === undefined) {
  22901. return;
  22902. }
  22903. var engine = this.getScene().getEngine();
  22904. engine._releaseEffect(this._effect);
  22905. };
  22906. ProceduralTexture.prototype.isReady = function () {
  22907. var _this = this;
  22908. var engine = this.getScene().getEngine();
  22909. var shaders;
  22910. if (!this._fragment) {
  22911. return false;
  22912. }
  22913. if (this._fallbackTextureUsed) {
  22914. return true;
  22915. }
  22916. if (this._fragment.fragmentElement !== undefined) {
  22917. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  22918. }
  22919. else {
  22920. shaders = { vertex: "procedural", fragment: this._fragment };
  22921. }
  22922. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  22923. _this.releaseInternalTexture();
  22924. if (_this._fallbackTexture) {
  22925. _this._texture = _this._fallbackTexture._texture;
  22926. _this._texture.references++;
  22927. }
  22928. _this._fallbackTextureUsed = true;
  22929. });
  22930. return this._effect.isReady();
  22931. };
  22932. ProceduralTexture.prototype.resetRefreshCounter = function () {
  22933. this._currentRefreshId = -1;
  22934. };
  22935. ProceduralTexture.prototype.setFragment = function (fragment) {
  22936. this._fragment = fragment;
  22937. };
  22938. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  22939. get: function () {
  22940. return this._refreshRate;
  22941. },
  22942. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  22943. set: function (value) {
  22944. this._refreshRate = value;
  22945. this.resetRefreshCounter();
  22946. },
  22947. enumerable: true,
  22948. configurable: true
  22949. });
  22950. ProceduralTexture.prototype._shouldRender = function () {
  22951. if (!this.isEnabled || !this.isReady() || !this._texture) {
  22952. return false;
  22953. }
  22954. if (this._fallbackTextureUsed) {
  22955. return false;
  22956. }
  22957. if (this._currentRefreshId === -1) {
  22958. this._currentRefreshId = 1;
  22959. return true;
  22960. }
  22961. if (this.refreshRate === this._currentRefreshId) {
  22962. this._currentRefreshId = 1;
  22963. return true;
  22964. }
  22965. this._currentRefreshId++;
  22966. return false;
  22967. };
  22968. ProceduralTexture.prototype.getRenderSize = function () {
  22969. return this._size;
  22970. };
  22971. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  22972. if (this._fallbackTextureUsed) {
  22973. return;
  22974. }
  22975. this.releaseInternalTexture();
  22976. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  22977. };
  22978. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  22979. if (this._uniforms.indexOf(uniformName) === -1) {
  22980. this._uniforms.push(uniformName);
  22981. }
  22982. };
  22983. ProceduralTexture.prototype.setTexture = function (name, texture) {
  22984. if (this._samplers.indexOf(name) === -1) {
  22985. this._samplers.push(name);
  22986. }
  22987. this._textures[name] = texture;
  22988. return this;
  22989. };
  22990. ProceduralTexture.prototype.setFloat = function (name, value) {
  22991. this._checkUniform(name);
  22992. this._floats[name] = value;
  22993. return this;
  22994. };
  22995. ProceduralTexture.prototype.setFloats = function (name, value) {
  22996. this._checkUniform(name);
  22997. this._floatsArrays[name] = value;
  22998. return this;
  22999. };
  23000. ProceduralTexture.prototype.setColor3 = function (name, value) {
  23001. this._checkUniform(name);
  23002. this._colors3[name] = value;
  23003. return this;
  23004. };
  23005. ProceduralTexture.prototype.setColor4 = function (name, value) {
  23006. this._checkUniform(name);
  23007. this._colors4[name] = value;
  23008. return this;
  23009. };
  23010. ProceduralTexture.prototype.setVector2 = function (name, value) {
  23011. this._checkUniform(name);
  23012. this._vectors2[name] = value;
  23013. return this;
  23014. };
  23015. ProceduralTexture.prototype.setVector3 = function (name, value) {
  23016. this._checkUniform(name);
  23017. this._vectors3[name] = value;
  23018. return this;
  23019. };
  23020. ProceduralTexture.prototype.setMatrix = function (name, value) {
  23021. this._checkUniform(name);
  23022. this._matrices[name] = value;
  23023. return this;
  23024. };
  23025. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  23026. var scene = this.getScene();
  23027. var engine = scene.getEngine();
  23028. // Render
  23029. engine.enableEffect(this._effect);
  23030. engine.setState(false);
  23031. // Texture
  23032. for (var name in this._textures) {
  23033. this._effect.setTexture(name, this._textures[name]);
  23034. }
  23035. // Float
  23036. for (name in this._floats) {
  23037. this._effect.setFloat(name, this._floats[name]);
  23038. }
  23039. // Floats
  23040. for (name in this._floatsArrays) {
  23041. this._effect.setArray(name, this._floatsArrays[name]);
  23042. }
  23043. // Color3
  23044. for (name in this._colors3) {
  23045. this._effect.setColor3(name, this._colors3[name]);
  23046. }
  23047. // Color4
  23048. for (name in this._colors4) {
  23049. var color = this._colors4[name];
  23050. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  23051. }
  23052. // Vector2
  23053. for (name in this._vectors2) {
  23054. this._effect.setVector2(name, this._vectors2[name]);
  23055. }
  23056. // Vector3
  23057. for (name in this._vectors3) {
  23058. this._effect.setVector3(name, this._vectors3[name]);
  23059. }
  23060. // Matrix
  23061. for (name in this._matrices) {
  23062. this._effect.setMatrix(name, this._matrices[name]);
  23063. }
  23064. // VBOs
  23065. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  23066. if (this.isCube) {
  23067. for (var face = 0; face < 6; face++) {
  23068. engine.bindFramebuffer(this._texture, face);
  23069. this._effect.setFloat("face", face);
  23070. // Clear
  23071. engine.clear(scene.clearColor, true, true, true);
  23072. // Draw order
  23073. engine.draw(true, 0, 6);
  23074. // Mipmaps
  23075. if (face === 5) {
  23076. engine.generateMipMapsForCubemap(this._texture);
  23077. }
  23078. }
  23079. }
  23080. else {
  23081. engine.bindFramebuffer(this._texture);
  23082. // Clear
  23083. engine.clear(scene.clearColor, true, true, true);
  23084. // Draw order
  23085. engine.draw(true, 0, 6);
  23086. }
  23087. // Unbind
  23088. engine.unBindFramebuffer(this._texture, this.isCube);
  23089. if (this.onGenerated) {
  23090. this.onGenerated();
  23091. }
  23092. };
  23093. ProceduralTexture.prototype.clone = function () {
  23094. var textureSize = this.getSize();
  23095. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  23096. // Base texture
  23097. newTexture.hasAlpha = this.hasAlpha;
  23098. newTexture.level = this.level;
  23099. // RenderTarget Texture
  23100. newTexture.coordinatesMode = this.coordinatesMode;
  23101. return newTexture;
  23102. };
  23103. ProceduralTexture.prototype.dispose = function () {
  23104. var index = this.getScene()._proceduralTextures.indexOf(this);
  23105. if (index >= 0) {
  23106. this.getScene()._proceduralTextures.splice(index, 1);
  23107. }
  23108. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  23109. if (vertexBuffer) {
  23110. vertexBuffer.dispose();
  23111. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  23112. }
  23113. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  23114. this._indexBuffer = null;
  23115. }
  23116. _super.prototype.dispose.call(this);
  23117. };
  23118. return ProceduralTexture;
  23119. })(BABYLON.Texture);
  23120. BABYLON.ProceduralTexture = ProceduralTexture;
  23121. })(BABYLON || (BABYLON = {}));
  23122. var BABYLON;
  23123. (function (BABYLON) {
  23124. var MirrorTexture = (function (_super) {
  23125. __extends(MirrorTexture, _super);
  23126. function MirrorTexture(name, size, scene, generateMipMaps) {
  23127. var _this = this;
  23128. _super.call(this, name, size, scene, generateMipMaps, true);
  23129. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  23130. this._transformMatrix = BABYLON.Matrix.Zero();
  23131. this._mirrorMatrix = BABYLON.Matrix.Zero();
  23132. this.onBeforeRenderObservable.add(function () {
  23133. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  23134. _this._savedViewMatrix = scene.getViewMatrix();
  23135. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  23136. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  23137. scene.clipPlane = _this.mirrorPlane;
  23138. scene.getEngine().cullBackFaces = false;
  23139. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  23140. });
  23141. this.onAfterRenderObservable.add(function () {
  23142. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  23143. scene.getEngine().cullBackFaces = true;
  23144. scene._mirroredCameraPosition = null;
  23145. delete scene.clipPlane;
  23146. });
  23147. }
  23148. MirrorTexture.prototype.clone = function () {
  23149. var textureSize = this.getSize();
  23150. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23151. // Base texture
  23152. newTexture.hasAlpha = this.hasAlpha;
  23153. newTexture.level = this.level;
  23154. // Mirror Texture
  23155. newTexture.mirrorPlane = this.mirrorPlane.clone();
  23156. newTexture.renderList = this.renderList.slice(0);
  23157. return newTexture;
  23158. };
  23159. MirrorTexture.prototype.serialize = function () {
  23160. if (!this.name) {
  23161. return null;
  23162. }
  23163. var serializationObject = _super.prototype.serialize.call(this);
  23164. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  23165. return serializationObject;
  23166. };
  23167. return MirrorTexture;
  23168. })(BABYLON.RenderTargetTexture);
  23169. BABYLON.MirrorTexture = MirrorTexture;
  23170. })(BABYLON || (BABYLON = {}));
  23171. var BABYLON;
  23172. (function (BABYLON) {
  23173. /**
  23174. * Creates a refraction texture used by refraction channel of the standard material.
  23175. * @param name the texture name
  23176. * @param size size of the underlying texture
  23177. * @param scene root scene
  23178. */
  23179. var RefractionTexture = (function (_super) {
  23180. __extends(RefractionTexture, _super);
  23181. function RefractionTexture(name, size, scene, generateMipMaps) {
  23182. var _this = this;
  23183. _super.call(this, name, size, scene, generateMipMaps, true);
  23184. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  23185. this.depth = 2.0;
  23186. this.onBeforeRenderObservable.add(function () {
  23187. scene.clipPlane = _this.refractionPlane;
  23188. });
  23189. this.onAfterRenderObservable.add(function () {
  23190. delete scene.clipPlane;
  23191. });
  23192. }
  23193. RefractionTexture.prototype.clone = function () {
  23194. var textureSize = this.getSize();
  23195. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23196. // Base texture
  23197. newTexture.hasAlpha = this.hasAlpha;
  23198. newTexture.level = this.level;
  23199. // Refraction Texture
  23200. newTexture.refractionPlane = this.refractionPlane.clone();
  23201. newTexture.renderList = this.renderList.slice(0);
  23202. newTexture.depth = this.depth;
  23203. return newTexture;
  23204. };
  23205. RefractionTexture.prototype.serialize = function () {
  23206. if (!this.name) {
  23207. return null;
  23208. }
  23209. var serializationObject = _super.prototype.serialize.call(this);
  23210. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  23211. serializationObject.depth = this.depth;
  23212. return serializationObject;
  23213. };
  23214. return RefractionTexture;
  23215. })(BABYLON.RenderTargetTexture);
  23216. BABYLON.RefractionTexture = RefractionTexture;
  23217. })(BABYLON || (BABYLON = {}));
  23218. var BABYLON;
  23219. (function (BABYLON) {
  23220. var DynamicTexture = (function (_super) {
  23221. __extends(DynamicTexture, _super);
  23222. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  23223. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23224. _super.call(this, null, scene, !generateMipMaps);
  23225. this.name = name;
  23226. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23227. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23228. this._generateMipMaps = generateMipMaps;
  23229. if (options.getContext) {
  23230. this._canvas = options;
  23231. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  23232. }
  23233. else {
  23234. this._canvas = document.createElement("canvas");
  23235. if (options.width) {
  23236. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  23237. }
  23238. else {
  23239. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  23240. }
  23241. }
  23242. var textureSize = this.getSize();
  23243. this._canvas.width = textureSize.width;
  23244. this._canvas.height = textureSize.height;
  23245. this._context = this._canvas.getContext("2d");
  23246. }
  23247. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  23248. get: function () {
  23249. return true;
  23250. },
  23251. enumerable: true,
  23252. configurable: true
  23253. });
  23254. DynamicTexture.prototype.scale = function (ratio) {
  23255. var textureSize = this.getSize();
  23256. textureSize.width *= ratio;
  23257. textureSize.height *= ratio;
  23258. this._canvas.width = textureSize.width;
  23259. this._canvas.height = textureSize.height;
  23260. this.releaseInternalTexture();
  23261. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  23262. };
  23263. DynamicTexture.prototype.getContext = function () {
  23264. return this._context;
  23265. };
  23266. DynamicTexture.prototype.clear = function () {
  23267. var size = this.getSize();
  23268. this._context.fillRect(0, 0, size.width, size.height);
  23269. };
  23270. DynamicTexture.prototype.update = function (invertY) {
  23271. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  23272. };
  23273. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  23274. if (update === void 0) { update = true; }
  23275. var size = this.getSize();
  23276. if (clearColor) {
  23277. this._context.fillStyle = clearColor;
  23278. this._context.fillRect(0, 0, size.width, size.height);
  23279. }
  23280. this._context.font = font;
  23281. if (x === null) {
  23282. var textSize = this._context.measureText(text);
  23283. x = (size.width - textSize.width) / 2;
  23284. }
  23285. this._context.fillStyle = color;
  23286. this._context.fillText(text, x, y);
  23287. if (update) {
  23288. this.update(invertY);
  23289. }
  23290. };
  23291. DynamicTexture.prototype.clone = function () {
  23292. var textureSize = this.getSize();
  23293. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  23294. // Base texture
  23295. newTexture.hasAlpha = this.hasAlpha;
  23296. newTexture.level = this.level;
  23297. // Dynamic Texture
  23298. newTexture.wrapU = this.wrapU;
  23299. newTexture.wrapV = this.wrapV;
  23300. return newTexture;
  23301. };
  23302. return DynamicTexture;
  23303. })(BABYLON.Texture);
  23304. BABYLON.DynamicTexture = DynamicTexture;
  23305. })(BABYLON || (BABYLON = {}));
  23306. var BABYLON;
  23307. (function (BABYLON) {
  23308. var VideoTexture = (function (_super) {
  23309. __extends(VideoTexture, _super);
  23310. /**
  23311. * Creates a video texture.
  23312. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  23313. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  23314. * @param {BABYLON.Scene} scene is obviously the current scene.
  23315. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  23316. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  23317. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  23318. */
  23319. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  23320. var _this = this;
  23321. if (generateMipMaps === void 0) { generateMipMaps = false; }
  23322. if (invertY === void 0) { invertY = false; }
  23323. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23324. _super.call(this, null, scene, !generateMipMaps, invertY);
  23325. this._autoLaunch = true;
  23326. var urls;
  23327. this.name = name;
  23328. if (urlsOrVideo instanceof HTMLVideoElement) {
  23329. this.video = urlsOrVideo;
  23330. }
  23331. else {
  23332. urls = urlsOrVideo;
  23333. this.video = document.createElement("video");
  23334. this.video.autoplay = false;
  23335. this.video.loop = true;
  23336. }
  23337. this._generateMipMaps = generateMipMaps;
  23338. this._samplingMode = samplingMode;
  23339. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  23340. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23341. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23342. }
  23343. else {
  23344. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23345. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23346. this._generateMipMaps = false;
  23347. }
  23348. if (urls) {
  23349. this.video.addEventListener("canplaythrough", function () {
  23350. _this._createTexture();
  23351. });
  23352. urls.forEach(function (url) {
  23353. var source = document.createElement("source");
  23354. source.src = url;
  23355. _this.video.appendChild(source);
  23356. });
  23357. }
  23358. else {
  23359. this._createTexture();
  23360. }
  23361. this._lastUpdate = BABYLON.Tools.Now;
  23362. }
  23363. VideoTexture.prototype._createTexture = function () {
  23364. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  23365. this._texture.isReady = true;
  23366. };
  23367. VideoTexture.prototype.update = function () {
  23368. if (this._autoLaunch) {
  23369. this._autoLaunch = false;
  23370. this.video.play();
  23371. }
  23372. var now = BABYLON.Tools.Now;
  23373. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  23374. return false;
  23375. }
  23376. this._lastUpdate = now;
  23377. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  23378. return true;
  23379. };
  23380. return VideoTexture;
  23381. })(BABYLON.Texture);
  23382. BABYLON.VideoTexture = VideoTexture;
  23383. })(BABYLON || (BABYLON = {}));
  23384. var BABYLON;
  23385. (function (BABYLON) {
  23386. var CustomProceduralTexture = (function (_super) {
  23387. __extends(CustomProceduralTexture, _super);
  23388. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  23389. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  23390. this._animate = true;
  23391. this._time = 0;
  23392. this._texturePath = texturePath;
  23393. //Try to load json
  23394. this.loadJson(texturePath);
  23395. this.refreshRate = 1;
  23396. }
  23397. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  23398. var _this = this;
  23399. var that = this;
  23400. function noConfigFile() {
  23401. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  23402. try {
  23403. that.setFragment(that._texturePath);
  23404. }
  23405. catch (ex) {
  23406. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  23407. }
  23408. }
  23409. var configFileUrl = jsonUrl + "/config.json";
  23410. var xhr = new XMLHttpRequest();
  23411. xhr.open("GET", configFileUrl, true);
  23412. xhr.addEventListener("load", function () {
  23413. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  23414. try {
  23415. _this._config = JSON.parse(xhr.response);
  23416. _this.updateShaderUniforms();
  23417. _this.updateTextures();
  23418. _this.setFragment(_this._texturePath + "/custom");
  23419. _this._animate = _this._config.animate;
  23420. _this.refreshRate = _this._config.refreshrate;
  23421. }
  23422. catch (ex) {
  23423. noConfigFile();
  23424. }
  23425. }
  23426. else {
  23427. noConfigFile();
  23428. }
  23429. }, false);
  23430. xhr.addEventListener("error", function () {
  23431. noConfigFile();
  23432. }, false);
  23433. try {
  23434. xhr.send();
  23435. }
  23436. catch (ex) {
  23437. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  23438. }
  23439. };
  23440. CustomProceduralTexture.prototype.isReady = function () {
  23441. if (!_super.prototype.isReady.call(this)) {
  23442. return false;
  23443. }
  23444. for (var name in this._textures) {
  23445. var texture = this._textures[name];
  23446. if (!texture.isReady()) {
  23447. return false;
  23448. }
  23449. }
  23450. return true;
  23451. };
  23452. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  23453. if (this._animate) {
  23454. this._time += this.getScene().getAnimationRatio() * 0.03;
  23455. this.updateShaderUniforms();
  23456. }
  23457. _super.prototype.render.call(this, useCameraPostProcess);
  23458. };
  23459. CustomProceduralTexture.prototype.updateTextures = function () {
  23460. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  23461. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  23462. }
  23463. };
  23464. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  23465. if (this._config) {
  23466. for (var j = 0; j < this._config.uniforms.length; j++) {
  23467. var uniform = this._config.uniforms[j];
  23468. switch (uniform.type) {
  23469. case "float":
  23470. this.setFloat(uniform.name, uniform.value);
  23471. break;
  23472. case "color3":
  23473. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  23474. break;
  23475. case "color4":
  23476. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  23477. break;
  23478. case "vector2":
  23479. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  23480. break;
  23481. case "vector3":
  23482. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  23483. break;
  23484. }
  23485. }
  23486. }
  23487. this.setFloat("time", this._time);
  23488. };
  23489. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  23490. get: function () {
  23491. return this._animate;
  23492. },
  23493. set: function (value) {
  23494. this._animate = value;
  23495. },
  23496. enumerable: true,
  23497. configurable: true
  23498. });
  23499. return CustomProceduralTexture;
  23500. })(BABYLON.ProceduralTexture);
  23501. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  23502. })(BABYLON || (BABYLON = {}));
  23503. var BABYLON;
  23504. (function (BABYLON) {
  23505. var EffectFallbacks = (function () {
  23506. function EffectFallbacks() {
  23507. this._defines = {};
  23508. this._currentRank = 32;
  23509. this._maxRank = -1;
  23510. }
  23511. EffectFallbacks.prototype.addFallback = function (rank, define) {
  23512. if (!this._defines[rank]) {
  23513. if (rank < this._currentRank) {
  23514. this._currentRank = rank;
  23515. }
  23516. if (rank > this._maxRank) {
  23517. this._maxRank = rank;
  23518. }
  23519. this._defines[rank] = new Array();
  23520. }
  23521. this._defines[rank].push(define);
  23522. };
  23523. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  23524. this._meshRank = rank;
  23525. this._mesh = mesh;
  23526. if (rank > this._maxRank) {
  23527. this._maxRank = rank;
  23528. }
  23529. };
  23530. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  23531. get: function () {
  23532. return this._currentRank <= this._maxRank;
  23533. },
  23534. enumerable: true,
  23535. configurable: true
  23536. });
  23537. EffectFallbacks.prototype.reduce = function (currentDefines) {
  23538. var currentFallbacks = this._defines[this._currentRank];
  23539. for (var index = 0; index < currentFallbacks.length; index++) {
  23540. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  23541. }
  23542. if (this._mesh && this._currentRank === this._meshRank) {
  23543. this._mesh.computeBonesUsingShaders = false;
  23544. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  23545. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  23546. }
  23547. this._currentRank++;
  23548. return currentDefines;
  23549. };
  23550. return EffectFallbacks;
  23551. })();
  23552. BABYLON.EffectFallbacks = EffectFallbacks;
  23553. var Effect = (function () {
  23554. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  23555. var _this = this;
  23556. this._isReady = false;
  23557. this._compilationError = "";
  23558. this._valueCache = {};
  23559. this._engine = engine;
  23560. this.name = baseName;
  23561. this.defines = defines;
  23562. this._uniformsNames = uniformsNames.concat(samplers);
  23563. this._samplers = samplers;
  23564. this._attributesNames = attributesNames;
  23565. this.onError = onError;
  23566. this.onCompiled = onCompiled;
  23567. this._indexParameters = indexParameters;
  23568. var vertexSource;
  23569. var fragmentSource;
  23570. if (baseName.vertexElement) {
  23571. vertexSource = document.getElementById(baseName.vertexElement);
  23572. if (!vertexSource) {
  23573. vertexSource = baseName.vertexElement;
  23574. }
  23575. }
  23576. else {
  23577. vertexSource = baseName.vertex || baseName;
  23578. }
  23579. if (baseName.fragmentElement) {
  23580. fragmentSource = document.getElementById(baseName.fragmentElement);
  23581. if (!fragmentSource) {
  23582. fragmentSource = baseName.fragmentElement;
  23583. }
  23584. }
  23585. else {
  23586. fragmentSource = baseName.fragment || baseName;
  23587. }
  23588. this._loadVertexShader(vertexSource, function (vertexCode) {
  23589. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  23590. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  23591. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  23592. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  23593. });
  23594. });
  23595. });
  23596. });
  23597. }
  23598. // Properties
  23599. Effect.prototype.isReady = function () {
  23600. return this._isReady;
  23601. };
  23602. Effect.prototype.getProgram = function () {
  23603. return this._program;
  23604. };
  23605. Effect.prototype.getAttributesNames = function () {
  23606. return this._attributesNames;
  23607. };
  23608. Effect.prototype.getAttributeLocation = function (index) {
  23609. return this._attributes[index];
  23610. };
  23611. Effect.prototype.getAttributeLocationByName = function (name) {
  23612. var index = this._attributesNames.indexOf(name);
  23613. return this._attributes[index];
  23614. };
  23615. Effect.prototype.getAttributesCount = function () {
  23616. return this._attributes.length;
  23617. };
  23618. Effect.prototype.getUniformIndex = function (uniformName) {
  23619. return this._uniformsNames.indexOf(uniformName);
  23620. };
  23621. Effect.prototype.getUniform = function (uniformName) {
  23622. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  23623. };
  23624. Effect.prototype.getSamplers = function () {
  23625. return this._samplers;
  23626. };
  23627. Effect.prototype.getCompilationError = function () {
  23628. return this._compilationError;
  23629. };
  23630. // Methods
  23631. Effect.prototype._loadVertexShader = function (vertex, callback) {
  23632. // DOM element ?
  23633. if (vertex instanceof HTMLElement) {
  23634. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  23635. callback(vertexCode);
  23636. return;
  23637. }
  23638. // Is in local store ?
  23639. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  23640. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  23641. return;
  23642. }
  23643. var vertexShaderUrl;
  23644. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  23645. vertexShaderUrl = vertex;
  23646. }
  23647. else {
  23648. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  23649. }
  23650. // Vertex shader
  23651. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  23652. };
  23653. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  23654. // DOM element ?
  23655. if (fragment instanceof HTMLElement) {
  23656. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  23657. callback(fragmentCode);
  23658. return;
  23659. }
  23660. // Is in local store ?
  23661. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  23662. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  23663. return;
  23664. }
  23665. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  23666. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  23667. return;
  23668. }
  23669. var fragmentShaderUrl;
  23670. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  23671. fragmentShaderUrl = fragment;
  23672. }
  23673. else {
  23674. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  23675. }
  23676. // Fragment shader
  23677. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  23678. };
  23679. Effect.prototype._dumpShadersName = function () {
  23680. if (this.name.vertexElement) {
  23681. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  23682. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  23683. }
  23684. else if (this.name.vertex) {
  23685. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  23686. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  23687. }
  23688. else {
  23689. BABYLON.Tools.Error("Vertex shader:" + this.name);
  23690. BABYLON.Tools.Error("Fragment shader:" + this.name);
  23691. }
  23692. };
  23693. Effect.prototype._processIncludes = function (sourceCode, callback) {
  23694. var _this = this;
  23695. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  23696. var match = regex.exec(sourceCode);
  23697. var returnValue = new String(sourceCode);
  23698. while (match != null) {
  23699. var includeFile = match[1];
  23700. if (Effect.IncludesShadersStore[includeFile]) {
  23701. // Substitution
  23702. var includeContent = Effect.IncludesShadersStore[includeFile];
  23703. if (match[2]) {
  23704. var splits = match[3].split(",");
  23705. for (var index = 0; index < splits.length; index += 2) {
  23706. var source = new RegExp(splits[index], "g");
  23707. var dest = splits[index + 1];
  23708. includeContent = includeContent.replace(source, dest);
  23709. }
  23710. }
  23711. if (match[4]) {
  23712. var indexString = match[5];
  23713. if (indexString.indexOf("..") !== -1) {
  23714. var indexSplits = indexString.split("..");
  23715. var minIndex = parseInt(indexSplits[0]);
  23716. var maxIndex = parseInt(indexSplits[1]);
  23717. var sourceIncludeContent = includeContent.slice(0);
  23718. includeContent = "";
  23719. if (isNaN(maxIndex)) {
  23720. maxIndex = this._indexParameters[indexSplits[1]];
  23721. }
  23722. for (var i = minIndex; i <= maxIndex; i++) {
  23723. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  23724. }
  23725. }
  23726. else {
  23727. includeContent = includeContent.replace(/\{X\}/g, indexString);
  23728. }
  23729. }
  23730. // Replace
  23731. returnValue = returnValue.replace(match[0], includeContent);
  23732. }
  23733. else {
  23734. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  23735. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  23736. Effect.IncludesShadersStore[includeFile] = fileContent;
  23737. _this._processIncludes(returnValue, callback);
  23738. });
  23739. return;
  23740. }
  23741. match = regex.exec(sourceCode);
  23742. }
  23743. callback(returnValue);
  23744. };
  23745. Effect.prototype._processPrecision = function (source) {
  23746. if (source.indexOf("precision highp float") === -1) {
  23747. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23748. source = "precision mediump float;\n" + source;
  23749. }
  23750. else {
  23751. source = "precision highp float;\n" + source;
  23752. }
  23753. }
  23754. else {
  23755. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23756. source = source.replace("precision highp float", "precision mediump float");
  23757. }
  23758. }
  23759. return source;
  23760. };
  23761. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  23762. try {
  23763. var engine = this._engine;
  23764. // Precision
  23765. vertexSourceCode = this._processPrecision(vertexSourceCode);
  23766. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  23767. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  23768. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  23769. this._attributes = engine.getAttributes(this._program, attributesNames);
  23770. var index;
  23771. for (index = 0; index < this._samplers.length; index++) {
  23772. var sampler = this.getUniform(this._samplers[index]);
  23773. if (sampler == null) {
  23774. this._samplers.splice(index, 1);
  23775. index--;
  23776. }
  23777. }
  23778. engine.bindSamplers(this);
  23779. this._isReady = true;
  23780. if (this.onCompiled) {
  23781. this.onCompiled(this);
  23782. }
  23783. }
  23784. catch (e) {
  23785. // Let's go through fallbacks then
  23786. if (fallbacks && fallbacks.isMoreFallbacks) {
  23787. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  23788. this._dumpShadersName();
  23789. defines = fallbacks.reduce(defines);
  23790. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  23791. }
  23792. else {
  23793. BABYLON.Tools.Error("Unable to compile effect: ");
  23794. this._dumpShadersName();
  23795. BABYLON.Tools.Error("Defines: " + defines);
  23796. BABYLON.Tools.Error("Error: " + e.message);
  23797. this._compilationError = e.message;
  23798. if (this.onError) {
  23799. this.onError(this, this._compilationError);
  23800. }
  23801. }
  23802. }
  23803. };
  23804. Object.defineProperty(Effect.prototype, "isSupported", {
  23805. get: function () {
  23806. return this._compilationError === "";
  23807. },
  23808. enumerable: true,
  23809. configurable: true
  23810. });
  23811. Effect.prototype._bindTexture = function (channel, texture) {
  23812. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  23813. };
  23814. Effect.prototype.setTexture = function (channel, texture) {
  23815. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  23816. };
  23817. Effect.prototype.setTextureArray = function (channel, textures) {
  23818. if (this._samplers.indexOf(channel + "Ex") === -1) {
  23819. var initialPos = this._samplers.indexOf(channel);
  23820. for (var index = 1; index < textures.length; index++) {
  23821. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  23822. }
  23823. }
  23824. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  23825. };
  23826. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  23827. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  23828. };
  23829. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  23830. var changed = false;
  23831. var cache = this._valueCache[uniformName];
  23832. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  23833. changed = true;
  23834. cache = new BABYLON.Matrix();
  23835. }
  23836. var tm = cache.m;
  23837. var om = matrix.m;
  23838. for (var index = 0; index < 16; index++) {
  23839. if (tm[index] !== om[index]) {
  23840. tm[index] = om[index];
  23841. changed = true;
  23842. }
  23843. }
  23844. this._valueCache[uniformName] = cache;
  23845. return changed;
  23846. };
  23847. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  23848. var cache = this._valueCache[uniformName];
  23849. if (!cache) {
  23850. cache = [x, y];
  23851. this._valueCache[uniformName] = cache;
  23852. return true;
  23853. }
  23854. var changed = false;
  23855. if (cache[0] !== x) {
  23856. cache[0] = x;
  23857. changed = true;
  23858. }
  23859. if (cache[1] !== y) {
  23860. cache[1] = y;
  23861. changed = true;
  23862. }
  23863. return changed;
  23864. };
  23865. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  23866. var cache = this._valueCache[uniformName];
  23867. if (!cache) {
  23868. cache = [x, y, z];
  23869. this._valueCache[uniformName] = cache;
  23870. return true;
  23871. }
  23872. var changed = false;
  23873. if (cache[0] !== x) {
  23874. cache[0] = x;
  23875. changed = true;
  23876. }
  23877. if (cache[1] !== y) {
  23878. cache[1] = y;
  23879. changed = true;
  23880. }
  23881. if (cache[2] !== z) {
  23882. cache[2] = z;
  23883. changed = true;
  23884. }
  23885. return changed;
  23886. };
  23887. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  23888. var cache = this._valueCache[uniformName];
  23889. if (!cache) {
  23890. cache = [x, y, z, w];
  23891. this._valueCache[uniformName] = cache;
  23892. return true;
  23893. }
  23894. var changed = false;
  23895. if (cache[0] !== x) {
  23896. cache[0] = x;
  23897. changed = true;
  23898. }
  23899. if (cache[1] !== y) {
  23900. cache[1] = y;
  23901. changed = true;
  23902. }
  23903. if (cache[2] !== z) {
  23904. cache[2] = z;
  23905. changed = true;
  23906. }
  23907. if (cache[3] !== w) {
  23908. cache[3] = w;
  23909. changed = true;
  23910. }
  23911. return changed;
  23912. };
  23913. Effect.prototype.setIntArray = function (uniformName, array) {
  23914. this._valueCache[uniformName] = null;
  23915. this._engine.setIntArray(this.getUniform(uniformName), array);
  23916. return this;
  23917. };
  23918. Effect.prototype.setIntArray2 = function (uniformName, array) {
  23919. this._valueCache[uniformName] = null;
  23920. this._engine.setIntArray2(this.getUniform(uniformName), array);
  23921. return this;
  23922. };
  23923. Effect.prototype.setIntArray3 = function (uniformName, array) {
  23924. this._valueCache[uniformName] = null;
  23925. this._engine.setIntArray3(this.getUniform(uniformName), array);
  23926. return this;
  23927. };
  23928. Effect.prototype.setIntArray4 = function (uniformName, array) {
  23929. this._valueCache[uniformName] = null;
  23930. this._engine.setIntArray4(this.getUniform(uniformName), array);
  23931. return this;
  23932. };
  23933. Effect.prototype.setFloatArray = function (uniformName, array) {
  23934. this._valueCache[uniformName] = null;
  23935. this._engine.setFloatArray(this.getUniform(uniformName), array);
  23936. return this;
  23937. };
  23938. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  23939. this._valueCache[uniformName] = null;
  23940. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  23941. return this;
  23942. };
  23943. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  23944. this._valueCache[uniformName] = null;
  23945. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  23946. return this;
  23947. };
  23948. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  23949. this._valueCache[uniformName] = null;
  23950. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  23951. return this;
  23952. };
  23953. Effect.prototype.setArray = function (uniformName, array) {
  23954. this._valueCache[uniformName] = null;
  23955. this._engine.setArray(this.getUniform(uniformName), array);
  23956. return this;
  23957. };
  23958. Effect.prototype.setArray2 = function (uniformName, array) {
  23959. this._valueCache[uniformName] = null;
  23960. this._engine.setArray2(this.getUniform(uniformName), array);
  23961. return this;
  23962. };
  23963. Effect.prototype.setArray3 = function (uniformName, array) {
  23964. this._valueCache[uniformName] = null;
  23965. this._engine.setArray3(this.getUniform(uniformName), array);
  23966. return this;
  23967. };
  23968. Effect.prototype.setArray4 = function (uniformName, array) {
  23969. this._valueCache[uniformName] = null;
  23970. this._engine.setArray4(this.getUniform(uniformName), array);
  23971. return this;
  23972. };
  23973. Effect.prototype.setMatrices = function (uniformName, matrices) {
  23974. this._valueCache[uniformName] = null;
  23975. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  23976. return this;
  23977. };
  23978. Effect.prototype.setMatrix = function (uniformName, matrix) {
  23979. if (this._cacheMatrix(uniformName, matrix)) {
  23980. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  23981. }
  23982. return this;
  23983. };
  23984. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  23985. this._valueCache[uniformName] = null;
  23986. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  23987. return this;
  23988. };
  23989. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  23990. this._valueCache[uniformName] = null;
  23991. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  23992. return this;
  23993. };
  23994. Effect.prototype.setFloat = function (uniformName, value) {
  23995. var cache = this._valueCache[uniformName];
  23996. if (cache !== undefined && cache === value)
  23997. return this;
  23998. this._valueCache[uniformName] = value;
  23999. this._engine.setFloat(this.getUniform(uniformName), value);
  24000. return this;
  24001. };
  24002. Effect.prototype.setBool = function (uniformName, bool) {
  24003. var cache = this._valueCache[uniformName];
  24004. if (cache !== undefined && cache === bool)
  24005. return this;
  24006. this._valueCache[uniformName] = bool;
  24007. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24008. return this;
  24009. };
  24010. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24011. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24012. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24013. }
  24014. return this;
  24015. };
  24016. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24017. if (this._cacheFloat2(uniformName, x, y)) {
  24018. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24019. }
  24020. return this;
  24021. };
  24022. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24023. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24024. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24025. }
  24026. return this;
  24027. };
  24028. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24029. if (this._cacheFloat3(uniformName, x, y, z)) {
  24030. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24031. }
  24032. return this;
  24033. };
  24034. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24035. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24036. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24037. }
  24038. return this;
  24039. };
  24040. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24041. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24042. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24043. }
  24044. return this;
  24045. };
  24046. Effect.prototype.setColor3 = function (uniformName, color3) {
  24047. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24048. this._engine.setColor3(this.getUniform(uniformName), color3);
  24049. }
  24050. return this;
  24051. };
  24052. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24053. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24054. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24055. }
  24056. return this;
  24057. };
  24058. // Statics
  24059. Effect.ShadersStore = {};
  24060. Effect.IncludesShadersStore = {};
  24061. return Effect;
  24062. })();
  24063. BABYLON.Effect = Effect;
  24064. })(BABYLON || (BABYLON = {}));
  24065. var BABYLON;
  24066. (function (BABYLON) {
  24067. var MaterialHelper = (function () {
  24068. function MaterialHelper() {
  24069. }
  24070. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  24071. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24072. var lightIndex = 0;
  24073. var needNormals = false;
  24074. var needRebuild = false;
  24075. var needShadows = false;
  24076. for (var index = 0; index < scene.lights.length; index++) {
  24077. var light = scene.lights[index];
  24078. if (!light.isEnabled()) {
  24079. continue;
  24080. }
  24081. // Excluded check
  24082. if (light._excludedMeshesIds.length > 0) {
  24083. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  24084. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  24085. if (excludedMesh) {
  24086. light.excludedMeshes.push(excludedMesh);
  24087. }
  24088. }
  24089. light._excludedMeshesIds = [];
  24090. }
  24091. // Included check
  24092. if (light._includedOnlyMeshesIds.length > 0) {
  24093. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  24094. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  24095. if (includedOnlyMesh) {
  24096. light.includedOnlyMeshes.push(includedOnlyMesh);
  24097. }
  24098. }
  24099. light._includedOnlyMeshesIds = [];
  24100. }
  24101. if (!light.canAffectMesh(mesh)) {
  24102. continue;
  24103. }
  24104. needNormals = true;
  24105. if (defines["LIGHT" + lightIndex] === undefined) {
  24106. needRebuild = true;
  24107. }
  24108. defines["LIGHT" + lightIndex] = true;
  24109. var type;
  24110. if (light instanceof BABYLON.SpotLight) {
  24111. type = "SPOTLIGHT" + lightIndex;
  24112. }
  24113. else if (light instanceof BABYLON.HemisphericLight) {
  24114. type = "HEMILIGHT" + lightIndex;
  24115. }
  24116. else if (light instanceof BABYLON.PointLight) {
  24117. type = "POINTLIGHT" + lightIndex;
  24118. }
  24119. else {
  24120. type = "DIRLIGHT" + lightIndex;
  24121. }
  24122. if (defines[type] === undefined) {
  24123. needRebuild = true;
  24124. }
  24125. defines[type] = true;
  24126. // Specular
  24127. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  24128. defines["SPECULARTERM"] = true;
  24129. }
  24130. // Shadows
  24131. if (scene.shadowsEnabled) {
  24132. var shadowGenerator = light.getShadowGenerator();
  24133. if (mesh && mesh.receiveShadows && shadowGenerator) {
  24134. if (defines["SHADOW" + lightIndex] === undefined) {
  24135. needRebuild = true;
  24136. }
  24137. defines["SHADOW" + lightIndex] = true;
  24138. defines["SHADOWS"] = true;
  24139. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  24140. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  24141. needRebuild = true;
  24142. }
  24143. defines["SHADOWVSM" + lightIndex] = true;
  24144. }
  24145. if (shadowGenerator.usePoissonSampling) {
  24146. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  24147. needRebuild = true;
  24148. }
  24149. defines["SHADOWPCF" + lightIndex] = true;
  24150. }
  24151. needShadows = true;
  24152. }
  24153. }
  24154. lightIndex++;
  24155. if (lightIndex === maxSimultaneousLights)
  24156. break;
  24157. }
  24158. var caps = scene.getEngine().getCaps();
  24159. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  24160. if (defines["SHADOWFULLFLOAT"] === undefined) {
  24161. needRebuild = true;
  24162. }
  24163. defines["SHADOWFULLFLOAT"] = true;
  24164. }
  24165. if (needRebuild) {
  24166. defines.rebuild();
  24167. }
  24168. return needNormals;
  24169. };
  24170. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  24171. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24172. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24173. if (!defines["LIGHT" + lightIndex]) {
  24174. break;
  24175. }
  24176. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  24177. samplersList.push("shadowSampler" + lightIndex);
  24178. }
  24179. };
  24180. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  24181. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24182. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24183. if (!defines["LIGHT" + lightIndex]) {
  24184. break;
  24185. }
  24186. if (lightIndex > 0) {
  24187. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  24188. }
  24189. if (defines["SHADOW" + lightIndex]) {
  24190. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  24191. }
  24192. if (defines["SHADOWPCF" + lightIndex]) {
  24193. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  24194. }
  24195. if (defines["SHADOWVSM" + lightIndex]) {
  24196. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  24197. }
  24198. }
  24199. };
  24200. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  24201. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  24202. fallbacks.addCPUSkinningFallback(0, mesh);
  24203. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24204. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24205. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  24206. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  24207. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  24208. }
  24209. }
  24210. };
  24211. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  24212. if (defines["INSTANCES"]) {
  24213. attribs.push("world0");
  24214. attribs.push("world1");
  24215. attribs.push("world2");
  24216. attribs.push("world3");
  24217. }
  24218. };
  24219. // Bindings
  24220. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  24221. var shadowGenerator = light.getShadowGenerator();
  24222. if (mesh.receiveShadows && shadowGenerator) {
  24223. if (!light.needCube()) {
  24224. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  24225. }
  24226. else {
  24227. if (!depthValuesAlreadySet) {
  24228. depthValuesAlreadySet = true;
  24229. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  24230. }
  24231. }
  24232. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  24233. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  24234. }
  24235. return depthValuesAlreadySet;
  24236. };
  24237. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  24238. if (light instanceof BABYLON.PointLight) {
  24239. // Point Light
  24240. light.transferToEffect(effect, "vLightData" + lightIndex);
  24241. }
  24242. else if (light instanceof BABYLON.DirectionalLight) {
  24243. // Directional Light
  24244. light.transferToEffect(effect, "vLightData" + lightIndex);
  24245. }
  24246. else if (light instanceof BABYLON.SpotLight) {
  24247. // Spot Light
  24248. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  24249. }
  24250. else if (light instanceof BABYLON.HemisphericLight) {
  24251. // Hemispheric Light
  24252. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  24253. }
  24254. };
  24255. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  24256. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24257. var lightIndex = 0;
  24258. var depthValuesAlreadySet = false;
  24259. for (var index = 0; index < scene.lights.length; index++) {
  24260. var light = scene.lights[index];
  24261. if (!light.isEnabled()) {
  24262. continue;
  24263. }
  24264. if (!light.canAffectMesh(mesh)) {
  24265. continue;
  24266. }
  24267. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  24268. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  24269. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  24270. if (defines["SPECULARTERM"]) {
  24271. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  24272. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  24273. }
  24274. // Shadows
  24275. if (scene.shadowsEnabled) {
  24276. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  24277. }
  24278. lightIndex++;
  24279. if (lightIndex === maxSimultaneousLights)
  24280. break;
  24281. }
  24282. };
  24283. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  24284. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  24285. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  24286. effect.setColor3("vFogColor", scene.fogColor);
  24287. }
  24288. };
  24289. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  24290. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  24291. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  24292. }
  24293. };
  24294. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  24295. if (defines["LOGARITHMICDEPTH"]) {
  24296. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  24297. }
  24298. };
  24299. MaterialHelper.BindClipPlane = function (effect, scene) {
  24300. if (scene.clipPlane) {
  24301. var clipPlane = scene.clipPlane;
  24302. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  24303. }
  24304. };
  24305. return MaterialHelper;
  24306. })();
  24307. BABYLON.MaterialHelper = MaterialHelper;
  24308. })(BABYLON || (BABYLON = {}));
  24309. var BABYLON;
  24310. (function (BABYLON) {
  24311. var FresnelParameters = (function () {
  24312. function FresnelParameters() {
  24313. this.isEnabled = true;
  24314. this.leftColor = BABYLON.Color3.White();
  24315. this.rightColor = BABYLON.Color3.Black();
  24316. this.bias = 0;
  24317. this.power = 1;
  24318. }
  24319. FresnelParameters.prototype.clone = function () {
  24320. var newFresnelParameters = new FresnelParameters();
  24321. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  24322. return new FresnelParameters;
  24323. };
  24324. FresnelParameters.prototype.serialize = function () {
  24325. var serializationObject = {};
  24326. serializationObject.isEnabled = this.isEnabled;
  24327. serializationObject.leftColor = this.leftColor;
  24328. serializationObject.rightColor = this.rightColor;
  24329. serializationObject.bias = this.bias;
  24330. serializationObject.power = this.power;
  24331. return serializationObject;
  24332. };
  24333. FresnelParameters.Parse = function (parsedFresnelParameters) {
  24334. var fresnelParameters = new FresnelParameters();
  24335. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  24336. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  24337. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  24338. fresnelParameters.bias = parsedFresnelParameters.bias;
  24339. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  24340. return fresnelParameters;
  24341. };
  24342. return FresnelParameters;
  24343. })();
  24344. BABYLON.FresnelParameters = FresnelParameters;
  24345. })(BABYLON || (BABYLON = {}));
  24346. var BABYLON;
  24347. (function (BABYLON) {
  24348. var MaterialDefines = (function () {
  24349. function MaterialDefines() {
  24350. }
  24351. MaterialDefines.prototype.rebuild = function () {
  24352. if (this._keys) {
  24353. delete this._keys;
  24354. }
  24355. this._keys = Object.keys(this);
  24356. };
  24357. MaterialDefines.prototype.isEqual = function (other) {
  24358. if (this._keys.length !== other._keys.length) {
  24359. return false;
  24360. }
  24361. for (var index = 0; index < this._keys.length; index++) {
  24362. var prop = this._keys[index];
  24363. if (this[prop] !== other[prop]) {
  24364. return false;
  24365. }
  24366. }
  24367. return true;
  24368. };
  24369. MaterialDefines.prototype.cloneTo = function (other) {
  24370. if (this._keys.length !== other._keys.length) {
  24371. other._keys = this._keys.slice(0);
  24372. }
  24373. for (var index = 0; index < this._keys.length; index++) {
  24374. var prop = this._keys[index];
  24375. other[prop] = this[prop];
  24376. }
  24377. };
  24378. MaterialDefines.prototype.reset = function () {
  24379. for (var index = 0; index < this._keys.length; index++) {
  24380. var prop = this._keys[index];
  24381. if (typeof (this[prop]) === "number") {
  24382. this[prop] = 0;
  24383. }
  24384. else {
  24385. this[prop] = false;
  24386. }
  24387. }
  24388. };
  24389. MaterialDefines.prototype.toString = function () {
  24390. var result = "";
  24391. for (var index = 0; index < this._keys.length; index++) {
  24392. var prop = this._keys[index];
  24393. if (typeof (this[prop]) === "number") {
  24394. result += "#define " + prop + " " + this[prop] + "\n";
  24395. }
  24396. else if (this[prop]) {
  24397. result += "#define " + prop + "\n";
  24398. }
  24399. }
  24400. return result;
  24401. };
  24402. return MaterialDefines;
  24403. })();
  24404. BABYLON.MaterialDefines = MaterialDefines;
  24405. var Material = (function () {
  24406. function Material(name, scene, doNotAdd) {
  24407. this.name = name;
  24408. this.checkReadyOnEveryCall = false;
  24409. this.checkReadyOnlyOnce = false;
  24410. this.state = "";
  24411. this.alpha = 1.0;
  24412. this.backFaceCulling = true;
  24413. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  24414. /**
  24415. * An event triggered when the material is disposed.
  24416. * @type {BABYLON.Observable}
  24417. */
  24418. this.onDisposeObservable = new BABYLON.Observable();
  24419. /**
  24420. * An event triggered when the material is bound.
  24421. * @type {BABYLON.Observable}
  24422. */
  24423. this.onBindObservable = new BABYLON.Observable();
  24424. /**
  24425. * An event triggered when the material is unbound.
  24426. * @type {BABYLON.Observable}
  24427. */
  24428. this.onUnBindObservable = new BABYLON.Observable();
  24429. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  24430. this.disableDepthWrite = false;
  24431. this.fogEnabled = true;
  24432. this.pointSize = 1.0;
  24433. this.zOffset = 0;
  24434. this._wasPreviouslyReady = false;
  24435. this._fillMode = Material.TriangleFillMode;
  24436. this.id = name;
  24437. this._scene = scene;
  24438. if (!doNotAdd) {
  24439. scene.materials.push(this);
  24440. }
  24441. }
  24442. Object.defineProperty(Material, "TriangleFillMode", {
  24443. get: function () {
  24444. return Material._TriangleFillMode;
  24445. },
  24446. enumerable: true,
  24447. configurable: true
  24448. });
  24449. Object.defineProperty(Material, "WireFrameFillMode", {
  24450. get: function () {
  24451. return Material._WireFrameFillMode;
  24452. },
  24453. enumerable: true,
  24454. configurable: true
  24455. });
  24456. Object.defineProperty(Material, "PointFillMode", {
  24457. get: function () {
  24458. return Material._PointFillMode;
  24459. },
  24460. enumerable: true,
  24461. configurable: true
  24462. });
  24463. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  24464. get: function () {
  24465. return Material._ClockWiseSideOrientation;
  24466. },
  24467. enumerable: true,
  24468. configurable: true
  24469. });
  24470. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  24471. get: function () {
  24472. return Material._CounterClockWiseSideOrientation;
  24473. },
  24474. enumerable: true,
  24475. configurable: true
  24476. });
  24477. Object.defineProperty(Material.prototype, "onDispose", {
  24478. set: function (callback) {
  24479. if (this._onDisposeObserver) {
  24480. this.onDisposeObservable.remove(this._onDisposeObserver);
  24481. }
  24482. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24483. },
  24484. enumerable: true,
  24485. configurable: true
  24486. });
  24487. Object.defineProperty(Material.prototype, "onBind", {
  24488. set: function (callback) {
  24489. if (this._onBindObserver) {
  24490. this.onBindObservable.remove(this._onBindObserver);
  24491. }
  24492. this._onBindObserver = this.onBindObservable.add(callback);
  24493. },
  24494. enumerable: true,
  24495. configurable: true
  24496. });
  24497. Object.defineProperty(Material.prototype, "wireframe", {
  24498. get: function () {
  24499. return this._fillMode === Material.WireFrameFillMode;
  24500. },
  24501. set: function (value) {
  24502. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  24503. },
  24504. enumerable: true,
  24505. configurable: true
  24506. });
  24507. Object.defineProperty(Material.prototype, "pointsCloud", {
  24508. get: function () {
  24509. return this._fillMode === Material.PointFillMode;
  24510. },
  24511. set: function (value) {
  24512. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  24513. },
  24514. enumerable: true,
  24515. configurable: true
  24516. });
  24517. Object.defineProperty(Material.prototype, "fillMode", {
  24518. get: function () {
  24519. return this._fillMode;
  24520. },
  24521. set: function (value) {
  24522. this._fillMode = value;
  24523. },
  24524. enumerable: true,
  24525. configurable: true
  24526. });
  24527. /**
  24528. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24529. * subclasses should override adding information pertainent to themselves
  24530. */
  24531. Material.prototype.toString = function (fullDetails) {
  24532. var ret = "Name: " + this.name;
  24533. if (fullDetails) {
  24534. }
  24535. return ret;
  24536. };
  24537. Object.defineProperty(Material.prototype, "isFrozen", {
  24538. get: function () {
  24539. return this.checkReadyOnlyOnce;
  24540. },
  24541. enumerable: true,
  24542. configurable: true
  24543. });
  24544. Material.prototype.freeze = function () {
  24545. this.checkReadyOnlyOnce = true;
  24546. };
  24547. Material.prototype.unfreeze = function () {
  24548. this.checkReadyOnlyOnce = false;
  24549. };
  24550. Material.prototype.isReady = function (mesh, useInstances) {
  24551. return true;
  24552. };
  24553. Material.prototype.getEffect = function () {
  24554. return this._effect;
  24555. };
  24556. Material.prototype.getScene = function () {
  24557. return this._scene;
  24558. };
  24559. Material.prototype.needAlphaBlending = function () {
  24560. return (this.alpha < 1.0);
  24561. };
  24562. Material.prototype.needAlphaTesting = function () {
  24563. return false;
  24564. };
  24565. Material.prototype.getAlphaTestTexture = function () {
  24566. return null;
  24567. };
  24568. Material.prototype.markDirty = function () {
  24569. this._wasPreviouslyReady = false;
  24570. };
  24571. Material.prototype._preBind = function () {
  24572. var engine = this._scene.getEngine();
  24573. engine.enableEffect(this._effect);
  24574. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  24575. };
  24576. Material.prototype.bind = function (world, mesh) {
  24577. this._scene._cachedMaterial = this;
  24578. this.onBindObservable.notifyObservers(mesh);
  24579. if (this.disableDepthWrite) {
  24580. var engine = this._scene.getEngine();
  24581. this._cachedDepthWriteState = engine.getDepthWrite();
  24582. engine.setDepthWrite(false);
  24583. }
  24584. };
  24585. Material.prototype.bindOnlyWorldMatrix = function (world) {
  24586. };
  24587. Material.prototype.unbind = function () {
  24588. this.onUnBindObservable.notifyObservers(this);
  24589. if (this.disableDepthWrite) {
  24590. var engine = this._scene.getEngine();
  24591. engine.setDepthWrite(this._cachedDepthWriteState);
  24592. }
  24593. };
  24594. Material.prototype.clone = function (name) {
  24595. return null;
  24596. };
  24597. Material.prototype.getBindedMeshes = function () {
  24598. var result = new Array();
  24599. for (var index = 0; index < this._scene.meshes.length; index++) {
  24600. var mesh = this._scene.meshes[index];
  24601. if (mesh.material === this) {
  24602. result.push(mesh);
  24603. }
  24604. }
  24605. return result;
  24606. };
  24607. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24608. // Animations
  24609. this.getScene().stopAnimation(this);
  24610. // Remove from scene
  24611. var index = this._scene.materials.indexOf(this);
  24612. if (index >= 0) {
  24613. this._scene.materials.splice(index, 1);
  24614. }
  24615. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  24616. if (forceDisposeEffect && this._effect) {
  24617. this._scene.getEngine()._releaseEffect(this._effect);
  24618. this._effect = null;
  24619. }
  24620. // Remove from meshes
  24621. for (index = 0; index < this._scene.meshes.length; index++) {
  24622. var mesh = this._scene.meshes[index];
  24623. if (mesh.material === this) {
  24624. mesh.material = null;
  24625. }
  24626. }
  24627. // Callback
  24628. this.onDisposeObservable.notifyObservers(this);
  24629. this.onDisposeObservable.clear();
  24630. this.onBindObservable.clear();
  24631. };
  24632. Material.prototype.serialize = function () {
  24633. return BABYLON.SerializationHelper.Serialize(this);
  24634. };
  24635. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  24636. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  24637. multiMaterial.id = parsedMultiMaterial.id;
  24638. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  24639. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  24640. var subMatId = parsedMultiMaterial.materials[matIndex];
  24641. if (subMatId) {
  24642. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  24643. }
  24644. else {
  24645. multiMaterial.subMaterials.push(null);
  24646. }
  24647. }
  24648. return multiMaterial;
  24649. };
  24650. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  24651. if (!parsedMaterial.customType) {
  24652. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  24653. }
  24654. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  24655. return materialType.Parse(parsedMaterial, scene, rootUrl);
  24656. ;
  24657. };
  24658. Material._TriangleFillMode = 0;
  24659. Material._WireFrameFillMode = 1;
  24660. Material._PointFillMode = 2;
  24661. Material._ClockWiseSideOrientation = 0;
  24662. Material._CounterClockWiseSideOrientation = 1;
  24663. __decorate([
  24664. BABYLON.serialize()
  24665. ], Material.prototype, "id", void 0);
  24666. __decorate([
  24667. BABYLON.serialize()
  24668. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  24669. __decorate([
  24670. BABYLON.serialize()
  24671. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  24672. __decorate([
  24673. BABYLON.serialize()
  24674. ], Material.prototype, "state", void 0);
  24675. __decorate([
  24676. BABYLON.serialize()
  24677. ], Material.prototype, "alpha", void 0);
  24678. __decorate([
  24679. BABYLON.serialize()
  24680. ], Material.prototype, "backFaceCulling", void 0);
  24681. __decorate([
  24682. BABYLON.serialize()
  24683. ], Material.prototype, "sideOrientation", void 0);
  24684. __decorate([
  24685. BABYLON.serialize()
  24686. ], Material.prototype, "alphaMode", void 0);
  24687. __decorate([
  24688. BABYLON.serialize()
  24689. ], Material.prototype, "disableDepthWrite", void 0);
  24690. __decorate([
  24691. BABYLON.serialize()
  24692. ], Material.prototype, "fogEnabled", void 0);
  24693. __decorate([
  24694. BABYLON.serialize()
  24695. ], Material.prototype, "pointSize", void 0);
  24696. __decorate([
  24697. BABYLON.serialize()
  24698. ], Material.prototype, "zOffset", void 0);
  24699. __decorate([
  24700. BABYLON.serialize()
  24701. ], Material.prototype, "wireframe", null);
  24702. __decorate([
  24703. BABYLON.serialize()
  24704. ], Material.prototype, "pointsCloud", null);
  24705. __decorate([
  24706. BABYLON.serialize()
  24707. ], Material.prototype, "fillMode", null);
  24708. return Material;
  24709. })();
  24710. BABYLON.Material = Material;
  24711. })(BABYLON || (BABYLON = {}));
  24712. var BABYLON;
  24713. (function (BABYLON) {
  24714. var StandardMaterialDefines = (function (_super) {
  24715. __extends(StandardMaterialDefines, _super);
  24716. function StandardMaterialDefines() {
  24717. _super.call(this);
  24718. this.DIFFUSE = false;
  24719. this.AMBIENT = false;
  24720. this.OPACITY = false;
  24721. this.OPACITYRGB = false;
  24722. this.REFLECTION = false;
  24723. this.EMISSIVE = false;
  24724. this.SPECULAR = false;
  24725. this.BUMP = false;
  24726. this.PARALLAX = false;
  24727. this.PARALLAXOCCLUSION = false;
  24728. this.SPECULAROVERALPHA = false;
  24729. this.CLIPPLANE = false;
  24730. this.ALPHATEST = false;
  24731. this.ALPHAFROMDIFFUSE = false;
  24732. this.POINTSIZE = false;
  24733. this.FOG = false;
  24734. this.SPECULARTERM = false;
  24735. this.DIFFUSEFRESNEL = false;
  24736. this.OPACITYFRESNEL = false;
  24737. this.REFLECTIONFRESNEL = false;
  24738. this.REFRACTIONFRESNEL = false;
  24739. this.EMISSIVEFRESNEL = false;
  24740. this.FRESNEL = false;
  24741. this.NORMAL = false;
  24742. this.UV1 = false;
  24743. this.UV2 = false;
  24744. this.VERTEXCOLOR = false;
  24745. this.VERTEXALPHA = false;
  24746. this.NUM_BONE_INFLUENCERS = 0;
  24747. this.BonesPerMesh = 0;
  24748. this.INSTANCES = false;
  24749. this.GLOSSINESS = false;
  24750. this.ROUGHNESS = false;
  24751. this.EMISSIVEASILLUMINATION = false;
  24752. this.LINKEMISSIVEWITHDIFFUSE = false;
  24753. this.REFLECTIONFRESNELFROMSPECULAR = false;
  24754. this.LIGHTMAP = false;
  24755. this.USELIGHTMAPASSHADOWMAP = false;
  24756. this.REFLECTIONMAP_3D = false;
  24757. this.REFLECTIONMAP_SPHERICAL = false;
  24758. this.REFLECTIONMAP_PLANAR = false;
  24759. this.REFLECTIONMAP_CUBIC = false;
  24760. this.REFLECTIONMAP_PROJECTION = false;
  24761. this.REFLECTIONMAP_SKYBOX = false;
  24762. this.REFLECTIONMAP_EXPLICIT = false;
  24763. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  24764. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  24765. this.INVERTCUBICMAP = false;
  24766. this.LOGARITHMICDEPTH = false;
  24767. this.REFRACTION = false;
  24768. this.REFRACTIONMAP_3D = false;
  24769. this.REFLECTIONOVERALPHA = false;
  24770. this.INVERTNORMALMAPX = false;
  24771. this.INVERTNORMALMAPY = false;
  24772. this.SHADOWFULLFLOAT = false;
  24773. this.CAMERACOLORGRADING = false;
  24774. this.CAMERACOLORCURVES = false;
  24775. this.rebuild();
  24776. }
  24777. return StandardMaterialDefines;
  24778. })(BABYLON.MaterialDefines);
  24779. var StandardMaterial = (function (_super) {
  24780. __extends(StandardMaterial, _super);
  24781. function StandardMaterial(name, scene) {
  24782. var _this = this;
  24783. _super.call(this, name, scene);
  24784. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24785. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  24786. this.specularColor = new BABYLON.Color3(1, 1, 1);
  24787. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  24788. this.specularPower = 64;
  24789. this.useAlphaFromDiffuseTexture = false;
  24790. this.useEmissiveAsIllumination = false;
  24791. this.linkEmissiveWithDiffuse = false;
  24792. this.useReflectionFresnelFromSpecular = false;
  24793. this.useSpecularOverAlpha = false;
  24794. this.useReflectionOverAlpha = false;
  24795. this.disableLighting = false;
  24796. this.useParallax = false;
  24797. this.useParallaxOcclusion = false;
  24798. this.parallaxScaleBias = 0.05;
  24799. this.roughness = 0;
  24800. this.indexOfRefraction = 0.98;
  24801. this.invertRefractionY = true;
  24802. this.useLightmapAsShadowmap = false;
  24803. this.useGlossinessFromSpecularMapAlpha = false;
  24804. this.maxSimultaneousLights = 4;
  24805. /**
  24806. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  24807. */
  24808. this.invertNormalMapX = false;
  24809. /**
  24810. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  24811. */
  24812. this.invertNormalMapY = false;
  24813. /**
  24814. * Color Grading 2D Lookup Texture.
  24815. * This allows special effects like sepia, black and white to sixties rendering style.
  24816. */
  24817. this.cameraColorGradingTexture = null;
  24818. /**
  24819. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  24820. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  24821. * 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;
  24822. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  24823. */
  24824. this.cameraColorCurves = null;
  24825. this._renderTargets = new BABYLON.SmartArray(16);
  24826. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  24827. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  24828. this._defines = new StandardMaterialDefines();
  24829. this._cachedDefines = new StandardMaterialDefines();
  24830. this._cachedDefines.BonesPerMesh = -1;
  24831. this.getRenderTargetTextures = function () {
  24832. _this._renderTargets.reset();
  24833. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  24834. _this._renderTargets.push(_this.reflectionTexture);
  24835. }
  24836. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  24837. _this._renderTargets.push(_this.refractionTexture);
  24838. }
  24839. return _this._renderTargets;
  24840. };
  24841. }
  24842. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  24843. get: function () {
  24844. return this._useLogarithmicDepth;
  24845. },
  24846. set: function (value) {
  24847. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  24848. },
  24849. enumerable: true,
  24850. configurable: true
  24851. });
  24852. StandardMaterial.prototype.needAlphaBlending = function () {
  24853. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  24854. };
  24855. StandardMaterial.prototype.needAlphaTesting = function () {
  24856. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  24857. };
  24858. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  24859. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  24860. };
  24861. StandardMaterial.prototype.getAlphaTestTexture = function () {
  24862. return this.diffuseTexture;
  24863. };
  24864. // Methods
  24865. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  24866. if (!mesh) {
  24867. return true;
  24868. }
  24869. if (this._defines.INSTANCES !== useInstances) {
  24870. return false;
  24871. }
  24872. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  24873. return true;
  24874. }
  24875. return false;
  24876. };
  24877. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  24878. if (this.isFrozen) {
  24879. if (this._wasPreviouslyReady) {
  24880. return true;
  24881. }
  24882. }
  24883. var scene = this.getScene();
  24884. if (!this.checkReadyOnEveryCall) {
  24885. if (this._renderId === scene.getRenderId()) {
  24886. if (this._checkCache(scene, mesh, useInstances)) {
  24887. return true;
  24888. }
  24889. }
  24890. }
  24891. var engine = scene.getEngine();
  24892. var needNormals = false;
  24893. var needUVs = false;
  24894. this._defines.reset();
  24895. // Textures
  24896. if (scene.texturesEnabled) {
  24897. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  24898. if (!this.diffuseTexture.isReady()) {
  24899. return false;
  24900. }
  24901. else {
  24902. needUVs = true;
  24903. this._defines.DIFFUSE = true;
  24904. }
  24905. }
  24906. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  24907. if (!this.ambientTexture.isReady()) {
  24908. return false;
  24909. }
  24910. else {
  24911. needUVs = true;
  24912. this._defines.AMBIENT = true;
  24913. }
  24914. }
  24915. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  24916. if (!this.opacityTexture.isReady()) {
  24917. return false;
  24918. }
  24919. else {
  24920. needUVs = true;
  24921. this._defines.OPACITY = true;
  24922. if (this.opacityTexture.getAlphaFromRGB) {
  24923. this._defines.OPACITYRGB = true;
  24924. }
  24925. }
  24926. }
  24927. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  24928. if (!this.reflectionTexture.isReady()) {
  24929. return false;
  24930. }
  24931. else {
  24932. needNormals = true;
  24933. this._defines.REFLECTION = true;
  24934. if (this.roughness > 0) {
  24935. this._defines.ROUGHNESS = true;
  24936. }
  24937. if (this.useReflectionOverAlpha) {
  24938. this._defines.REFLECTIONOVERALPHA = true;
  24939. }
  24940. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  24941. this._defines.INVERTCUBICMAP = true;
  24942. }
  24943. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  24944. switch (this.reflectionTexture.coordinatesMode) {
  24945. case BABYLON.Texture.CUBIC_MODE:
  24946. case BABYLON.Texture.INVCUBIC_MODE:
  24947. this._defines.REFLECTIONMAP_CUBIC = true;
  24948. break;
  24949. case BABYLON.Texture.EXPLICIT_MODE:
  24950. this._defines.REFLECTIONMAP_EXPLICIT = true;
  24951. break;
  24952. case BABYLON.Texture.PLANAR_MODE:
  24953. this._defines.REFLECTIONMAP_PLANAR = true;
  24954. break;
  24955. case BABYLON.Texture.PROJECTION_MODE:
  24956. this._defines.REFLECTIONMAP_PROJECTION = true;
  24957. break;
  24958. case BABYLON.Texture.SKYBOX_MODE:
  24959. this._defines.REFLECTIONMAP_SKYBOX = true;
  24960. break;
  24961. case BABYLON.Texture.SPHERICAL_MODE:
  24962. this._defines.REFLECTIONMAP_SPHERICAL = true;
  24963. break;
  24964. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  24965. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  24966. break;
  24967. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  24968. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  24969. break;
  24970. }
  24971. }
  24972. }
  24973. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  24974. if (!this.emissiveTexture.isReady()) {
  24975. return false;
  24976. }
  24977. else {
  24978. needUVs = true;
  24979. this._defines.EMISSIVE = true;
  24980. }
  24981. }
  24982. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  24983. if (!this.lightmapTexture.isReady()) {
  24984. return false;
  24985. }
  24986. else {
  24987. needUVs = true;
  24988. this._defines.LIGHTMAP = true;
  24989. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  24990. }
  24991. }
  24992. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  24993. if (!this.specularTexture.isReady()) {
  24994. return false;
  24995. }
  24996. else {
  24997. needUVs = true;
  24998. this._defines.SPECULAR = true;
  24999. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  25000. }
  25001. }
  25002. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  25003. if (!this.bumpTexture.isReady()) {
  25004. return false;
  25005. }
  25006. else {
  25007. needUVs = true;
  25008. this._defines.BUMP = true;
  25009. if (this.useParallax) {
  25010. this._defines.PARALLAX = true;
  25011. if (this.useParallaxOcclusion) {
  25012. this._defines.PARALLAXOCCLUSION = true;
  25013. }
  25014. }
  25015. if (this.invertNormalMapX) {
  25016. this._defines.INVERTNORMALMAPX = true;
  25017. }
  25018. if (this.invertNormalMapY) {
  25019. this._defines.INVERTNORMALMAPY = true;
  25020. }
  25021. }
  25022. }
  25023. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  25024. if (!this.refractionTexture.isReady()) {
  25025. return false;
  25026. }
  25027. else {
  25028. needUVs = true;
  25029. this._defines.REFRACTION = true;
  25030. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  25031. }
  25032. }
  25033. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  25034. if (!this.cameraColorGradingTexture.isReady()) {
  25035. return false;
  25036. }
  25037. else {
  25038. this._defines.CAMERACOLORGRADING = true;
  25039. }
  25040. }
  25041. }
  25042. // Effect
  25043. if (scene.clipPlane) {
  25044. this._defines.CLIPPLANE = true;
  25045. }
  25046. if (engine.getAlphaTesting()) {
  25047. this._defines.ALPHATEST = true;
  25048. }
  25049. if (this._shouldUseAlphaFromDiffuseTexture()) {
  25050. this._defines.ALPHAFROMDIFFUSE = true;
  25051. }
  25052. if (this.useEmissiveAsIllumination) {
  25053. this._defines.EMISSIVEASILLUMINATION = true;
  25054. }
  25055. if (this.linkEmissiveWithDiffuse) {
  25056. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  25057. }
  25058. if (this.useLogarithmicDepth) {
  25059. this._defines.LOGARITHMICDEPTH = true;
  25060. }
  25061. if (this.cameraColorCurves) {
  25062. this._defines.CAMERACOLORCURVES = true;
  25063. }
  25064. // Point size
  25065. if (this.pointsCloud || scene.forcePointsCloud) {
  25066. this._defines.POINTSIZE = true;
  25067. }
  25068. // Fog
  25069. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25070. this._defines.FOG = true;
  25071. }
  25072. if (scene.lightsEnabled && !this.disableLighting) {
  25073. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  25074. }
  25075. if (StandardMaterial.FresnelEnabled) {
  25076. // Fresnel
  25077. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  25078. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  25079. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  25080. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  25081. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25082. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  25083. this._defines.DIFFUSEFRESNEL = true;
  25084. }
  25085. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  25086. this._defines.OPACITYFRESNEL = true;
  25087. }
  25088. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25089. this._defines.REFLECTIONFRESNEL = true;
  25090. if (this.useReflectionFresnelFromSpecular) {
  25091. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  25092. }
  25093. }
  25094. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  25095. this._defines.REFRACTIONFRESNEL = true;
  25096. }
  25097. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  25098. this._defines.EMISSIVEFRESNEL = true;
  25099. }
  25100. needNormals = true;
  25101. this._defines.FRESNEL = true;
  25102. }
  25103. }
  25104. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  25105. this._defines.SPECULAROVERALPHA = true;
  25106. }
  25107. // Attribs
  25108. if (mesh) {
  25109. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25110. this._defines.NORMAL = true;
  25111. }
  25112. if (needUVs) {
  25113. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25114. this._defines.UV1 = true;
  25115. }
  25116. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25117. this._defines.UV2 = true;
  25118. }
  25119. }
  25120. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25121. this._defines.VERTEXCOLOR = true;
  25122. if (mesh.hasVertexAlpha) {
  25123. this._defines.VERTEXALPHA = true;
  25124. }
  25125. }
  25126. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  25127. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  25128. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  25129. }
  25130. // Instances
  25131. if (useInstances) {
  25132. this._defines.INSTANCES = true;
  25133. }
  25134. }
  25135. // Get correct effect
  25136. if (!this._defines.isEqual(this._cachedDefines)) {
  25137. this._defines.cloneTo(this._cachedDefines);
  25138. scene.resetCachedMaterial();
  25139. // Fallbacks
  25140. var fallbacks = new BABYLON.EffectFallbacks();
  25141. if (this._defines.REFLECTION) {
  25142. fallbacks.addFallback(0, "REFLECTION");
  25143. }
  25144. if (this._defines.SPECULAR) {
  25145. fallbacks.addFallback(0, "SPECULAR");
  25146. }
  25147. if (this._defines.BUMP) {
  25148. fallbacks.addFallback(0, "BUMP");
  25149. }
  25150. if (this._defines.PARALLAX) {
  25151. fallbacks.addFallback(1, "PARALLAX");
  25152. }
  25153. if (this._defines.PARALLAXOCCLUSION) {
  25154. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  25155. }
  25156. if (this._defines.SPECULAROVERALPHA) {
  25157. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  25158. }
  25159. if (this._defines.FOG) {
  25160. fallbacks.addFallback(1, "FOG");
  25161. }
  25162. if (this._defines.POINTSIZE) {
  25163. fallbacks.addFallback(0, "POINTSIZE");
  25164. }
  25165. if (this._defines.LOGARITHMICDEPTH) {
  25166. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  25167. }
  25168. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  25169. if (this._defines.SPECULARTERM) {
  25170. fallbacks.addFallback(0, "SPECULARTERM");
  25171. }
  25172. if (this._defines.DIFFUSEFRESNEL) {
  25173. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  25174. }
  25175. if (this._defines.OPACITYFRESNEL) {
  25176. fallbacks.addFallback(2, "OPACITYFRESNEL");
  25177. }
  25178. if (this._defines.REFLECTIONFRESNEL) {
  25179. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  25180. }
  25181. if (this._defines.EMISSIVEFRESNEL) {
  25182. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  25183. }
  25184. if (this._defines.FRESNEL) {
  25185. fallbacks.addFallback(4, "FRESNEL");
  25186. }
  25187. //Attributes
  25188. var attribs = [BABYLON.VertexBuffer.PositionKind];
  25189. if (this._defines.NORMAL) {
  25190. attribs.push(BABYLON.VertexBuffer.NormalKind);
  25191. }
  25192. if (this._defines.UV1) {
  25193. attribs.push(BABYLON.VertexBuffer.UVKind);
  25194. }
  25195. if (this._defines.UV2) {
  25196. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  25197. }
  25198. if (this._defines.VERTEXCOLOR) {
  25199. attribs.push(BABYLON.VertexBuffer.ColorKind);
  25200. }
  25201. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  25202. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  25203. var shaderName = "default";
  25204. var join = this._defines.toString();
  25205. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  25206. "vFogInfos", "vFogColor", "pointSize",
  25207. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  25208. "mBones",
  25209. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  25210. "depthValues",
  25211. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  25212. "logarithmicDepthConstant"
  25213. ];
  25214. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  25215. if (this._defines.CAMERACOLORCURVES) {
  25216. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  25217. }
  25218. if (this._defines.CAMERACOLORGRADING) {
  25219. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  25220. }
  25221. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  25222. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  25223. }
  25224. if (!this._effect.isReady()) {
  25225. return false;
  25226. }
  25227. this._renderId = scene.getRenderId();
  25228. this._wasPreviouslyReady = true;
  25229. if (mesh) {
  25230. if (!mesh._materialDefines) {
  25231. mesh._materialDefines = new StandardMaterialDefines();
  25232. }
  25233. this._defines.cloneTo(mesh._materialDefines);
  25234. }
  25235. return true;
  25236. };
  25237. StandardMaterial.prototype.unbind = function () {
  25238. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  25239. this._effect.setTexture("reflection2DSampler", null);
  25240. }
  25241. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  25242. this._effect.setTexture("refraction2DSampler", null);
  25243. }
  25244. _super.prototype.unbind.call(this);
  25245. };
  25246. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25247. this._effect.setMatrix("world", world);
  25248. };
  25249. StandardMaterial.prototype.bind = function (world, mesh) {
  25250. var scene = this.getScene();
  25251. // Matrices
  25252. this.bindOnlyWorldMatrix(world);
  25253. // Bones
  25254. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  25255. if (scene.getCachedMaterial() !== this) {
  25256. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  25257. if (StandardMaterial.FresnelEnabled) {
  25258. // Fresnel
  25259. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  25260. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  25261. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  25262. }
  25263. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  25264. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  25265. }
  25266. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25267. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  25268. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  25269. }
  25270. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  25271. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  25272. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  25273. }
  25274. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  25275. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  25276. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  25277. }
  25278. }
  25279. // Textures
  25280. if (scene.texturesEnabled) {
  25281. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  25282. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  25283. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  25284. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  25285. }
  25286. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  25287. this._effect.setTexture("ambientSampler", this.ambientTexture);
  25288. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  25289. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  25290. }
  25291. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  25292. this._effect.setTexture("opacitySampler", this.opacityTexture);
  25293. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  25294. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  25295. }
  25296. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  25297. if (this.reflectionTexture.isCube) {
  25298. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  25299. }
  25300. else {
  25301. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  25302. }
  25303. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  25304. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  25305. }
  25306. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  25307. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  25308. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  25309. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  25310. }
  25311. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  25312. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  25313. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  25314. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  25315. }
  25316. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  25317. this._effect.setTexture("specularSampler", this.specularTexture);
  25318. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  25319. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  25320. }
  25321. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  25322. this._effect.setTexture("bumpSampler", this.bumpTexture);
  25323. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  25324. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  25325. }
  25326. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  25327. var depth = 1.0;
  25328. if (this.refractionTexture.isCube) {
  25329. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  25330. }
  25331. else {
  25332. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  25333. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  25334. if (this.refractionTexture.depth) {
  25335. depth = this.refractionTexture.depth;
  25336. }
  25337. }
  25338. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  25339. }
  25340. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  25341. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  25342. }
  25343. }
  25344. // Clip plane
  25345. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  25346. // Point size
  25347. if (this.pointsCloud) {
  25348. this._effect.setFloat("pointSize", this.pointSize);
  25349. }
  25350. // Colors
  25351. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  25352. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  25353. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  25354. if (this._defines.SPECULARTERM) {
  25355. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  25356. }
  25357. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  25358. }
  25359. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  25360. // Diffuse
  25361. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  25362. // Lights
  25363. if (scene.lightsEnabled && !this.disableLighting) {
  25364. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  25365. }
  25366. // View
  25367. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  25368. this._effect.setMatrix("view", scene.getViewMatrix());
  25369. }
  25370. // Fog
  25371. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  25372. // Log. depth
  25373. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  25374. // Color Curves
  25375. if (this.cameraColorCurves) {
  25376. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  25377. }
  25378. }
  25379. _super.prototype.bind.call(this, world, mesh);
  25380. };
  25381. StandardMaterial.prototype.getAnimatables = function () {
  25382. var results = [];
  25383. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  25384. results.push(this.diffuseTexture);
  25385. }
  25386. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  25387. results.push(this.ambientTexture);
  25388. }
  25389. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  25390. results.push(this.opacityTexture);
  25391. }
  25392. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  25393. results.push(this.reflectionTexture);
  25394. }
  25395. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  25396. results.push(this.emissiveTexture);
  25397. }
  25398. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  25399. results.push(this.specularTexture);
  25400. }
  25401. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  25402. results.push(this.bumpTexture);
  25403. }
  25404. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  25405. results.push(this.lightmapTexture);
  25406. }
  25407. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  25408. results.push(this.refractionTexture);
  25409. }
  25410. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  25411. results.push(this.cameraColorGradingTexture);
  25412. }
  25413. return results;
  25414. };
  25415. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25416. if (forceDisposeTextures) {
  25417. if (this.diffuseTexture) {
  25418. this.diffuseTexture.dispose();
  25419. }
  25420. if (this.ambientTexture) {
  25421. this.ambientTexture.dispose();
  25422. }
  25423. if (this.opacityTexture) {
  25424. this.opacityTexture.dispose();
  25425. }
  25426. if (this.reflectionTexture) {
  25427. this.reflectionTexture.dispose();
  25428. }
  25429. if (this.emissiveTexture) {
  25430. this.emissiveTexture.dispose();
  25431. }
  25432. if (this.specularTexture) {
  25433. this.specularTexture.dispose();
  25434. }
  25435. if (this.bumpTexture) {
  25436. this.bumpTexture.dispose();
  25437. }
  25438. if (this.lightmapTexture) {
  25439. this.lightmapTexture.dispose();
  25440. }
  25441. if (this.refractionTexture) {
  25442. this.refractionTexture.dispose();
  25443. }
  25444. if (this.cameraColorGradingTexture) {
  25445. this.cameraColorGradingTexture.dispose();
  25446. }
  25447. }
  25448. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  25449. };
  25450. StandardMaterial.prototype.clone = function (name) {
  25451. var _this = this;
  25452. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  25453. };
  25454. StandardMaterial.prototype.serialize = function () {
  25455. return BABYLON.SerializationHelper.Serialize(this);
  25456. };
  25457. // Statics
  25458. StandardMaterial.Parse = function (source, scene, rootUrl) {
  25459. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  25460. };
  25461. // Flags used to enable or disable a type of texture for all Standard Materials
  25462. StandardMaterial.DiffuseTextureEnabled = true;
  25463. StandardMaterial.AmbientTextureEnabled = true;
  25464. StandardMaterial.OpacityTextureEnabled = true;
  25465. StandardMaterial.ReflectionTextureEnabled = true;
  25466. StandardMaterial.EmissiveTextureEnabled = true;
  25467. StandardMaterial.SpecularTextureEnabled = true;
  25468. StandardMaterial.BumpTextureEnabled = true;
  25469. StandardMaterial.FresnelEnabled = true;
  25470. StandardMaterial.LightmapTextureEnabled = true;
  25471. StandardMaterial.RefractionTextureEnabled = true;
  25472. StandardMaterial.ColorGradingTextureEnabled = true;
  25473. __decorate([
  25474. BABYLON.serializeAsTexture()
  25475. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  25476. __decorate([
  25477. BABYLON.serializeAsTexture()
  25478. ], StandardMaterial.prototype, "ambientTexture", void 0);
  25479. __decorate([
  25480. BABYLON.serializeAsTexture()
  25481. ], StandardMaterial.prototype, "opacityTexture", void 0);
  25482. __decorate([
  25483. BABYLON.serializeAsTexture()
  25484. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  25485. __decorate([
  25486. BABYLON.serializeAsTexture()
  25487. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  25488. __decorate([
  25489. BABYLON.serializeAsTexture()
  25490. ], StandardMaterial.prototype, "specularTexture", void 0);
  25491. __decorate([
  25492. BABYLON.serializeAsTexture()
  25493. ], StandardMaterial.prototype, "bumpTexture", void 0);
  25494. __decorate([
  25495. BABYLON.serializeAsTexture()
  25496. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  25497. __decorate([
  25498. BABYLON.serializeAsTexture()
  25499. ], StandardMaterial.prototype, "refractionTexture", void 0);
  25500. __decorate([
  25501. BABYLON.serializeAsColor3("ambient")
  25502. ], StandardMaterial.prototype, "ambientColor", void 0);
  25503. __decorate([
  25504. BABYLON.serializeAsColor3("diffuse")
  25505. ], StandardMaterial.prototype, "diffuseColor", void 0);
  25506. __decorate([
  25507. BABYLON.serializeAsColor3("specular")
  25508. ], StandardMaterial.prototype, "specularColor", void 0);
  25509. __decorate([
  25510. BABYLON.serializeAsColor3("emissive")
  25511. ], StandardMaterial.prototype, "emissiveColor", void 0);
  25512. __decorate([
  25513. BABYLON.serialize()
  25514. ], StandardMaterial.prototype, "specularPower", void 0);
  25515. __decorate([
  25516. BABYLON.serialize()
  25517. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  25518. __decorate([
  25519. BABYLON.serialize()
  25520. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  25521. __decorate([
  25522. BABYLON.serialize()
  25523. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  25524. __decorate([
  25525. BABYLON.serialize()
  25526. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  25527. __decorate([
  25528. BABYLON.serialize()
  25529. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  25530. __decorate([
  25531. BABYLON.serialize()
  25532. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  25533. __decorate([
  25534. BABYLON.serialize()
  25535. ], StandardMaterial.prototype, "disableLighting", void 0);
  25536. __decorate([
  25537. BABYLON.serialize()
  25538. ], StandardMaterial.prototype, "useParallax", void 0);
  25539. __decorate([
  25540. BABYLON.serialize()
  25541. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  25542. __decorate([
  25543. BABYLON.serialize()
  25544. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  25545. __decorate([
  25546. BABYLON.serialize()
  25547. ], StandardMaterial.prototype, "roughness", void 0);
  25548. __decorate([
  25549. BABYLON.serialize()
  25550. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  25551. __decorate([
  25552. BABYLON.serialize()
  25553. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  25554. __decorate([
  25555. BABYLON.serialize()
  25556. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  25557. __decorate([
  25558. BABYLON.serializeAsFresnelParameters()
  25559. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  25560. __decorate([
  25561. BABYLON.serializeAsFresnelParameters()
  25562. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  25563. __decorate([
  25564. BABYLON.serializeAsFresnelParameters()
  25565. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  25566. __decorate([
  25567. BABYLON.serializeAsFresnelParameters()
  25568. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  25569. __decorate([
  25570. BABYLON.serializeAsFresnelParameters()
  25571. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  25572. __decorate([
  25573. BABYLON.serialize()
  25574. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  25575. __decorate([
  25576. BABYLON.serialize()
  25577. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  25578. __decorate([
  25579. BABYLON.serialize()
  25580. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  25581. __decorate([
  25582. BABYLON.serialize()
  25583. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  25584. __decorate([
  25585. BABYLON.serializeAsTexture()
  25586. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  25587. __decorate([
  25588. BABYLON.serializeAsColorCurves()
  25589. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  25590. __decorate([
  25591. BABYLON.serialize()
  25592. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  25593. return StandardMaterial;
  25594. })(BABYLON.Material);
  25595. BABYLON.StandardMaterial = StandardMaterial;
  25596. })(BABYLON || (BABYLON = {}));
  25597. var BABYLON;
  25598. (function (BABYLON) {
  25599. var MultiMaterial = (function (_super) {
  25600. __extends(MultiMaterial, _super);
  25601. function MultiMaterial(name, scene) {
  25602. _super.call(this, name, scene, true);
  25603. this.subMaterials = new Array();
  25604. scene.multiMaterials.push(this);
  25605. }
  25606. // Properties
  25607. MultiMaterial.prototype.getSubMaterial = function (index) {
  25608. if (index < 0 || index >= this.subMaterials.length) {
  25609. return this.getScene().defaultMaterial;
  25610. }
  25611. return this.subMaterials[index];
  25612. };
  25613. // Methods
  25614. MultiMaterial.prototype.isReady = function (mesh) {
  25615. for (var index = 0; index < this.subMaterials.length; index++) {
  25616. var subMaterial = this.subMaterials[index];
  25617. if (subMaterial) {
  25618. if (!this.subMaterials[index].isReady(mesh)) {
  25619. return false;
  25620. }
  25621. }
  25622. }
  25623. return true;
  25624. };
  25625. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  25626. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  25627. for (var index = 0; index < this.subMaterials.length; index++) {
  25628. var subMaterial = null;
  25629. if (cloneChildren) {
  25630. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  25631. }
  25632. else {
  25633. subMaterial = this.subMaterials[index];
  25634. }
  25635. newMultiMaterial.subMaterials.push(subMaterial);
  25636. }
  25637. return newMultiMaterial;
  25638. };
  25639. MultiMaterial.prototype.serialize = function () {
  25640. var serializationObject = {};
  25641. serializationObject.name = this.name;
  25642. serializationObject.id = this.id;
  25643. serializationObject.tags = BABYLON.Tags.GetTags(this);
  25644. serializationObject.materials = [];
  25645. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  25646. var subMat = this.subMaterials[matIndex];
  25647. if (subMat) {
  25648. serializationObject.materials.push(subMat.id);
  25649. }
  25650. else {
  25651. serializationObject.materials.push(null);
  25652. }
  25653. }
  25654. return serializationObject;
  25655. };
  25656. return MultiMaterial;
  25657. })(BABYLON.Material);
  25658. BABYLON.MultiMaterial = MultiMaterial;
  25659. })(BABYLON || (BABYLON = {}));
  25660. var BABYLON;
  25661. (function (BABYLON) {
  25662. var SceneLoader = (function () {
  25663. function SceneLoader() {
  25664. }
  25665. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  25666. get: function () {
  25667. return 0;
  25668. },
  25669. enumerable: true,
  25670. configurable: true
  25671. });
  25672. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  25673. get: function () {
  25674. return 1;
  25675. },
  25676. enumerable: true,
  25677. configurable: true
  25678. });
  25679. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  25680. get: function () {
  25681. return 2;
  25682. },
  25683. enumerable: true,
  25684. configurable: true
  25685. });
  25686. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  25687. get: function () {
  25688. return 3;
  25689. },
  25690. enumerable: true,
  25691. configurable: true
  25692. });
  25693. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  25694. get: function () {
  25695. return SceneLoader._ForceFullSceneLoadingForIncremental;
  25696. },
  25697. set: function (value) {
  25698. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  25699. },
  25700. enumerable: true,
  25701. configurable: true
  25702. });
  25703. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  25704. get: function () {
  25705. return SceneLoader._ShowLoadingScreen;
  25706. },
  25707. set: function (value) {
  25708. SceneLoader._ShowLoadingScreen = value;
  25709. },
  25710. enumerable: true,
  25711. configurable: true
  25712. });
  25713. Object.defineProperty(SceneLoader, "loggingLevel", {
  25714. get: function () {
  25715. return SceneLoader._loggingLevel;
  25716. },
  25717. set: function (value) {
  25718. SceneLoader._loggingLevel = value;
  25719. },
  25720. enumerable: true,
  25721. configurable: true
  25722. });
  25723. SceneLoader._getPluginForFilename = function (sceneFilename) {
  25724. var dotPosition = sceneFilename.lastIndexOf(".");
  25725. var queryStringPosition = sceneFilename.indexOf("?");
  25726. if (queryStringPosition === -1) {
  25727. queryStringPosition = sceneFilename.length;
  25728. }
  25729. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  25730. for (var index = 0; index < this._registeredPlugins.length; index++) {
  25731. var plugin = this._registeredPlugins[index];
  25732. if (plugin.extensions.indexOf(extension) !== -1) {
  25733. return plugin;
  25734. }
  25735. }
  25736. return this._registeredPlugins[0];
  25737. };
  25738. // Public functions
  25739. SceneLoader.GetPluginForExtension = function (extension) {
  25740. for (var index = 0; index < this._registeredPlugins.length; index++) {
  25741. var plugin = this._registeredPlugins[index];
  25742. if (plugin.extensions.indexOf(extension) !== -1) {
  25743. return plugin;
  25744. }
  25745. }
  25746. return null;
  25747. };
  25748. SceneLoader.RegisterPlugin = function (plugin) {
  25749. plugin.extensions = plugin.extensions.toLowerCase();
  25750. SceneLoader._registeredPlugins.push(plugin);
  25751. };
  25752. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  25753. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25754. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25755. return;
  25756. }
  25757. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25758. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25759. return;
  25760. }
  25761. var loadingToken = {};
  25762. scene._addPendingData(loadingToken);
  25763. var manifestChecked = function (success) {
  25764. scene.database = database;
  25765. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  25766. var importMeshFromData = function (data) {
  25767. var meshes = [];
  25768. var particleSystems = [];
  25769. var skeletons = [];
  25770. try {
  25771. if (plugin.importMesh) {
  25772. var syncedPlugin = plugin;
  25773. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  25774. if (onerror) {
  25775. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  25776. }
  25777. scene._removePendingData(loadingToken);
  25778. return;
  25779. }
  25780. if (onsuccess) {
  25781. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  25782. onsuccess(meshes, particleSystems, skeletons);
  25783. scene._removePendingData(loadingToken);
  25784. }
  25785. }
  25786. else {
  25787. var asyncedPlugin = plugin;
  25788. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  25789. if (onsuccess) {
  25790. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  25791. onsuccess(meshes, particleSystems, skeletons);
  25792. scene._removePendingData(loadingToken);
  25793. }
  25794. }, function () {
  25795. if (onerror) {
  25796. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  25797. }
  25798. scene._removePendingData(loadingToken);
  25799. });
  25800. }
  25801. }
  25802. catch (e) {
  25803. if (onerror) {
  25804. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  25805. }
  25806. scene._removePendingData(loadingToken);
  25807. }
  25808. };
  25809. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  25810. // Direct load
  25811. importMeshFromData(sceneFilename.substr(5));
  25812. return;
  25813. }
  25814. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  25815. importMeshFromData(data);
  25816. }, progressCallBack, database);
  25817. };
  25818. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  25819. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  25820. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  25821. }
  25822. else {
  25823. // If the scene is a data stream or offline support is not enabled, it's a direct load
  25824. manifestChecked(true);
  25825. }
  25826. };
  25827. /**
  25828. * Load a scene
  25829. * @param rootUrl a string that defines the root url for scene and resources
  25830. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  25831. * @param engine is the instance of BABYLON.Engine to use to create the scene
  25832. */
  25833. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  25834. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  25835. };
  25836. /**
  25837. * Append a scene
  25838. * @param rootUrl a string that defines the root url for scene and resources
  25839. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  25840. * @param scene is the instance of BABYLON.Scene to append to
  25841. */
  25842. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  25843. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25844. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25845. return;
  25846. }
  25847. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  25848. var database;
  25849. var loadingToken = {};
  25850. scene._addPendingData(loadingToken);
  25851. if (SceneLoader.ShowLoadingScreen) {
  25852. scene.getEngine().displayLoadingUI();
  25853. }
  25854. var loadSceneFromData = function (data) {
  25855. scene.database = database;
  25856. if (plugin.load) {
  25857. var syncedPlugin = plugin;
  25858. if (!syncedPlugin.load(scene, data, rootUrl)) {
  25859. if (onerror) {
  25860. onerror(scene);
  25861. }
  25862. scene._removePendingData(loadingToken);
  25863. scene.getEngine().hideLoadingUI();
  25864. return;
  25865. }
  25866. if (onsuccess) {
  25867. onsuccess(scene);
  25868. }
  25869. scene._removePendingData(loadingToken);
  25870. }
  25871. else {
  25872. var asyncedPlugin = plugin;
  25873. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  25874. if (onsuccess) {
  25875. onsuccess(scene);
  25876. }
  25877. }, function () {
  25878. if (onerror) {
  25879. onerror(scene);
  25880. }
  25881. scene._removePendingData(loadingToken);
  25882. scene.getEngine().hideLoadingUI();
  25883. });
  25884. }
  25885. if (SceneLoader.ShowLoadingScreen) {
  25886. scene.executeWhenReady(function () {
  25887. scene.getEngine().hideLoadingUI();
  25888. });
  25889. }
  25890. };
  25891. var manifestChecked = function (success) {
  25892. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  25893. };
  25894. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  25895. // Direct load
  25896. loadSceneFromData(sceneFilename.substr(5));
  25897. return;
  25898. }
  25899. if (rootUrl.indexOf("file:") === -1) {
  25900. if (scene.getEngine().enableOfflineSupport) {
  25901. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  25902. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  25903. }
  25904. else {
  25905. manifestChecked(true);
  25906. }
  25907. }
  25908. else {
  25909. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  25910. }
  25911. };
  25912. // Flags
  25913. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  25914. SceneLoader._ShowLoadingScreen = true;
  25915. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  25916. // Members
  25917. SceneLoader._registeredPlugins = new Array();
  25918. return SceneLoader;
  25919. })();
  25920. BABYLON.SceneLoader = SceneLoader;
  25921. ;
  25922. })(BABYLON || (BABYLON = {}));
  25923. var BABYLON;
  25924. (function (BABYLON) {
  25925. var Internals;
  25926. (function (Internals) {
  25927. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  25928. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  25929. var parsedMaterial = parsedData.materials[index];
  25930. if (parsedMaterial.id === id) {
  25931. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  25932. }
  25933. }
  25934. return null;
  25935. };
  25936. var isDescendantOf = function (mesh, names, hierarchyIds) {
  25937. names = (names instanceof Array) ? names : [names];
  25938. for (var i in names) {
  25939. if (mesh.name === names[i]) {
  25940. hierarchyIds.push(mesh.id);
  25941. return true;
  25942. }
  25943. }
  25944. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  25945. hierarchyIds.push(mesh.id);
  25946. return true;
  25947. }
  25948. return false;
  25949. };
  25950. var logOperation = function (operation, producer) {
  25951. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  25952. };
  25953. BABYLON.SceneLoader.RegisterPlugin({
  25954. extensions: ".babylon",
  25955. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  25956. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  25957. // when SceneLoader.debugLogging = true (default), or exception encountered.
  25958. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  25959. // and avoid problems with multiple concurrent .babylon loads.
  25960. var log = "importMesh has failed JSON parse";
  25961. try {
  25962. var parsedData = JSON.parse(data);
  25963. log = "";
  25964. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  25965. var loadedSkeletonsIds = [];
  25966. var loadedMaterialsIds = [];
  25967. var hierarchyIds = [];
  25968. var index;
  25969. var cache;
  25970. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  25971. var parsedMesh = parsedData.meshes[index];
  25972. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  25973. if (meshesNames instanceof Array) {
  25974. // Remove found mesh name from list.
  25975. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  25976. }
  25977. //Geometry?
  25978. if (parsedMesh.geometryId) {
  25979. //does the file contain geometries?
  25980. if (parsedData.geometries) {
  25981. //find the correct geometry and add it to the scene
  25982. var found = false;
  25983. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  25984. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  25985. return;
  25986. }
  25987. else {
  25988. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  25989. if (parsedGeometryData.id === parsedMesh.geometryId) {
  25990. switch (geometryType) {
  25991. case "boxes":
  25992. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  25993. break;
  25994. case "spheres":
  25995. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  25996. break;
  25997. case "cylinders":
  25998. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  25999. break;
  26000. case "toruses":
  26001. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  26002. break;
  26003. case "grounds":
  26004. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  26005. break;
  26006. case "planes":
  26007. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  26008. break;
  26009. case "torusKnots":
  26010. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  26011. break;
  26012. case "vertexData":
  26013. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  26014. break;
  26015. }
  26016. found = true;
  26017. }
  26018. });
  26019. }
  26020. });
  26021. if (!found) {
  26022. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  26023. }
  26024. }
  26025. }
  26026. // Material ?
  26027. if (parsedMesh.materialId) {
  26028. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  26029. if (!materialFound && parsedData.multiMaterials) {
  26030. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  26031. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  26032. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  26033. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  26034. var subMatId = parsedMultiMaterial.materials[matIndex];
  26035. loadedMaterialsIds.push(subMatId);
  26036. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  26037. log += "\n\tMaterial " + mat.toString(fullDetails);
  26038. }
  26039. loadedMaterialsIds.push(parsedMultiMaterial.id);
  26040. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  26041. materialFound = true;
  26042. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  26043. break;
  26044. }
  26045. }
  26046. }
  26047. if (!materialFound) {
  26048. loadedMaterialsIds.push(parsedMesh.materialId);
  26049. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  26050. if (!mat) {
  26051. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  26052. }
  26053. else {
  26054. log += "\n\tMaterial " + mat.toString(fullDetails);
  26055. }
  26056. }
  26057. }
  26058. // Skeleton ?
  26059. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  26060. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  26061. if (!skeletonAlreadyLoaded) {
  26062. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  26063. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  26064. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  26065. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  26066. skeletons.push(skeleton);
  26067. loadedSkeletonsIds.push(parsedSkeleton.id);
  26068. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  26069. }
  26070. }
  26071. }
  26072. }
  26073. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  26074. meshes.push(mesh);
  26075. log += "\n\tMesh " + mesh.toString(fullDetails);
  26076. }
  26077. }
  26078. // Connecting parents
  26079. var currentMesh;
  26080. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26081. currentMesh = scene.meshes[index];
  26082. if (currentMesh._waitingParentId) {
  26083. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  26084. currentMesh._waitingParentId = undefined;
  26085. }
  26086. }
  26087. // freeze and compute world matrix application
  26088. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26089. currentMesh = scene.meshes[index];
  26090. if (currentMesh._waitingFreezeWorldMatrix) {
  26091. currentMesh.freezeWorldMatrix();
  26092. currentMesh._waitingFreezeWorldMatrix = undefined;
  26093. }
  26094. else {
  26095. currentMesh.computeWorldMatrix(true);
  26096. }
  26097. }
  26098. // Particles
  26099. if (parsedData.particleSystems) {
  26100. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  26101. var parsedParticleSystem = parsedData.particleSystems[index];
  26102. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  26103. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  26104. }
  26105. }
  26106. }
  26107. return true;
  26108. }
  26109. catch (err) {
  26110. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  26111. log = null;
  26112. throw err;
  26113. }
  26114. finally {
  26115. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  26116. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  26117. }
  26118. }
  26119. },
  26120. load: function (scene, data, rootUrl) {
  26121. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  26122. // when SceneLoader.debugLogging = true (default), or exception encountered.
  26123. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  26124. // and avoid problems with multiple concurrent .babylon loads.
  26125. var log = "importScene has failed JSON parse";
  26126. try {
  26127. var parsedData = JSON.parse(data);
  26128. log = "";
  26129. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  26130. // Scene
  26131. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  26132. scene.autoClear = parsedData.autoClear;
  26133. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  26134. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  26135. if (parsedData.gravity) {
  26136. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  26137. }
  26138. // Fog
  26139. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  26140. scene.fogMode = parsedData.fogMode;
  26141. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  26142. scene.fogStart = parsedData.fogStart;
  26143. scene.fogEnd = parsedData.fogEnd;
  26144. scene.fogDensity = parsedData.fogDensity;
  26145. log += "\tFog mode for scene: ";
  26146. switch (scene.fogMode) {
  26147. // getters not compiling, so using hardcoded
  26148. case 1:
  26149. log += "exp\n";
  26150. break;
  26151. case 2:
  26152. log += "exp2\n";
  26153. break;
  26154. case 3:
  26155. log += "linear\n";
  26156. break;
  26157. }
  26158. }
  26159. //Physics
  26160. if (parsedData.physicsEnabled) {
  26161. var physicsPlugin;
  26162. if (parsedData.physicsEngine === "cannon") {
  26163. physicsPlugin = new BABYLON.CannonJSPlugin();
  26164. }
  26165. else if (parsedData.physicsEngine === "oimo") {
  26166. physicsPlugin = new BABYLON.OimoJSPlugin();
  26167. }
  26168. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  26169. //else - default engine, which is currently oimo
  26170. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  26171. scene.enablePhysics(physicsGravity, physicsPlugin);
  26172. }
  26173. //collisions, if defined. otherwise, default is true
  26174. if (parsedData.collisionsEnabled != undefined) {
  26175. scene.collisionsEnabled = parsedData.collisionsEnabled;
  26176. }
  26177. scene.workerCollisions = !!parsedData.workerCollisions;
  26178. var index;
  26179. var cache;
  26180. // Lights
  26181. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  26182. var parsedLight = parsedData.lights[index];
  26183. var light = BABYLON.Light.Parse(parsedLight, scene);
  26184. log += (index === 0 ? "\n\tLights:" : "");
  26185. log += "\n\t\t" + light.toString(fullDetails);
  26186. }
  26187. // Animations
  26188. if (parsedData.animations) {
  26189. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  26190. var parsedAnimation = parsedData.animations[index];
  26191. var animation = BABYLON.Animation.Parse(parsedAnimation);
  26192. scene.animations.push(animation);
  26193. log += (index === 0 ? "\n\tAnimations:" : "");
  26194. log += "\n\t\t" + animation.toString(fullDetails);
  26195. }
  26196. }
  26197. if (parsedData.autoAnimate) {
  26198. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  26199. }
  26200. // Materials
  26201. if (parsedData.materials) {
  26202. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  26203. var parsedMaterial = parsedData.materials[index];
  26204. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  26205. log += (index === 0 ? "\n\tMaterials:" : "");
  26206. log += "\n\t\t" + mat.toString(fullDetails);
  26207. }
  26208. }
  26209. if (parsedData.multiMaterials) {
  26210. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  26211. var parsedMultiMaterial = parsedData.multiMaterials[index];
  26212. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  26213. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  26214. log += "\n\t\t" + mmat.toString(fullDetails);
  26215. }
  26216. }
  26217. // Skeletons
  26218. if (parsedData.skeletons) {
  26219. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  26220. var parsedSkeleton = parsedData.skeletons[index];
  26221. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  26222. log += (index === 0 ? "\n\tSkeletons:" : "");
  26223. log += "\n\t\t" + skeleton.toString(fullDetails);
  26224. }
  26225. }
  26226. // Geometries
  26227. var geometries = parsedData.geometries;
  26228. if (geometries) {
  26229. // Boxes
  26230. var boxes = geometries.boxes;
  26231. if (boxes) {
  26232. for (index = 0, cache = boxes.length; index < cache; index++) {
  26233. var parsedBox = boxes[index];
  26234. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  26235. }
  26236. }
  26237. // Spheres
  26238. var spheres = geometries.spheres;
  26239. if (spheres) {
  26240. for (index = 0, cache = spheres.length; index < cache; index++) {
  26241. var parsedSphere = spheres[index];
  26242. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  26243. }
  26244. }
  26245. // Cylinders
  26246. var cylinders = geometries.cylinders;
  26247. if (cylinders) {
  26248. for (index = 0, cache = cylinders.length; index < cache; index++) {
  26249. var parsedCylinder = cylinders[index];
  26250. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  26251. }
  26252. }
  26253. // Toruses
  26254. var toruses = geometries.toruses;
  26255. if (toruses) {
  26256. for (index = 0, cache = toruses.length; index < cache; index++) {
  26257. var parsedTorus = toruses[index];
  26258. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  26259. }
  26260. }
  26261. // Grounds
  26262. var grounds = geometries.grounds;
  26263. if (grounds) {
  26264. for (index = 0, cache = grounds.length; index < cache; index++) {
  26265. var parsedGround = grounds[index];
  26266. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  26267. }
  26268. }
  26269. // Planes
  26270. var planes = geometries.planes;
  26271. if (planes) {
  26272. for (index = 0, cache = planes.length; index < cache; index++) {
  26273. var parsedPlane = planes[index];
  26274. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  26275. }
  26276. }
  26277. // TorusKnots
  26278. var torusKnots = geometries.torusKnots;
  26279. if (torusKnots) {
  26280. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  26281. var parsedTorusKnot = torusKnots[index];
  26282. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  26283. }
  26284. }
  26285. // VertexData
  26286. var vertexData = geometries.vertexData;
  26287. if (vertexData) {
  26288. for (index = 0, cache = vertexData.length; index < cache; index++) {
  26289. var parsedVertexData = vertexData[index];
  26290. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  26291. }
  26292. }
  26293. }
  26294. // Meshes
  26295. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  26296. var parsedMesh = parsedData.meshes[index];
  26297. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  26298. log += (index === 0 ? "\n\tMeshes:" : "");
  26299. log += "\n\t\t" + mesh.toString(fullDetails);
  26300. }
  26301. // Cameras
  26302. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  26303. var parsedCamera = parsedData.cameras[index];
  26304. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  26305. log += (index === 0 ? "\n\tCameras:" : "");
  26306. log += "\n\t\t" + camera.toString(fullDetails);
  26307. }
  26308. if (parsedData.activeCameraID) {
  26309. scene.setActiveCameraByID(parsedData.activeCameraID);
  26310. }
  26311. // Browsing all the graph to connect the dots
  26312. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  26313. var camera = scene.cameras[index];
  26314. if (camera._waitingParentId) {
  26315. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  26316. camera._waitingParentId = undefined;
  26317. }
  26318. }
  26319. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  26320. var light = scene.lights[index];
  26321. if (light._waitingParentId) {
  26322. light.parent = scene.getLastEntryByID(light._waitingParentId);
  26323. light._waitingParentId = undefined;
  26324. }
  26325. }
  26326. // Sounds
  26327. var loadedSounds = [];
  26328. var loadedSound;
  26329. if (BABYLON.AudioEngine && parsedData.sounds) {
  26330. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  26331. var parsedSound = parsedData.sounds[index];
  26332. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26333. if (!parsedSound.url)
  26334. parsedSound.url = parsedSound.name;
  26335. if (!loadedSounds[parsedSound.url]) {
  26336. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  26337. loadedSounds[parsedSound.url] = loadedSound;
  26338. }
  26339. else {
  26340. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  26341. }
  26342. }
  26343. else {
  26344. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  26345. }
  26346. }
  26347. }
  26348. loadedSounds = [];
  26349. // Connect parents & children and parse actions
  26350. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26351. var mesh = scene.meshes[index];
  26352. if (mesh._waitingParentId) {
  26353. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  26354. mesh._waitingParentId = undefined;
  26355. }
  26356. if (mesh._waitingActions) {
  26357. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  26358. mesh._waitingActions = undefined;
  26359. }
  26360. }
  26361. // freeze world matrix application
  26362. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26363. var currentMesh = scene.meshes[index];
  26364. if (currentMesh._waitingFreezeWorldMatrix) {
  26365. currentMesh.freezeWorldMatrix();
  26366. currentMesh._waitingFreezeWorldMatrix = undefined;
  26367. }
  26368. else {
  26369. currentMesh.computeWorldMatrix(true);
  26370. }
  26371. }
  26372. // Particles Systems
  26373. if (parsedData.particleSystems) {
  26374. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  26375. var parsedParticleSystem = parsedData.particleSystems[index];
  26376. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  26377. }
  26378. }
  26379. // Lens flares
  26380. if (parsedData.lensFlareSystems) {
  26381. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  26382. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  26383. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  26384. }
  26385. }
  26386. // Shadows
  26387. if (parsedData.shadowGenerators) {
  26388. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  26389. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  26390. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  26391. }
  26392. }
  26393. // Actions (scene)
  26394. if (parsedData.actions) {
  26395. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  26396. }
  26397. // Finish
  26398. return true;
  26399. }
  26400. catch (err) {
  26401. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  26402. log = null;
  26403. throw err;
  26404. }
  26405. finally {
  26406. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  26407. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  26408. }
  26409. }
  26410. }
  26411. });
  26412. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26413. })(BABYLON || (BABYLON = {}));
  26414. var BABYLON;
  26415. (function (BABYLON) {
  26416. var SpriteManager = (function () {
  26417. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  26418. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26419. this.name = name;
  26420. this.sprites = new Array();
  26421. this.renderingGroupId = 0;
  26422. this.layerMask = 0x0FFFFFFF;
  26423. this.fogEnabled = true;
  26424. this.isPickable = false;
  26425. /**
  26426. * An event triggered when the manager is disposed.
  26427. * @type {BABYLON.Observable}
  26428. */
  26429. this.onDisposeObservable = new BABYLON.Observable();
  26430. this._vertexBuffers = {};
  26431. this._capacity = capacity;
  26432. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  26433. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26434. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26435. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  26436. if (cellSize.width) {
  26437. this.cellWidth = cellSize.width;
  26438. this.cellHeight = cellSize.height;
  26439. }
  26440. else {
  26441. this.cellWidth = cellSize;
  26442. this.cellHeight = cellSize;
  26443. }
  26444. this._scene = scene;
  26445. this._scene.spriteManagers.push(this);
  26446. var indices = [];
  26447. var index = 0;
  26448. for (var count = 0; count < capacity; count++) {
  26449. indices.push(index);
  26450. indices.push(index + 1);
  26451. indices.push(index + 2);
  26452. indices.push(index);
  26453. indices.push(index + 2);
  26454. indices.push(index + 3);
  26455. index += 4;
  26456. }
  26457. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  26458. // VBO
  26459. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  26460. this._vertexData = new Float32Array(capacity * 16 * 4);
  26461. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  26462. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  26463. var options = this._buffer.createVertexBuffer("options", 4, 4);
  26464. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  26465. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  26466. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  26467. this._vertexBuffers["options"] = options;
  26468. this._vertexBuffers["cellInfo"] = cellInfo;
  26469. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  26470. // Effects
  26471. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  26472. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  26473. }
  26474. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  26475. set: function (callback) {
  26476. if (this._onDisposeObserver) {
  26477. this.onDisposeObservable.remove(this._onDisposeObserver);
  26478. }
  26479. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26480. },
  26481. enumerable: true,
  26482. configurable: true
  26483. });
  26484. Object.defineProperty(SpriteManager.prototype, "texture", {
  26485. get: function () {
  26486. return this._spriteTexture;
  26487. },
  26488. set: function (value) {
  26489. this._spriteTexture = value;
  26490. },
  26491. enumerable: true,
  26492. configurable: true
  26493. });
  26494. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  26495. var arrayOffset = index * 16;
  26496. if (offsetX === 0)
  26497. offsetX = this._epsilon;
  26498. else if (offsetX === 1)
  26499. offsetX = 1 - this._epsilon;
  26500. if (offsetY === 0)
  26501. offsetY = this._epsilon;
  26502. else if (offsetY === 1)
  26503. offsetY = 1 - this._epsilon;
  26504. this._vertexData[arrayOffset] = sprite.position.x;
  26505. this._vertexData[arrayOffset + 1] = sprite.position.y;
  26506. this._vertexData[arrayOffset + 2] = sprite.position.z;
  26507. this._vertexData[arrayOffset + 3] = sprite.angle;
  26508. this._vertexData[arrayOffset + 4] = sprite.width;
  26509. this._vertexData[arrayOffset + 5] = sprite.height;
  26510. this._vertexData[arrayOffset + 6] = offsetX;
  26511. this._vertexData[arrayOffset + 7] = offsetY;
  26512. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  26513. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  26514. var offset = (sprite.cellIndex / rowSize) >> 0;
  26515. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  26516. this._vertexData[arrayOffset + 11] = offset;
  26517. // Color
  26518. this._vertexData[arrayOffset + 12] = sprite.color.r;
  26519. this._vertexData[arrayOffset + 13] = sprite.color.g;
  26520. this._vertexData[arrayOffset + 14] = sprite.color.b;
  26521. this._vertexData[arrayOffset + 15] = sprite.color.a;
  26522. };
  26523. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  26524. var count = Math.min(this._capacity, this.sprites.length);
  26525. var min = BABYLON.Vector3.Zero();
  26526. var max = BABYLON.Vector3.Zero();
  26527. var distance = Number.MAX_VALUE;
  26528. var currentSprite;
  26529. var cameraSpacePosition = BABYLON.Vector3.Zero();
  26530. var cameraView = camera.getViewMatrix();
  26531. for (var index = 0; index < count; index++) {
  26532. var sprite = this.sprites[index];
  26533. if (!sprite) {
  26534. continue;
  26535. }
  26536. if (predicate) {
  26537. if (!predicate(sprite)) {
  26538. continue;
  26539. }
  26540. }
  26541. else if (!sprite.isPickable) {
  26542. continue;
  26543. }
  26544. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  26545. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  26546. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  26547. if (ray.intersectsBoxMinMax(min, max)) {
  26548. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  26549. if (distance > currentDistance) {
  26550. distance = currentDistance;
  26551. currentSprite = sprite;
  26552. if (fastCheck) {
  26553. break;
  26554. }
  26555. }
  26556. }
  26557. }
  26558. if (currentSprite) {
  26559. var result = new BABYLON.PickingInfo();
  26560. result.hit = true;
  26561. result.pickedSprite = currentSprite;
  26562. result.distance = distance;
  26563. return result;
  26564. }
  26565. return null;
  26566. };
  26567. SpriteManager.prototype.render = function () {
  26568. // Check
  26569. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  26570. return;
  26571. var engine = this._scene.getEngine();
  26572. var baseSize = this._spriteTexture.getBaseSize();
  26573. // Sprites
  26574. var deltaTime = engine.getDeltaTime();
  26575. var max = Math.min(this._capacity, this.sprites.length);
  26576. var rowSize = baseSize.width / this.cellWidth;
  26577. var offset = 0;
  26578. for (var index = 0; index < max; index++) {
  26579. var sprite = this.sprites[index];
  26580. if (!sprite) {
  26581. continue;
  26582. }
  26583. sprite._animate(deltaTime);
  26584. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  26585. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  26586. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  26587. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  26588. }
  26589. this._buffer.update(this._vertexData);
  26590. // Render
  26591. var effect = this._effectBase;
  26592. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26593. effect = this._effectFog;
  26594. }
  26595. engine.enableEffect(effect);
  26596. var viewMatrix = this._scene.getViewMatrix();
  26597. effect.setTexture("diffuseSampler", this._spriteTexture);
  26598. effect.setMatrix("view", viewMatrix);
  26599. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  26600. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  26601. // Fog
  26602. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26603. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  26604. effect.setColor3("vFogColor", this._scene.fogColor);
  26605. }
  26606. // VBOs
  26607. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  26608. // Draw order
  26609. engine.setDepthFunctionToLessOrEqual();
  26610. effect.setBool("alphaTest", true);
  26611. engine.setColorWrite(false);
  26612. engine.draw(true, 0, max * 6);
  26613. engine.setColorWrite(true);
  26614. effect.setBool("alphaTest", false);
  26615. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26616. engine.draw(true, 0, max * 6);
  26617. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26618. };
  26619. SpriteManager.prototype.dispose = function () {
  26620. if (this._buffer) {
  26621. this._buffer.dispose();
  26622. this._buffer = null;
  26623. }
  26624. if (this._indexBuffer) {
  26625. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26626. this._indexBuffer = null;
  26627. }
  26628. if (this._spriteTexture) {
  26629. this._spriteTexture.dispose();
  26630. this._spriteTexture = null;
  26631. }
  26632. // Remove from scene
  26633. var index = this._scene.spriteManagers.indexOf(this);
  26634. this._scene.spriteManagers.splice(index, 1);
  26635. // Callback
  26636. this.onDisposeObservable.notifyObservers(this);
  26637. this.onDisposeObservable.clear();
  26638. };
  26639. return SpriteManager;
  26640. })();
  26641. BABYLON.SpriteManager = SpriteManager;
  26642. })(BABYLON || (BABYLON = {}));
  26643. var BABYLON;
  26644. (function (BABYLON) {
  26645. var Sprite = (function () {
  26646. function Sprite(name, manager) {
  26647. this.name = name;
  26648. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26649. this.width = 1.0;
  26650. this.height = 1.0;
  26651. this.angle = 0;
  26652. this.cellIndex = 0;
  26653. this.invertU = 0;
  26654. this.invertV = 0;
  26655. this.animations = new Array();
  26656. this.isPickable = false;
  26657. this._animationStarted = false;
  26658. this._loopAnimation = false;
  26659. this._fromIndex = 0;
  26660. this._toIndex = 0;
  26661. this._delay = 0;
  26662. this._direction = 1;
  26663. this._frameCount = 0;
  26664. this._time = 0;
  26665. this._manager = manager;
  26666. this._manager.sprites.push(this);
  26667. this.position = BABYLON.Vector3.Zero();
  26668. }
  26669. Object.defineProperty(Sprite.prototype, "size", {
  26670. get: function () {
  26671. return this.width;
  26672. },
  26673. set: function (value) {
  26674. this.width = value;
  26675. this.height = value;
  26676. },
  26677. enumerable: true,
  26678. configurable: true
  26679. });
  26680. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  26681. this._fromIndex = from;
  26682. this._toIndex = to;
  26683. this._loopAnimation = loop;
  26684. this._delay = delay;
  26685. this._animationStarted = true;
  26686. this._direction = from < to ? 1 : -1;
  26687. this.cellIndex = from;
  26688. this._time = 0;
  26689. };
  26690. Sprite.prototype.stopAnimation = function () {
  26691. this._animationStarted = false;
  26692. };
  26693. Sprite.prototype._animate = function (deltaTime) {
  26694. if (!this._animationStarted)
  26695. return;
  26696. this._time += deltaTime;
  26697. if (this._time > this._delay) {
  26698. this._time = this._time % this._delay;
  26699. this.cellIndex += this._direction;
  26700. if (this.cellIndex == this._toIndex) {
  26701. if (this._loopAnimation) {
  26702. this.cellIndex = this._fromIndex;
  26703. }
  26704. else {
  26705. this._animationStarted = false;
  26706. if (this.disposeWhenFinishedAnimating) {
  26707. this.dispose();
  26708. }
  26709. }
  26710. }
  26711. }
  26712. };
  26713. Sprite.prototype.dispose = function () {
  26714. for (var i = 0; i < this._manager.sprites.length; i++) {
  26715. if (this._manager.sprites[i] == this) {
  26716. this._manager.sprites.splice(i, 1);
  26717. }
  26718. }
  26719. };
  26720. return Sprite;
  26721. })();
  26722. BABYLON.Sprite = Sprite;
  26723. })(BABYLON || (BABYLON = {}));
  26724. var BABYLON;
  26725. (function (BABYLON) {
  26726. var Layer = (function () {
  26727. function Layer(name, imgUrl, scene, isBackground, color) {
  26728. this.name = name;
  26729. this.scale = new BABYLON.Vector2(1, 1);
  26730. this.offset = new BABYLON.Vector2(0, 0);
  26731. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  26732. this._vertexBuffers = {};
  26733. // Events
  26734. /**
  26735. * An event triggered when the layer is disposed.
  26736. * @type {BABYLON.Observable}
  26737. */
  26738. this.onDisposeObservable = new BABYLON.Observable();
  26739. /**
  26740. * An event triggered before rendering the scene
  26741. * @type {BABYLON.Observable}
  26742. */
  26743. this.onBeforeRenderObservable = new BABYLON.Observable();
  26744. /**
  26745. * An event triggered after rendering the scene
  26746. * @type {BABYLON.Observable}
  26747. */
  26748. this.onAfterRenderObservable = new BABYLON.Observable();
  26749. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  26750. this.isBackground = isBackground === undefined ? true : isBackground;
  26751. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  26752. this._scene = scene;
  26753. this._scene.layers.push(this);
  26754. var engine = scene.getEngine();
  26755. // VBO
  26756. var vertices = [];
  26757. vertices.push(1, 1);
  26758. vertices.push(-1, 1);
  26759. vertices.push(-1, -1);
  26760. vertices.push(1, -1);
  26761. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  26762. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  26763. // Indices
  26764. var indices = [];
  26765. indices.push(0);
  26766. indices.push(1);
  26767. indices.push(2);
  26768. indices.push(0);
  26769. indices.push(2);
  26770. indices.push(3);
  26771. this._indexBuffer = engine.createIndexBuffer(indices);
  26772. // Effects
  26773. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  26774. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  26775. }
  26776. Object.defineProperty(Layer.prototype, "onDispose", {
  26777. set: function (callback) {
  26778. if (this._onDisposeObserver) {
  26779. this.onDisposeObservable.remove(this._onDisposeObserver);
  26780. }
  26781. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26782. },
  26783. enumerable: true,
  26784. configurable: true
  26785. });
  26786. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  26787. set: function (callback) {
  26788. if (this._onBeforeRenderObserver) {
  26789. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  26790. }
  26791. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  26792. },
  26793. enumerable: true,
  26794. configurable: true
  26795. });
  26796. Object.defineProperty(Layer.prototype, "onAfterRender", {
  26797. set: function (callback) {
  26798. if (this._onAfterRenderObserver) {
  26799. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  26800. }
  26801. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  26802. },
  26803. enumerable: true,
  26804. configurable: true
  26805. });
  26806. Layer.prototype.render = function () {
  26807. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  26808. // Check
  26809. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  26810. return;
  26811. var engine = this._scene.getEngine();
  26812. this.onBeforeRenderObservable.notifyObservers(this);
  26813. // Render
  26814. engine.enableEffect(currentEffect);
  26815. engine.setState(false);
  26816. // Texture
  26817. currentEffect.setTexture("textureSampler", this.texture);
  26818. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  26819. // Color
  26820. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  26821. // Scale / offset
  26822. currentEffect.setVector2("offset", this.offset);
  26823. currentEffect.setVector2("scale", this.scale);
  26824. // VBOs
  26825. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  26826. // Draw order
  26827. if (!this._alphaTestEffect) {
  26828. engine.setAlphaMode(this.alphaBlendingMode);
  26829. engine.draw(true, 0, 6);
  26830. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26831. }
  26832. else {
  26833. engine.draw(true, 0, 6);
  26834. }
  26835. this.onAfterRenderObservable.notifyObservers(this);
  26836. };
  26837. Layer.prototype.dispose = function () {
  26838. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  26839. if (vertexBuffer) {
  26840. vertexBuffer.dispose();
  26841. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  26842. }
  26843. if (this._indexBuffer) {
  26844. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26845. this._indexBuffer = null;
  26846. }
  26847. if (this.texture) {
  26848. this.texture.dispose();
  26849. this.texture = null;
  26850. }
  26851. // Remove from scene
  26852. var index = this._scene.layers.indexOf(this);
  26853. this._scene.layers.splice(index, 1);
  26854. // Callback
  26855. this.onDisposeObservable.notifyObservers(this);
  26856. this.onDisposeObservable.clear();
  26857. this.onAfterRenderObservable.clear();
  26858. this.onBeforeRenderObservable.clear();
  26859. };
  26860. return Layer;
  26861. })();
  26862. BABYLON.Layer = Layer;
  26863. })(BABYLON || (BABYLON = {}));
  26864. var BABYLON;
  26865. (function (BABYLON) {
  26866. var Particle = (function () {
  26867. function Particle() {
  26868. this.position = BABYLON.Vector3.Zero();
  26869. this.direction = BABYLON.Vector3.Zero();
  26870. this.color = new BABYLON.Color4(0, 0, 0, 0);
  26871. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  26872. this.lifeTime = 1.0;
  26873. this.age = 0;
  26874. this.size = 0;
  26875. this.angle = 0;
  26876. this.angularSpeed = 0;
  26877. }
  26878. Particle.prototype.copyTo = function (other) {
  26879. other.position.copyFrom(this.position);
  26880. other.direction.copyFrom(this.direction);
  26881. other.color.copyFrom(this.color);
  26882. other.colorStep.copyFrom(this.colorStep);
  26883. other.lifeTime = this.lifeTime;
  26884. other.age = this.age;
  26885. other.size = this.size;
  26886. other.angle = this.angle;
  26887. other.angularSpeed = this.angularSpeed;
  26888. };
  26889. return Particle;
  26890. })();
  26891. BABYLON.Particle = Particle;
  26892. })(BABYLON || (BABYLON = {}));
  26893. var BABYLON;
  26894. (function (BABYLON) {
  26895. var randomNumber = function (min, max) {
  26896. if (min === max) {
  26897. return (min);
  26898. }
  26899. var random = Math.random();
  26900. return ((random * (max - min)) + min);
  26901. };
  26902. var ParticleSystem = (function () {
  26903. function ParticleSystem(name, capacity, scene, customEffect) {
  26904. var _this = this;
  26905. this.name = name;
  26906. // Members
  26907. this.animations = [];
  26908. this.renderingGroupId = 0;
  26909. this.emitter = null;
  26910. this.emitRate = 10;
  26911. this.manualEmitCount = -1;
  26912. this.updateSpeed = 0.01;
  26913. this.targetStopDuration = 0;
  26914. this.disposeOnStop = false;
  26915. this.minEmitPower = 1;
  26916. this.maxEmitPower = 1;
  26917. this.minLifeTime = 1;
  26918. this.maxLifeTime = 1;
  26919. this.minSize = 1;
  26920. this.maxSize = 1;
  26921. this.minAngularSpeed = 0;
  26922. this.maxAngularSpeed = 0;
  26923. this.layerMask = 0x0FFFFFFF;
  26924. /**
  26925. * An event triggered when the system is disposed.
  26926. * @type {BABYLON.Observable}
  26927. */
  26928. this.onDisposeObservable = new BABYLON.Observable();
  26929. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  26930. this.forceDepthWrite = false;
  26931. this.gravity = BABYLON.Vector3.Zero();
  26932. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  26933. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  26934. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  26935. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  26936. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26937. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26938. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  26939. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26940. this.particles = new Array();
  26941. this._stockParticles = new Array();
  26942. this._newPartsExcess = 0;
  26943. this._vertexBuffers = {};
  26944. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  26945. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  26946. this._scaledDirection = BABYLON.Vector3.Zero();
  26947. this._scaledGravity = BABYLON.Vector3.Zero();
  26948. this._currentRenderId = -1;
  26949. this._started = false;
  26950. this._stopped = false;
  26951. this._actualFrame = 0;
  26952. this.id = name;
  26953. this._capacity = capacity;
  26954. this._scene = scene;
  26955. this._customEffect = customEffect;
  26956. scene.particleSystems.push(this);
  26957. var indices = [];
  26958. var index = 0;
  26959. for (var count = 0; count < capacity; count++) {
  26960. indices.push(index);
  26961. indices.push(index + 1);
  26962. indices.push(index + 2);
  26963. indices.push(index);
  26964. indices.push(index + 2);
  26965. indices.push(index + 3);
  26966. index += 4;
  26967. }
  26968. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  26969. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  26970. this._vertexData = new Float32Array(capacity * 11 * 4);
  26971. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  26972. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  26973. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  26974. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  26975. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  26976. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  26977. this._vertexBuffers["options"] = options;
  26978. // Default behaviors
  26979. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  26980. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  26981. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  26982. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  26983. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  26984. };
  26985. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  26986. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  26987. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  26988. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  26989. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  26990. };
  26991. this.updateFunction = function (particles) {
  26992. for (var index = 0; index < particles.length; index++) {
  26993. var particle = particles[index];
  26994. particle.age += _this._scaledUpdateSpeed;
  26995. if (particle.age >= particle.lifeTime) {
  26996. _this.recycleParticle(particle);
  26997. index--;
  26998. continue;
  26999. }
  27000. else {
  27001. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  27002. particle.color.addInPlace(_this._scaledColorStep);
  27003. if (particle.color.a < 0)
  27004. particle.color.a = 0;
  27005. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  27006. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  27007. particle.position.addInPlace(_this._scaledDirection);
  27008. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  27009. particle.direction.addInPlace(_this._scaledGravity);
  27010. }
  27011. }
  27012. };
  27013. }
  27014. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  27015. set: function (callback) {
  27016. if (this._onDisposeObserver) {
  27017. this.onDisposeObservable.remove(this._onDisposeObserver);
  27018. }
  27019. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27020. },
  27021. enumerable: true,
  27022. configurable: true
  27023. });
  27024. ParticleSystem.prototype.recycleParticle = function (particle) {
  27025. var lastParticle = this.particles.pop();
  27026. if (lastParticle !== particle) {
  27027. lastParticle.copyTo(particle);
  27028. this._stockParticles.push(lastParticle);
  27029. }
  27030. };
  27031. ParticleSystem.prototype.getCapacity = function () {
  27032. return this._capacity;
  27033. };
  27034. ParticleSystem.prototype.isAlive = function () {
  27035. return this._alive;
  27036. };
  27037. ParticleSystem.prototype.isStarted = function () {
  27038. return this._started;
  27039. };
  27040. ParticleSystem.prototype.start = function () {
  27041. this._started = true;
  27042. this._stopped = false;
  27043. this._actualFrame = 0;
  27044. };
  27045. ParticleSystem.prototype.stop = function () {
  27046. this._stopped = true;
  27047. };
  27048. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  27049. var offset = index * 11;
  27050. this._vertexData[offset] = particle.position.x;
  27051. this._vertexData[offset + 1] = particle.position.y;
  27052. this._vertexData[offset + 2] = particle.position.z;
  27053. this._vertexData[offset + 3] = particle.color.r;
  27054. this._vertexData[offset + 4] = particle.color.g;
  27055. this._vertexData[offset + 5] = particle.color.b;
  27056. this._vertexData[offset + 6] = particle.color.a;
  27057. this._vertexData[offset + 7] = particle.angle;
  27058. this._vertexData[offset + 8] = particle.size;
  27059. this._vertexData[offset + 9] = offsetX;
  27060. this._vertexData[offset + 10] = offsetY;
  27061. };
  27062. ParticleSystem.prototype._update = function (newParticles) {
  27063. // Update current
  27064. this._alive = this.particles.length > 0;
  27065. this.updateFunction(this.particles);
  27066. // Add new ones
  27067. var worldMatrix;
  27068. if (this.emitter.position) {
  27069. worldMatrix = this.emitter.getWorldMatrix();
  27070. }
  27071. else {
  27072. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  27073. }
  27074. var particle;
  27075. for (var index = 0; index < newParticles; index++) {
  27076. if (this.particles.length === this._capacity) {
  27077. break;
  27078. }
  27079. if (this._stockParticles.length !== 0) {
  27080. particle = this._stockParticles.pop();
  27081. particle.age = 0;
  27082. }
  27083. else {
  27084. particle = new BABYLON.Particle();
  27085. }
  27086. this.particles.push(particle);
  27087. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  27088. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  27089. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  27090. particle.size = randomNumber(this.minSize, this.maxSize);
  27091. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  27092. this.startPositionFunction(worldMatrix, particle.position, particle);
  27093. var step = randomNumber(0, 1.0);
  27094. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  27095. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  27096. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  27097. }
  27098. };
  27099. ParticleSystem.prototype._getEffect = function () {
  27100. if (this._customEffect) {
  27101. return this._customEffect;
  27102. }
  27103. ;
  27104. var defines = [];
  27105. if (this._scene.clipPlane) {
  27106. defines.push("#define CLIPPLANE");
  27107. }
  27108. // Effect
  27109. var join = defines.join("\n");
  27110. if (this._cachedDefines !== join) {
  27111. this._cachedDefines = join;
  27112. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  27113. }
  27114. return this._effect;
  27115. };
  27116. ParticleSystem.prototype.animate = function () {
  27117. if (!this._started)
  27118. return;
  27119. var effect = this._getEffect();
  27120. // Check
  27121. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  27122. return;
  27123. if (this._currentRenderId === this._scene.getRenderId()) {
  27124. return;
  27125. }
  27126. this._currentRenderId = this._scene.getRenderId();
  27127. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  27128. // determine the number of particles we need to create
  27129. var newParticles;
  27130. if (this.manualEmitCount > -1) {
  27131. newParticles = this.manualEmitCount;
  27132. this._newPartsExcess = 0;
  27133. this.manualEmitCount = 0;
  27134. }
  27135. else {
  27136. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  27137. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  27138. }
  27139. if (this._newPartsExcess > 1.0) {
  27140. newParticles += this._newPartsExcess >> 0;
  27141. this._newPartsExcess -= this._newPartsExcess >> 0;
  27142. }
  27143. this._alive = false;
  27144. if (!this._stopped) {
  27145. this._actualFrame += this._scaledUpdateSpeed;
  27146. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  27147. this.stop();
  27148. }
  27149. else {
  27150. newParticles = 0;
  27151. }
  27152. this._update(newParticles);
  27153. // Stopped?
  27154. if (this._stopped) {
  27155. if (!this._alive) {
  27156. this._started = false;
  27157. if (this.disposeOnStop) {
  27158. this._scene._toBeDisposed.push(this);
  27159. }
  27160. }
  27161. }
  27162. // Update VBO
  27163. var offset = 0;
  27164. for (var index = 0; index < this.particles.length; index++) {
  27165. var particle = this.particles[index];
  27166. this._appendParticleVertex(offset++, particle, 0, 0);
  27167. this._appendParticleVertex(offset++, particle, 1, 0);
  27168. this._appendParticleVertex(offset++, particle, 1, 1);
  27169. this._appendParticleVertex(offset++, particle, 0, 1);
  27170. }
  27171. this._vertexBuffer.update(this._vertexData);
  27172. };
  27173. ParticleSystem.prototype.render = function () {
  27174. var effect = this._getEffect();
  27175. // Check
  27176. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  27177. return 0;
  27178. var engine = this._scene.getEngine();
  27179. // Render
  27180. engine.enableEffect(effect);
  27181. engine.setState(false);
  27182. var viewMatrix = this._scene.getViewMatrix();
  27183. effect.setTexture("diffuseSampler", this.particleTexture);
  27184. effect.setMatrix("view", viewMatrix);
  27185. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  27186. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  27187. if (this._scene.clipPlane) {
  27188. var clipPlane = this._scene.clipPlane;
  27189. var invView = viewMatrix.clone();
  27190. invView.invert();
  27191. effect.setMatrix("invView", invView);
  27192. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  27193. }
  27194. // VBOs
  27195. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27196. // Draw order
  27197. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  27198. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  27199. }
  27200. else {
  27201. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27202. }
  27203. if (this.forceDepthWrite) {
  27204. engine.setDepthWrite(true);
  27205. }
  27206. engine.draw(true, 0, this.particles.length * 6);
  27207. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27208. return this.particles.length;
  27209. };
  27210. ParticleSystem.prototype.dispose = function () {
  27211. if (this._vertexBuffer) {
  27212. this._vertexBuffer.dispose();
  27213. this._vertexBuffer = null;
  27214. }
  27215. if (this._indexBuffer) {
  27216. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27217. this._indexBuffer = null;
  27218. }
  27219. if (this.particleTexture) {
  27220. this.particleTexture.dispose();
  27221. this.particleTexture = null;
  27222. }
  27223. // Remove from scene
  27224. var index = this._scene.particleSystems.indexOf(this);
  27225. this._scene.particleSystems.splice(index, 1);
  27226. // Callback
  27227. this.onDisposeObservable.notifyObservers(this);
  27228. this.onDisposeObservable.clear();
  27229. };
  27230. // Clone
  27231. ParticleSystem.prototype.clone = function (name, newEmitter) {
  27232. var result = new ParticleSystem(name, this._capacity, this._scene);
  27233. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  27234. if (newEmitter === undefined) {
  27235. newEmitter = this.emitter;
  27236. }
  27237. result.emitter = newEmitter;
  27238. if (this.particleTexture) {
  27239. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  27240. }
  27241. result.start();
  27242. return result;
  27243. };
  27244. ParticleSystem.prototype.serialize = function () {
  27245. var serializationObject = {};
  27246. serializationObject.name = this.name;
  27247. serializationObject.id = this.id;
  27248. // Emitter
  27249. if (this.emitter.position) {
  27250. serializationObject.emitterId = this.emitter.id;
  27251. }
  27252. else {
  27253. serializationObject.emitter = this.emitter.asArray();
  27254. }
  27255. serializationObject.capacity = this.getCapacity();
  27256. if (this.particleTexture) {
  27257. serializationObject.textureName = this.particleTexture.name;
  27258. }
  27259. // Animations
  27260. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27261. // Particle system
  27262. serializationObject.minAngularSpeed = this.minAngularSpeed;
  27263. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  27264. serializationObject.minSize = this.minSize;
  27265. serializationObject.maxSize = this.maxSize;
  27266. serializationObject.minEmitPower = this.minEmitPower;
  27267. serializationObject.maxEmitPower = this.maxEmitPower;
  27268. serializationObject.minLifeTime = this.minLifeTime;
  27269. serializationObject.maxLifeTime = this.maxLifeTime;
  27270. serializationObject.emitRate = this.emitRate;
  27271. serializationObject.minEmitBox = this.minEmitBox.asArray();
  27272. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  27273. serializationObject.gravity = this.gravity.asArray();
  27274. serializationObject.direction1 = this.direction1.asArray();
  27275. serializationObject.direction2 = this.direction2.asArray();
  27276. serializationObject.color1 = this.color1.asArray();
  27277. serializationObject.color2 = this.color2.asArray();
  27278. serializationObject.colorDead = this.colorDead.asArray();
  27279. serializationObject.updateSpeed = this.updateSpeed;
  27280. serializationObject.targetStopDuration = this.targetStopDuration;
  27281. serializationObject.textureMask = this.textureMask.asArray();
  27282. serializationObject.blendMode = this.blendMode;
  27283. return serializationObject;
  27284. };
  27285. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  27286. var name = parsedParticleSystem.name;
  27287. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  27288. if (parsedParticleSystem.id) {
  27289. particleSystem.id = parsedParticleSystem.id;
  27290. }
  27291. // Texture
  27292. if (parsedParticleSystem.textureName) {
  27293. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  27294. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  27295. }
  27296. // Emitter
  27297. if (parsedParticleSystem.emitterId) {
  27298. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  27299. }
  27300. else {
  27301. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  27302. }
  27303. // Animations
  27304. if (parsedParticleSystem.animations) {
  27305. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  27306. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  27307. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27308. }
  27309. }
  27310. if (parsedParticleSystem.autoAnimate) {
  27311. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  27312. }
  27313. // Particle system
  27314. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  27315. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  27316. particleSystem.minSize = parsedParticleSystem.minSize;
  27317. particleSystem.maxSize = parsedParticleSystem.maxSize;
  27318. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  27319. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  27320. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  27321. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  27322. particleSystem.emitRate = parsedParticleSystem.emitRate;
  27323. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  27324. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  27325. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  27326. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  27327. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  27328. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  27329. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  27330. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  27331. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  27332. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  27333. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  27334. particleSystem.blendMode = parsedParticleSystem.blendMode;
  27335. if (!parsedParticleSystem.preventAutoStart) {
  27336. particleSystem.start();
  27337. }
  27338. return particleSystem;
  27339. };
  27340. // Statics
  27341. ParticleSystem.BLENDMODE_ONEONE = 0;
  27342. ParticleSystem.BLENDMODE_STANDARD = 1;
  27343. return ParticleSystem;
  27344. })();
  27345. BABYLON.ParticleSystem = ParticleSystem;
  27346. })(BABYLON || (BABYLON = {}));
  27347. var BABYLON;
  27348. (function (BABYLON) {
  27349. var AnimationRange = (function () {
  27350. function AnimationRange(name, from, to) {
  27351. this.name = name;
  27352. this.from = from;
  27353. this.to = to;
  27354. }
  27355. AnimationRange.prototype.clone = function () {
  27356. return new AnimationRange(this.name, this.from, this.to);
  27357. };
  27358. return AnimationRange;
  27359. })();
  27360. BABYLON.AnimationRange = AnimationRange;
  27361. /**
  27362. * Composed of a frame, and an action function
  27363. */
  27364. var AnimationEvent = (function () {
  27365. function AnimationEvent(frame, action, onlyOnce) {
  27366. this.frame = frame;
  27367. this.action = action;
  27368. this.onlyOnce = onlyOnce;
  27369. this.isDone = false;
  27370. }
  27371. return AnimationEvent;
  27372. })();
  27373. BABYLON.AnimationEvent = AnimationEvent;
  27374. var PathCursor = (function () {
  27375. function PathCursor(path) {
  27376. this.path = path;
  27377. this._onchange = new Array();
  27378. this.value = 0;
  27379. this.animations = new Array();
  27380. }
  27381. PathCursor.prototype.getPoint = function () {
  27382. var point = this.path.getPointAtLengthPosition(this.value);
  27383. return new BABYLON.Vector3(point.x, 0, point.y);
  27384. };
  27385. PathCursor.prototype.moveAhead = function (step) {
  27386. if (step === void 0) { step = 0.002; }
  27387. this.move(step);
  27388. return this;
  27389. };
  27390. PathCursor.prototype.moveBack = function (step) {
  27391. if (step === void 0) { step = 0.002; }
  27392. this.move(-step);
  27393. return this;
  27394. };
  27395. PathCursor.prototype.move = function (step) {
  27396. if (Math.abs(step) > 1) {
  27397. throw "step size should be less than 1.";
  27398. }
  27399. this.value += step;
  27400. this.ensureLimits();
  27401. this.raiseOnChange();
  27402. return this;
  27403. };
  27404. PathCursor.prototype.ensureLimits = function () {
  27405. while (this.value > 1) {
  27406. this.value -= 1;
  27407. }
  27408. while (this.value < 0) {
  27409. this.value += 1;
  27410. }
  27411. return this;
  27412. };
  27413. // used by animation engine
  27414. PathCursor.prototype.markAsDirty = function (propertyName) {
  27415. this.ensureLimits();
  27416. this.raiseOnChange();
  27417. return this;
  27418. };
  27419. PathCursor.prototype.raiseOnChange = function () {
  27420. var _this = this;
  27421. this._onchange.forEach(function (f) { return f(_this); });
  27422. return this;
  27423. };
  27424. PathCursor.prototype.onchange = function (f) {
  27425. this._onchange.push(f);
  27426. return this;
  27427. };
  27428. return PathCursor;
  27429. })();
  27430. BABYLON.PathCursor = PathCursor;
  27431. var Animation = (function () {
  27432. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  27433. this.name = name;
  27434. this.targetProperty = targetProperty;
  27435. this.framePerSecond = framePerSecond;
  27436. this.dataType = dataType;
  27437. this.loopMode = loopMode;
  27438. this.enableBlending = enableBlending;
  27439. this._offsetsCache = {};
  27440. this._highLimitsCache = {};
  27441. this._stopped = false;
  27442. this._blendingFactor = 0;
  27443. // The set of event that will be linked to this animation
  27444. this._events = new Array();
  27445. this.allowMatricesInterpolation = false;
  27446. this.blendingSpeed = 0.01;
  27447. this._ranges = {};
  27448. this.targetPropertyPath = targetProperty.split(".");
  27449. this.dataType = dataType;
  27450. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  27451. }
  27452. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  27453. var dataType = undefined;
  27454. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  27455. dataType = Animation.ANIMATIONTYPE_FLOAT;
  27456. }
  27457. else if (from instanceof BABYLON.Quaternion) {
  27458. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  27459. }
  27460. else if (from instanceof BABYLON.Vector3) {
  27461. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  27462. }
  27463. else if (from instanceof BABYLON.Vector2) {
  27464. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  27465. }
  27466. else if (from instanceof BABYLON.Color3) {
  27467. dataType = Animation.ANIMATIONTYPE_COLOR3;
  27468. }
  27469. else if (from instanceof BABYLON.Size) {
  27470. dataType = Animation.ANIMATIONTYPE_SIZE;
  27471. }
  27472. if (dataType == undefined) {
  27473. return null;
  27474. }
  27475. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  27476. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  27477. animation.setKeys(keys);
  27478. if (easingFunction !== undefined) {
  27479. animation.setEasingFunction(easingFunction);
  27480. }
  27481. return animation;
  27482. };
  27483. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  27484. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  27485. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  27486. };
  27487. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  27488. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  27489. node.animations.push(animation);
  27490. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  27491. };
  27492. // Methods
  27493. /**
  27494. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27495. */
  27496. Animation.prototype.toString = function (fullDetails) {
  27497. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  27498. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  27499. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  27500. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  27501. if (fullDetails) {
  27502. ret += ", Ranges: {";
  27503. var first = true;
  27504. for (var name in this._ranges) {
  27505. if (first) {
  27506. ret += ", ";
  27507. first = false;
  27508. }
  27509. ret += name;
  27510. }
  27511. ret += "}";
  27512. }
  27513. return ret;
  27514. };
  27515. /**
  27516. * Add an event to this animation.
  27517. */
  27518. Animation.prototype.addEvent = function (event) {
  27519. this._events.push(event);
  27520. };
  27521. /**
  27522. * Remove all events found at the given frame
  27523. * @param frame
  27524. */
  27525. Animation.prototype.removeEvents = function (frame) {
  27526. for (var index = 0; index < this._events.length; index++) {
  27527. if (this._events[index].frame === frame) {
  27528. this._events.splice(index, 1);
  27529. index--;
  27530. }
  27531. }
  27532. };
  27533. Animation.prototype.createRange = function (name, from, to) {
  27534. // check name not already in use; could happen for bones after serialized
  27535. if (!this._ranges[name]) {
  27536. this._ranges[name] = new AnimationRange(name, from, to);
  27537. }
  27538. };
  27539. Animation.prototype.deleteRange = function (name, deleteFrames) {
  27540. if (deleteFrames === void 0) { deleteFrames = true; }
  27541. if (this._ranges[name]) {
  27542. if (deleteFrames) {
  27543. var from = this._ranges[name].from;
  27544. var to = this._ranges[name].to;
  27545. // this loop MUST go high to low for multiple splices to work
  27546. for (var key = this._keys.length - 1; key >= 0; key--) {
  27547. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  27548. this._keys.splice(key, 1);
  27549. }
  27550. }
  27551. }
  27552. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  27553. }
  27554. };
  27555. Animation.prototype.getRange = function (name) {
  27556. return this._ranges[name];
  27557. };
  27558. Animation.prototype.reset = function () {
  27559. this._offsetsCache = {};
  27560. this._highLimitsCache = {};
  27561. this.currentFrame = 0;
  27562. this._blendingFactor = 0;
  27563. this._originalBlendValue = null;
  27564. };
  27565. Animation.prototype.isStopped = function () {
  27566. return this._stopped;
  27567. };
  27568. Animation.prototype.getKeys = function () {
  27569. return this._keys;
  27570. };
  27571. Animation.prototype.getHighestFrame = function () {
  27572. var ret = 0;
  27573. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  27574. if (ret < this._keys[key].frame) {
  27575. ret = this._keys[key].frame;
  27576. }
  27577. }
  27578. return ret;
  27579. };
  27580. Animation.prototype.getEasingFunction = function () {
  27581. return this._easingFunction;
  27582. };
  27583. Animation.prototype.setEasingFunction = function (easingFunction) {
  27584. this._easingFunction = easingFunction;
  27585. };
  27586. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  27587. return startValue + (endValue - startValue) * gradient;
  27588. };
  27589. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  27590. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  27591. };
  27592. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  27593. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  27594. };
  27595. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  27596. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  27597. };
  27598. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  27599. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  27600. };
  27601. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  27602. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  27603. };
  27604. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  27605. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  27606. };
  27607. Animation.prototype.clone = function () {
  27608. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  27609. if (this._keys) {
  27610. clone.setKeys(this._keys);
  27611. }
  27612. if (this._ranges) {
  27613. clone._ranges = {};
  27614. for (var name in this._ranges) {
  27615. clone._ranges[name] = this._ranges[name].clone();
  27616. }
  27617. }
  27618. return clone;
  27619. };
  27620. Animation.prototype.setKeys = function (values) {
  27621. this._keys = values.slice(0);
  27622. this._offsetsCache = {};
  27623. this._highLimitsCache = {};
  27624. };
  27625. Animation.prototype._getKeyValue = function (value) {
  27626. if (typeof value === "function") {
  27627. return value();
  27628. }
  27629. return value;
  27630. };
  27631. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  27632. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  27633. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  27634. }
  27635. this.currentFrame = currentFrame;
  27636. // Try to get a hash to find the right key
  27637. 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));
  27638. if (this._keys[startKey].frame >= currentFrame) {
  27639. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  27640. startKey--;
  27641. }
  27642. }
  27643. for (var key = startKey; key < this._keys.length; key++) {
  27644. if (this._keys[key + 1].frame >= currentFrame) {
  27645. var startValue = this._getKeyValue(this._keys[key].value);
  27646. var endValue = this._getKeyValue(this._keys[key + 1].value);
  27647. // gradient : percent of currentFrame between the frame inf and the frame sup
  27648. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  27649. // check for easingFunction and correction of gradient
  27650. if (this._easingFunction != null) {
  27651. gradient = this._easingFunction.ease(gradient);
  27652. }
  27653. switch (this.dataType) {
  27654. // Float
  27655. case Animation.ANIMATIONTYPE_FLOAT:
  27656. switch (loopMode) {
  27657. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27658. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27659. return this.floatInterpolateFunction(startValue, endValue, gradient);
  27660. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27661. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  27662. }
  27663. break;
  27664. // Quaternion
  27665. case Animation.ANIMATIONTYPE_QUATERNION:
  27666. var quaternion = null;
  27667. switch (loopMode) {
  27668. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27669. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27670. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  27671. break;
  27672. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27673. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27674. break;
  27675. }
  27676. return quaternion;
  27677. // Vector3
  27678. case Animation.ANIMATIONTYPE_VECTOR3:
  27679. switch (loopMode) {
  27680. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27681. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27682. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  27683. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27684. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27685. }
  27686. // Vector2
  27687. case Animation.ANIMATIONTYPE_VECTOR2:
  27688. switch (loopMode) {
  27689. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27690. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27691. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  27692. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27693. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27694. }
  27695. // Size
  27696. case Animation.ANIMATIONTYPE_SIZE:
  27697. switch (loopMode) {
  27698. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27699. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27700. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  27701. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27702. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27703. }
  27704. // Color3
  27705. case Animation.ANIMATIONTYPE_COLOR3:
  27706. switch (loopMode) {
  27707. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27708. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27709. return this.color3InterpolateFunction(startValue, endValue, gradient);
  27710. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27711. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27712. }
  27713. // Matrix
  27714. case Animation.ANIMATIONTYPE_MATRIX:
  27715. switch (loopMode) {
  27716. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27717. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27718. if (this.allowMatricesInterpolation) {
  27719. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  27720. }
  27721. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27722. return startValue;
  27723. }
  27724. default:
  27725. break;
  27726. }
  27727. break;
  27728. }
  27729. }
  27730. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  27731. };
  27732. Animation.prototype.setValue = function (currentValue, blend) {
  27733. if (blend === void 0) { blend = false; }
  27734. // Set value
  27735. var path;
  27736. var destination;
  27737. if (this.targetPropertyPath.length > 1) {
  27738. var property = this._target[this.targetPropertyPath[0]];
  27739. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  27740. property = property[this.targetPropertyPath[index]];
  27741. }
  27742. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  27743. destination = property;
  27744. }
  27745. else {
  27746. path = this.targetPropertyPath[0];
  27747. destination = this._target;
  27748. }
  27749. // Blending
  27750. if (this.enableBlending && this._blendingFactor <= 1.0) {
  27751. if (!this._originalBlendValue) {
  27752. if (destination[path].clone) {
  27753. this._originalBlendValue = destination[path].clone();
  27754. }
  27755. else {
  27756. this._originalBlendValue = destination[path];
  27757. }
  27758. }
  27759. if (this._originalBlendValue.prototype) {
  27760. if (this._originalBlendValue.prototype.Lerp) {
  27761. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  27762. }
  27763. else {
  27764. destination[path] = currentValue;
  27765. }
  27766. }
  27767. else if (this._originalBlendValue.m) {
  27768. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  27769. }
  27770. else {
  27771. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  27772. }
  27773. this._blendingFactor += this.blendingSpeed;
  27774. }
  27775. else {
  27776. destination[path] = currentValue;
  27777. }
  27778. if (this._target.markAsDirty) {
  27779. this._target.markAsDirty(this.targetProperty);
  27780. }
  27781. };
  27782. Animation.prototype.goToFrame = function (frame) {
  27783. if (frame < this._keys[0].frame) {
  27784. frame = this._keys[0].frame;
  27785. }
  27786. else if (frame > this._keys[this._keys.length - 1].frame) {
  27787. frame = this._keys[this._keys.length - 1].frame;
  27788. }
  27789. var currentValue = this._interpolate(frame, 0, this.loopMode);
  27790. this.setValue(currentValue);
  27791. };
  27792. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  27793. if (blend === void 0) { blend = false; }
  27794. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  27795. this._stopped = true;
  27796. return false;
  27797. }
  27798. var returnValue = true;
  27799. // Adding a start key at frame 0 if missing
  27800. if (this._keys[0].frame !== 0) {
  27801. var newKey = { frame: 0, value: this._keys[0].value };
  27802. this._keys.splice(0, 0, newKey);
  27803. }
  27804. // Check limits
  27805. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  27806. from = this._keys[0].frame;
  27807. }
  27808. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  27809. to = this._keys[this._keys.length - 1].frame;
  27810. }
  27811. // Compute ratio
  27812. var range = to - from;
  27813. var offsetValue;
  27814. // ratio represents the frame delta between from and to
  27815. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  27816. var highLimitValue = 0;
  27817. if (ratio > range && !loop) {
  27818. returnValue = false;
  27819. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  27820. }
  27821. else {
  27822. // Get max value if required
  27823. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  27824. var keyOffset = to.toString() + from.toString();
  27825. if (!this._offsetsCache[keyOffset]) {
  27826. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  27827. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  27828. switch (this.dataType) {
  27829. // Float
  27830. case Animation.ANIMATIONTYPE_FLOAT:
  27831. this._offsetsCache[keyOffset] = toValue - fromValue;
  27832. break;
  27833. // Quaternion
  27834. case Animation.ANIMATIONTYPE_QUATERNION:
  27835. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27836. break;
  27837. // Vector3
  27838. case Animation.ANIMATIONTYPE_VECTOR3:
  27839. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27840. // Vector2
  27841. case Animation.ANIMATIONTYPE_VECTOR2:
  27842. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27843. // Size
  27844. case Animation.ANIMATIONTYPE_SIZE:
  27845. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27846. // Color3
  27847. case Animation.ANIMATIONTYPE_COLOR3:
  27848. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27849. default:
  27850. break;
  27851. }
  27852. this._highLimitsCache[keyOffset] = toValue;
  27853. }
  27854. highLimitValue = this._highLimitsCache[keyOffset];
  27855. offsetValue = this._offsetsCache[keyOffset];
  27856. }
  27857. }
  27858. if (offsetValue === undefined) {
  27859. switch (this.dataType) {
  27860. // Float
  27861. case Animation.ANIMATIONTYPE_FLOAT:
  27862. offsetValue = 0;
  27863. break;
  27864. // Quaternion
  27865. case Animation.ANIMATIONTYPE_QUATERNION:
  27866. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  27867. break;
  27868. // Vector3
  27869. case Animation.ANIMATIONTYPE_VECTOR3:
  27870. offsetValue = BABYLON.Vector3.Zero();
  27871. break;
  27872. // Vector2
  27873. case Animation.ANIMATIONTYPE_VECTOR2:
  27874. offsetValue = BABYLON.Vector2.Zero();
  27875. break;
  27876. // Size
  27877. case Animation.ANIMATIONTYPE_SIZE:
  27878. offsetValue = BABYLON.Size.Zero();
  27879. break;
  27880. // Color3
  27881. case Animation.ANIMATIONTYPE_COLOR3:
  27882. offsetValue = BABYLON.Color3.Black();
  27883. }
  27884. }
  27885. // Compute value
  27886. var repeatCount = (ratio / range) >> 0;
  27887. var currentFrame = returnValue ? from + ratio % range : to;
  27888. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  27889. // Set value
  27890. this.setValue(currentValue);
  27891. // Check events
  27892. for (var index = 0; index < this._events.length; index++) {
  27893. if (currentFrame >= this._events[index].frame) {
  27894. var event = this._events[index];
  27895. if (!event.isDone) {
  27896. // If event should be done only once, remove it.
  27897. if (event.onlyOnce) {
  27898. this._events.splice(index, 1);
  27899. index--;
  27900. }
  27901. event.isDone = true;
  27902. event.action();
  27903. } // Don't do anything if the event has already be done.
  27904. }
  27905. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  27906. // reset event, the animation is looping
  27907. this._events[index].isDone = false;
  27908. }
  27909. }
  27910. if (!returnValue) {
  27911. this._stopped = true;
  27912. }
  27913. return returnValue;
  27914. };
  27915. Animation.prototype.serialize = function () {
  27916. var serializationObject = {};
  27917. serializationObject.name = this.name;
  27918. serializationObject.property = this.targetProperty;
  27919. serializationObject.framePerSecond = this.framePerSecond;
  27920. serializationObject.dataType = this.dataType;
  27921. serializationObject.loopBehavior = this.loopMode;
  27922. var dataType = this.dataType;
  27923. serializationObject.keys = [];
  27924. var keys = this.getKeys();
  27925. for (var index = 0; index < keys.length; index++) {
  27926. var animationKey = keys[index];
  27927. var key = {};
  27928. key.frame = animationKey.frame;
  27929. switch (dataType) {
  27930. case Animation.ANIMATIONTYPE_FLOAT:
  27931. key.values = [animationKey.value];
  27932. break;
  27933. case Animation.ANIMATIONTYPE_QUATERNION:
  27934. case Animation.ANIMATIONTYPE_MATRIX:
  27935. case Animation.ANIMATIONTYPE_VECTOR3:
  27936. case Animation.ANIMATIONTYPE_COLOR3:
  27937. key.values = animationKey.value.asArray();
  27938. break;
  27939. }
  27940. serializationObject.keys.push(key);
  27941. }
  27942. serializationObject.ranges = [];
  27943. for (var name in this._ranges) {
  27944. var range = {};
  27945. range.name = name;
  27946. range.from = this._ranges[name].from;
  27947. range.to = this._ranges[name].to;
  27948. serializationObject.ranges.push(range);
  27949. }
  27950. return serializationObject;
  27951. };
  27952. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  27953. get: function () {
  27954. return Animation._ANIMATIONTYPE_FLOAT;
  27955. },
  27956. enumerable: true,
  27957. configurable: true
  27958. });
  27959. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  27960. get: function () {
  27961. return Animation._ANIMATIONTYPE_VECTOR3;
  27962. },
  27963. enumerable: true,
  27964. configurable: true
  27965. });
  27966. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  27967. get: function () {
  27968. return Animation._ANIMATIONTYPE_VECTOR2;
  27969. },
  27970. enumerable: true,
  27971. configurable: true
  27972. });
  27973. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  27974. get: function () {
  27975. return Animation._ANIMATIONTYPE_SIZE;
  27976. },
  27977. enumerable: true,
  27978. configurable: true
  27979. });
  27980. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  27981. get: function () {
  27982. return Animation._ANIMATIONTYPE_QUATERNION;
  27983. },
  27984. enumerable: true,
  27985. configurable: true
  27986. });
  27987. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  27988. get: function () {
  27989. return Animation._ANIMATIONTYPE_MATRIX;
  27990. },
  27991. enumerable: true,
  27992. configurable: true
  27993. });
  27994. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  27995. get: function () {
  27996. return Animation._ANIMATIONTYPE_COLOR3;
  27997. },
  27998. enumerable: true,
  27999. configurable: true
  28000. });
  28001. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  28002. get: function () {
  28003. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  28004. },
  28005. enumerable: true,
  28006. configurable: true
  28007. });
  28008. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  28009. get: function () {
  28010. return Animation._ANIMATIONLOOPMODE_CYCLE;
  28011. },
  28012. enumerable: true,
  28013. configurable: true
  28014. });
  28015. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  28016. get: function () {
  28017. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  28018. },
  28019. enumerable: true,
  28020. configurable: true
  28021. });
  28022. Animation.Parse = function (parsedAnimation) {
  28023. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  28024. var dataType = parsedAnimation.dataType;
  28025. var keys = [];
  28026. var data;
  28027. var index;
  28028. for (index = 0; index < parsedAnimation.keys.length; index++) {
  28029. var key = parsedAnimation.keys[index];
  28030. switch (dataType) {
  28031. case Animation.ANIMATIONTYPE_FLOAT:
  28032. data = key.values[0];
  28033. break;
  28034. case Animation.ANIMATIONTYPE_QUATERNION:
  28035. data = BABYLON.Quaternion.FromArray(key.values);
  28036. break;
  28037. case Animation.ANIMATIONTYPE_MATRIX:
  28038. data = BABYLON.Matrix.FromArray(key.values);
  28039. break;
  28040. case Animation.ANIMATIONTYPE_COLOR3:
  28041. data = BABYLON.Color3.FromArray(key.values);
  28042. break;
  28043. case Animation.ANIMATIONTYPE_VECTOR3:
  28044. default:
  28045. data = BABYLON.Vector3.FromArray(key.values);
  28046. break;
  28047. }
  28048. keys.push({
  28049. frame: key.frame,
  28050. value: data
  28051. });
  28052. }
  28053. animation.setKeys(keys);
  28054. if (parsedAnimation.ranges) {
  28055. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  28056. data = parsedAnimation.ranges[index];
  28057. animation.createRange(data.name, data.from, data.to);
  28058. }
  28059. }
  28060. return animation;
  28061. };
  28062. Animation.AppendSerializedAnimations = function (source, destination) {
  28063. if (source.animations) {
  28064. destination.animations = [];
  28065. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  28066. var animation = source.animations[animationIndex];
  28067. destination.animations.push(animation.serialize());
  28068. }
  28069. }
  28070. };
  28071. // Statics
  28072. Animation._ANIMATIONTYPE_FLOAT = 0;
  28073. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  28074. Animation._ANIMATIONTYPE_QUATERNION = 2;
  28075. Animation._ANIMATIONTYPE_MATRIX = 3;
  28076. Animation._ANIMATIONTYPE_COLOR3 = 4;
  28077. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  28078. Animation._ANIMATIONTYPE_SIZE = 6;
  28079. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  28080. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  28081. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  28082. return Animation;
  28083. })();
  28084. BABYLON.Animation = Animation;
  28085. })(BABYLON || (BABYLON = {}));
  28086. var BABYLON;
  28087. (function (BABYLON) {
  28088. var Animatable = (function () {
  28089. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  28090. if (fromFrame === void 0) { fromFrame = 0; }
  28091. if (toFrame === void 0) { toFrame = 100; }
  28092. if (loopAnimation === void 0) { loopAnimation = false; }
  28093. if (speedRatio === void 0) { speedRatio = 1.0; }
  28094. this.target = target;
  28095. this.fromFrame = fromFrame;
  28096. this.toFrame = toFrame;
  28097. this.loopAnimation = loopAnimation;
  28098. this.speedRatio = speedRatio;
  28099. this.onAnimationEnd = onAnimationEnd;
  28100. this._animations = new Array();
  28101. this._paused = false;
  28102. this.animationStarted = false;
  28103. if (animations) {
  28104. this.appendAnimations(target, animations);
  28105. }
  28106. this._scene = scene;
  28107. scene._activeAnimatables.push(this);
  28108. }
  28109. // Methods
  28110. Animatable.prototype.getAnimations = function () {
  28111. return this._animations;
  28112. };
  28113. Animatable.prototype.appendAnimations = function (target, animations) {
  28114. for (var index = 0; index < animations.length; index++) {
  28115. var animation = animations[index];
  28116. animation._target = target;
  28117. this._animations.push(animation);
  28118. }
  28119. };
  28120. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  28121. var animations = this._animations;
  28122. for (var index = 0; index < animations.length; index++) {
  28123. if (animations[index].targetProperty === property) {
  28124. return animations[index];
  28125. }
  28126. }
  28127. return null;
  28128. };
  28129. Animatable.prototype.reset = function () {
  28130. var animations = this._animations;
  28131. for (var index = 0; index < animations.length; index++) {
  28132. animations[index].reset();
  28133. }
  28134. this._localDelayOffset = null;
  28135. this._pausedDelay = null;
  28136. };
  28137. Animatable.prototype.enableBlending = function (blendingSpeed) {
  28138. var animations = this._animations;
  28139. for (var index = 0; index < animations.length; index++) {
  28140. animations[index].enableBlending = true;
  28141. animations[index].blendingSpeed = blendingSpeed;
  28142. }
  28143. };
  28144. Animatable.prototype.disableBlending = function () {
  28145. var animations = this._animations;
  28146. for (var index = 0; index < animations.length; index++) {
  28147. animations[index].enableBlending = false;
  28148. }
  28149. };
  28150. Animatable.prototype.goToFrame = function (frame) {
  28151. var animations = this._animations;
  28152. for (var index = 0; index < animations.length; index++) {
  28153. animations[index].goToFrame(frame);
  28154. }
  28155. };
  28156. Animatable.prototype.pause = function () {
  28157. if (this._paused) {
  28158. return;
  28159. }
  28160. this._paused = true;
  28161. };
  28162. Animatable.prototype.restart = function () {
  28163. this._paused = false;
  28164. };
  28165. Animatable.prototype.stop = function () {
  28166. var index = this._scene._activeAnimatables.indexOf(this);
  28167. if (index > -1) {
  28168. this._scene._activeAnimatables.splice(index, 1);
  28169. var animations = this._animations;
  28170. for (var index = 0; index < animations.length; index++) {
  28171. animations[index].reset();
  28172. }
  28173. if (this.onAnimationEnd) {
  28174. this.onAnimationEnd();
  28175. }
  28176. }
  28177. };
  28178. Animatable.prototype._animate = function (delay) {
  28179. if (this._paused) {
  28180. this.animationStarted = false;
  28181. if (!this._pausedDelay) {
  28182. this._pausedDelay = delay;
  28183. }
  28184. return true;
  28185. }
  28186. if (!this._localDelayOffset) {
  28187. this._localDelayOffset = delay;
  28188. }
  28189. else if (this._pausedDelay) {
  28190. this._localDelayOffset += delay - this._pausedDelay;
  28191. this._pausedDelay = null;
  28192. }
  28193. // Animating
  28194. var running = false;
  28195. var animations = this._animations;
  28196. var index;
  28197. for (index = 0; index < animations.length; index++) {
  28198. var animation = animations[index];
  28199. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  28200. running = running || isRunning;
  28201. }
  28202. this.animationStarted = running;
  28203. if (!running) {
  28204. // Remove from active animatables
  28205. index = this._scene._activeAnimatables.indexOf(this);
  28206. this._scene._activeAnimatables.splice(index, 1);
  28207. }
  28208. if (!running && this.onAnimationEnd) {
  28209. this.onAnimationEnd();
  28210. this.onAnimationEnd = null;
  28211. }
  28212. return running;
  28213. };
  28214. return Animatable;
  28215. })();
  28216. BABYLON.Animatable = Animatable;
  28217. })(BABYLON || (BABYLON = {}));
  28218. var BABYLON;
  28219. (function (BABYLON) {
  28220. var EasingFunction = (function () {
  28221. function EasingFunction() {
  28222. // Properties
  28223. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  28224. }
  28225. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  28226. get: function () {
  28227. return EasingFunction._EASINGMODE_EASEIN;
  28228. },
  28229. enumerable: true,
  28230. configurable: true
  28231. });
  28232. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  28233. get: function () {
  28234. return EasingFunction._EASINGMODE_EASEOUT;
  28235. },
  28236. enumerable: true,
  28237. configurable: true
  28238. });
  28239. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  28240. get: function () {
  28241. return EasingFunction._EASINGMODE_EASEINOUT;
  28242. },
  28243. enumerable: true,
  28244. configurable: true
  28245. });
  28246. EasingFunction.prototype.setEasingMode = function (easingMode) {
  28247. var n = Math.min(Math.max(easingMode, 0), 2);
  28248. this._easingMode = n;
  28249. };
  28250. EasingFunction.prototype.getEasingMode = function () {
  28251. return this._easingMode;
  28252. };
  28253. EasingFunction.prototype.easeInCore = function (gradient) {
  28254. throw new Error('You must implement this method');
  28255. };
  28256. EasingFunction.prototype.ease = function (gradient) {
  28257. switch (this._easingMode) {
  28258. case EasingFunction.EASINGMODE_EASEIN:
  28259. return this.easeInCore(gradient);
  28260. case EasingFunction.EASINGMODE_EASEOUT:
  28261. return (1 - this.easeInCore(1 - gradient));
  28262. }
  28263. if (gradient >= 0.5) {
  28264. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  28265. }
  28266. return (this.easeInCore(gradient * 2) * 0.5);
  28267. };
  28268. //Statics
  28269. EasingFunction._EASINGMODE_EASEIN = 0;
  28270. EasingFunction._EASINGMODE_EASEOUT = 1;
  28271. EasingFunction._EASINGMODE_EASEINOUT = 2;
  28272. return EasingFunction;
  28273. })();
  28274. BABYLON.EasingFunction = EasingFunction;
  28275. var CircleEase = (function (_super) {
  28276. __extends(CircleEase, _super);
  28277. function CircleEase() {
  28278. _super.apply(this, arguments);
  28279. }
  28280. CircleEase.prototype.easeInCore = function (gradient) {
  28281. gradient = Math.max(0, Math.min(1, gradient));
  28282. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  28283. };
  28284. return CircleEase;
  28285. })(EasingFunction);
  28286. BABYLON.CircleEase = CircleEase;
  28287. var BackEase = (function (_super) {
  28288. __extends(BackEase, _super);
  28289. function BackEase(amplitude) {
  28290. if (amplitude === void 0) { amplitude = 1; }
  28291. _super.call(this);
  28292. this.amplitude = amplitude;
  28293. }
  28294. BackEase.prototype.easeInCore = function (gradient) {
  28295. var num = Math.max(0, this.amplitude);
  28296. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  28297. };
  28298. return BackEase;
  28299. })(EasingFunction);
  28300. BABYLON.BackEase = BackEase;
  28301. var BounceEase = (function (_super) {
  28302. __extends(BounceEase, _super);
  28303. function BounceEase(bounces, bounciness) {
  28304. if (bounces === void 0) { bounces = 3; }
  28305. if (bounciness === void 0) { bounciness = 2; }
  28306. _super.call(this);
  28307. this.bounces = bounces;
  28308. this.bounciness = bounciness;
  28309. }
  28310. BounceEase.prototype.easeInCore = function (gradient) {
  28311. var y = Math.max(0.0, this.bounces);
  28312. var bounciness = this.bounciness;
  28313. if (bounciness <= 1.0) {
  28314. bounciness = 1.001;
  28315. }
  28316. var num9 = Math.pow(bounciness, y);
  28317. var num5 = 1.0 - bounciness;
  28318. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  28319. var num15 = gradient * num4;
  28320. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  28321. var num3 = Math.floor(num65);
  28322. var num13 = num3 + 1.0;
  28323. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  28324. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  28325. var num7 = (num8 + num12) * 0.5;
  28326. var num6 = gradient - num7;
  28327. var num2 = num7 - num8;
  28328. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  28329. };
  28330. return BounceEase;
  28331. })(EasingFunction);
  28332. BABYLON.BounceEase = BounceEase;
  28333. var CubicEase = (function (_super) {
  28334. __extends(CubicEase, _super);
  28335. function CubicEase() {
  28336. _super.apply(this, arguments);
  28337. }
  28338. CubicEase.prototype.easeInCore = function (gradient) {
  28339. return (gradient * gradient * gradient);
  28340. };
  28341. return CubicEase;
  28342. })(EasingFunction);
  28343. BABYLON.CubicEase = CubicEase;
  28344. var ElasticEase = (function (_super) {
  28345. __extends(ElasticEase, _super);
  28346. function ElasticEase(oscillations, springiness) {
  28347. if (oscillations === void 0) { oscillations = 3; }
  28348. if (springiness === void 0) { springiness = 3; }
  28349. _super.call(this);
  28350. this.oscillations = oscillations;
  28351. this.springiness = springiness;
  28352. }
  28353. ElasticEase.prototype.easeInCore = function (gradient) {
  28354. var num2;
  28355. var num3 = Math.max(0.0, this.oscillations);
  28356. var num = Math.max(0.0, this.springiness);
  28357. if (num == 0) {
  28358. num2 = gradient;
  28359. }
  28360. else {
  28361. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  28362. }
  28363. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  28364. };
  28365. return ElasticEase;
  28366. })(EasingFunction);
  28367. BABYLON.ElasticEase = ElasticEase;
  28368. var ExponentialEase = (function (_super) {
  28369. __extends(ExponentialEase, _super);
  28370. function ExponentialEase(exponent) {
  28371. if (exponent === void 0) { exponent = 2; }
  28372. _super.call(this);
  28373. this.exponent = exponent;
  28374. }
  28375. ExponentialEase.prototype.easeInCore = function (gradient) {
  28376. if (this.exponent <= 0) {
  28377. return gradient;
  28378. }
  28379. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  28380. };
  28381. return ExponentialEase;
  28382. })(EasingFunction);
  28383. BABYLON.ExponentialEase = ExponentialEase;
  28384. var PowerEase = (function (_super) {
  28385. __extends(PowerEase, _super);
  28386. function PowerEase(power) {
  28387. if (power === void 0) { power = 2; }
  28388. _super.call(this);
  28389. this.power = power;
  28390. }
  28391. PowerEase.prototype.easeInCore = function (gradient) {
  28392. var y = Math.max(0.0, this.power);
  28393. return Math.pow(gradient, y);
  28394. };
  28395. return PowerEase;
  28396. })(EasingFunction);
  28397. BABYLON.PowerEase = PowerEase;
  28398. var QuadraticEase = (function (_super) {
  28399. __extends(QuadraticEase, _super);
  28400. function QuadraticEase() {
  28401. _super.apply(this, arguments);
  28402. }
  28403. QuadraticEase.prototype.easeInCore = function (gradient) {
  28404. return (gradient * gradient);
  28405. };
  28406. return QuadraticEase;
  28407. })(EasingFunction);
  28408. BABYLON.QuadraticEase = QuadraticEase;
  28409. var QuarticEase = (function (_super) {
  28410. __extends(QuarticEase, _super);
  28411. function QuarticEase() {
  28412. _super.apply(this, arguments);
  28413. }
  28414. QuarticEase.prototype.easeInCore = function (gradient) {
  28415. return (gradient * gradient * gradient * gradient);
  28416. };
  28417. return QuarticEase;
  28418. })(EasingFunction);
  28419. BABYLON.QuarticEase = QuarticEase;
  28420. var QuinticEase = (function (_super) {
  28421. __extends(QuinticEase, _super);
  28422. function QuinticEase() {
  28423. _super.apply(this, arguments);
  28424. }
  28425. QuinticEase.prototype.easeInCore = function (gradient) {
  28426. return (gradient * gradient * gradient * gradient * gradient);
  28427. };
  28428. return QuinticEase;
  28429. })(EasingFunction);
  28430. BABYLON.QuinticEase = QuinticEase;
  28431. var SineEase = (function (_super) {
  28432. __extends(SineEase, _super);
  28433. function SineEase() {
  28434. _super.apply(this, arguments);
  28435. }
  28436. SineEase.prototype.easeInCore = function (gradient) {
  28437. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  28438. };
  28439. return SineEase;
  28440. })(EasingFunction);
  28441. BABYLON.SineEase = SineEase;
  28442. var BezierCurveEase = (function (_super) {
  28443. __extends(BezierCurveEase, _super);
  28444. function BezierCurveEase(x1, y1, x2, y2) {
  28445. if (x1 === void 0) { x1 = 0; }
  28446. if (y1 === void 0) { y1 = 0; }
  28447. if (x2 === void 0) { x2 = 1; }
  28448. if (y2 === void 0) { y2 = 1; }
  28449. _super.call(this);
  28450. this.x1 = x1;
  28451. this.y1 = y1;
  28452. this.x2 = x2;
  28453. this.y2 = y2;
  28454. }
  28455. BezierCurveEase.prototype.easeInCore = function (gradient) {
  28456. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  28457. };
  28458. return BezierCurveEase;
  28459. })(EasingFunction);
  28460. BABYLON.BezierCurveEase = BezierCurveEase;
  28461. })(BABYLON || (BABYLON = {}));
  28462. var BABYLON;
  28463. (function (BABYLON) {
  28464. var Bone = (function (_super) {
  28465. __extends(Bone, _super);
  28466. function Bone(name, skeleton, parentBone, matrix, restPose) {
  28467. _super.call(this, name, skeleton.getScene());
  28468. this.name = name;
  28469. this.children = new Array();
  28470. this.animations = new Array();
  28471. this._worldTransform = new BABYLON.Matrix();
  28472. this._absoluteTransform = new BABYLON.Matrix();
  28473. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  28474. this._skeleton = skeleton;
  28475. this._matrix = matrix;
  28476. this._baseMatrix = matrix;
  28477. this._restPose = restPose ? restPose : matrix.clone();
  28478. skeleton.bones.push(this);
  28479. if (parentBone) {
  28480. this._parent = parentBone;
  28481. parentBone.children.push(this);
  28482. }
  28483. else {
  28484. this._parent = null;
  28485. }
  28486. this._updateDifferenceMatrix();
  28487. }
  28488. // Members
  28489. Bone.prototype.getParent = function () {
  28490. return this._parent;
  28491. };
  28492. Bone.prototype.getLocalMatrix = function () {
  28493. return this._matrix;
  28494. };
  28495. Bone.prototype.getBaseMatrix = function () {
  28496. return this._baseMatrix;
  28497. };
  28498. Bone.prototype.getRestPose = function () {
  28499. return this._restPose;
  28500. };
  28501. Bone.prototype.returnToRest = function () {
  28502. this.updateMatrix(this._restPose.clone());
  28503. };
  28504. Bone.prototype.getWorldMatrix = function () {
  28505. return this._worldTransform;
  28506. };
  28507. Bone.prototype.getInvertedAbsoluteTransform = function () {
  28508. return this._invertedAbsoluteTransform;
  28509. };
  28510. Bone.prototype.getAbsoluteTransform = function () {
  28511. return this._absoluteTransform;
  28512. };
  28513. // Methods
  28514. Bone.prototype.updateMatrix = function (matrix) {
  28515. this._baseMatrix = matrix.clone();
  28516. this._matrix = matrix.clone();
  28517. this._skeleton._markAsDirty();
  28518. this._updateDifferenceMatrix();
  28519. };
  28520. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  28521. if (!rootMatrix) {
  28522. rootMatrix = this._baseMatrix;
  28523. }
  28524. if (this._parent) {
  28525. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  28526. }
  28527. else {
  28528. this._absoluteTransform.copyFrom(rootMatrix);
  28529. }
  28530. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  28531. for (var index = 0; index < this.children.length; index++) {
  28532. this.children[index]._updateDifferenceMatrix();
  28533. }
  28534. };
  28535. Bone.prototype.markAsDirty = function () {
  28536. this._currentRenderId++;
  28537. this._skeleton._markAsDirty();
  28538. };
  28539. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  28540. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  28541. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  28542. // all animation may be coming from a library skeleton, so may need to create animation
  28543. if (this.animations.length === 0) {
  28544. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  28545. this.animations[0].setKeys([]);
  28546. }
  28547. // get animation info / verify there is such a range from the source bone
  28548. var sourceRange = source.animations[0].getRange(rangeName);
  28549. if (!sourceRange) {
  28550. return false;
  28551. }
  28552. var from = sourceRange.from;
  28553. var to = sourceRange.to;
  28554. var sourceKeys = source.animations[0].getKeys();
  28555. // rescaling prep
  28556. var sourceBoneLength = source.length;
  28557. var sourceParent = source.getParent();
  28558. var parent = this.getParent();
  28559. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  28560. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  28561. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  28562. var destKeys = this.animations[0].getKeys();
  28563. // loop vars declaration
  28564. var orig;
  28565. var origTranslation;
  28566. var mat;
  28567. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  28568. orig = sourceKeys[key];
  28569. if (orig.frame >= from && orig.frame <= to) {
  28570. if (rescaleAsRequired) {
  28571. mat = orig.value.clone();
  28572. // scale based on parent ratio, when bone has parent
  28573. if (parentScalingReqd) {
  28574. origTranslation = mat.getTranslation();
  28575. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  28576. }
  28577. else if (dimensionsScalingReqd) {
  28578. origTranslation = mat.getTranslation();
  28579. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  28580. }
  28581. else {
  28582. mat = orig.value;
  28583. }
  28584. }
  28585. else {
  28586. mat = orig.value;
  28587. }
  28588. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  28589. }
  28590. }
  28591. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  28592. return true;
  28593. };
  28594. return Bone;
  28595. })(BABYLON.Node);
  28596. BABYLON.Bone = Bone;
  28597. })(BABYLON || (BABYLON = {}));
  28598. var BABYLON;
  28599. (function (BABYLON) {
  28600. var Skeleton = (function () {
  28601. function Skeleton(name, id, scene) {
  28602. this.name = name;
  28603. this.id = id;
  28604. this.bones = new Array();
  28605. this.needInitialSkinMatrix = false;
  28606. this._isDirty = true;
  28607. this._meshesWithPoseMatrix = new Array();
  28608. this._identity = BABYLON.Matrix.Identity();
  28609. this._ranges = {};
  28610. this.bones = [];
  28611. this._scene = scene;
  28612. scene.skeletons.push(this);
  28613. //make sure it will recalculate the matrix next time prepare is called.
  28614. this._isDirty = true;
  28615. }
  28616. // Members
  28617. Skeleton.prototype.getTransformMatrices = function (mesh) {
  28618. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  28619. return mesh._bonesTransformMatrices;
  28620. }
  28621. return this._transformMatrices;
  28622. };
  28623. Skeleton.prototype.getScene = function () {
  28624. return this._scene;
  28625. };
  28626. // Methods
  28627. /**
  28628. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28629. */
  28630. Skeleton.prototype.toString = function (fullDetails) {
  28631. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  28632. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  28633. if (fullDetails) {
  28634. ret += ", Ranges: {";
  28635. var first = true;
  28636. for (var name_1 in this._ranges) {
  28637. if (first) {
  28638. ret += ", ";
  28639. first = false;
  28640. }
  28641. ret += name_1;
  28642. }
  28643. ret += "}";
  28644. }
  28645. return ret;
  28646. };
  28647. /**
  28648. * Get bone's index searching by name
  28649. * @param {string} name is bone's name to search for
  28650. * @return {number} Indice of the bone. Returns -1 if not found
  28651. */
  28652. Skeleton.prototype.getBoneIndexByName = function (name) {
  28653. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  28654. if (this.bones[boneIndex].name === name) {
  28655. return boneIndex;
  28656. }
  28657. }
  28658. return -1;
  28659. };
  28660. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  28661. // check name not already in use
  28662. if (!this._ranges[name]) {
  28663. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  28664. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28665. if (this.bones[i].animations[0]) {
  28666. this.bones[i].animations[0].createRange(name, from, to);
  28667. }
  28668. }
  28669. }
  28670. };
  28671. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  28672. if (deleteFrames === void 0) { deleteFrames = true; }
  28673. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28674. if (this.bones[i].animations[0]) {
  28675. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  28676. }
  28677. }
  28678. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  28679. };
  28680. Skeleton.prototype.getAnimationRange = function (name) {
  28681. return this._ranges[name];
  28682. };
  28683. /**
  28684. * Returns as an Array, all AnimationRanges defined on this skeleton
  28685. */
  28686. Skeleton.prototype.getAnimationRanges = function () {
  28687. var animationRanges = [];
  28688. var name;
  28689. var i = 0;
  28690. for (name in this._ranges) {
  28691. animationRanges[i] = this._ranges[name];
  28692. i++;
  28693. }
  28694. return animationRanges;
  28695. };
  28696. /**
  28697. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  28698. */
  28699. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  28700. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  28701. if (this._ranges[name] || !source.getAnimationRange(name)) {
  28702. return false;
  28703. }
  28704. var ret = true;
  28705. var frameOffset = this._getHighestAnimationFrame() + 1;
  28706. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  28707. var boneDict = {};
  28708. var sourceBones = source.bones;
  28709. var nBones;
  28710. var i;
  28711. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  28712. boneDict[sourceBones[i].name] = sourceBones[i];
  28713. }
  28714. if (this.bones.length !== sourceBones.length) {
  28715. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  28716. ret = false;
  28717. }
  28718. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  28719. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  28720. var boneName = this.bones[i].name;
  28721. var sourceBone = boneDict[boneName];
  28722. if (sourceBone) {
  28723. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  28724. }
  28725. else {
  28726. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  28727. ret = false;
  28728. }
  28729. }
  28730. // do not call createAnimationRange(), since it also is done to bones, which was already done
  28731. var range = source.getAnimationRange(name);
  28732. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  28733. return ret;
  28734. };
  28735. Skeleton.prototype.returnToRest = function () {
  28736. for (var index = 0; index < this.bones.length; index++) {
  28737. this.bones[index].returnToRest();
  28738. }
  28739. };
  28740. Skeleton.prototype._getHighestAnimationFrame = function () {
  28741. var ret = 0;
  28742. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28743. if (this.bones[i].animations[0]) {
  28744. var highest = this.bones[i].animations[0].getHighestFrame();
  28745. if (ret < highest) {
  28746. ret = highest;
  28747. }
  28748. }
  28749. }
  28750. return ret;
  28751. };
  28752. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  28753. var range = this.getAnimationRange(name);
  28754. if (!range) {
  28755. return null;
  28756. }
  28757. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  28758. };
  28759. Skeleton.prototype._markAsDirty = function () {
  28760. this._isDirty = true;
  28761. };
  28762. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  28763. this._meshesWithPoseMatrix.push(mesh);
  28764. };
  28765. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  28766. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  28767. if (index > -1) {
  28768. this._meshesWithPoseMatrix.splice(index, 1);
  28769. }
  28770. };
  28771. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  28772. for (var index = 0; index < this.bones.length; index++) {
  28773. var bone = this.bones[index];
  28774. var parentBone = bone.getParent();
  28775. if (parentBone) {
  28776. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  28777. }
  28778. else {
  28779. if (initialSkinMatrix) {
  28780. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  28781. }
  28782. else {
  28783. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  28784. }
  28785. }
  28786. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  28787. }
  28788. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  28789. };
  28790. Skeleton.prototype.prepare = function () {
  28791. if (!this._isDirty) {
  28792. return;
  28793. }
  28794. if (this.needInitialSkinMatrix) {
  28795. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  28796. var mesh = this._meshesWithPoseMatrix[index];
  28797. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  28798. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  28799. }
  28800. var poseMatrix = mesh.getPoseMatrix();
  28801. // Prepare bones
  28802. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  28803. var bone = this.bones[boneIndex];
  28804. if (!bone.getParent()) {
  28805. var matrix = bone.getBaseMatrix();
  28806. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  28807. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  28808. }
  28809. }
  28810. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  28811. }
  28812. }
  28813. else {
  28814. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  28815. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  28816. }
  28817. this._computeTransformMatrices(this._transformMatrices, null);
  28818. }
  28819. this._isDirty = false;
  28820. this._scene._activeBones.addCount(this.bones.length, false);
  28821. };
  28822. Skeleton.prototype.getAnimatables = function () {
  28823. if (!this._animatables || this._animatables.length !== this.bones.length) {
  28824. this._animatables = [];
  28825. for (var index = 0; index < this.bones.length; index++) {
  28826. this._animatables.push(this.bones[index]);
  28827. }
  28828. }
  28829. return this._animatables;
  28830. };
  28831. Skeleton.prototype.clone = function (name, id) {
  28832. var result = new Skeleton(name, id || name, this._scene);
  28833. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  28834. for (var index = 0; index < this.bones.length; index++) {
  28835. var source = this.bones[index];
  28836. var parentBone = null;
  28837. if (source.getParent()) {
  28838. var parentIndex = this.bones.indexOf(source.getParent());
  28839. parentBone = result.bones[parentIndex];
  28840. }
  28841. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  28842. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  28843. }
  28844. if (this._ranges) {
  28845. result._ranges = {};
  28846. for (var rangeName in this._ranges) {
  28847. result._ranges[rangeName] = this._ranges[rangeName].clone();
  28848. }
  28849. }
  28850. this._isDirty = true;
  28851. return result;
  28852. };
  28853. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  28854. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  28855. this.bones.forEach(function (bone) {
  28856. bone.animations.forEach(function (animation) {
  28857. animation.enableBlending = true;
  28858. animation.blendingSpeed = blendingSpeed;
  28859. });
  28860. });
  28861. };
  28862. Skeleton.prototype.dispose = function () {
  28863. this._meshesWithPoseMatrix = [];
  28864. // Animations
  28865. this.getScene().stopAnimation(this);
  28866. // Remove from scene
  28867. this.getScene().removeSkeleton(this);
  28868. };
  28869. Skeleton.prototype.serialize = function () {
  28870. var serializationObject = {};
  28871. serializationObject.name = this.name;
  28872. serializationObject.id = this.id;
  28873. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  28874. serializationObject.bones = [];
  28875. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  28876. for (var index = 0; index < this.bones.length; index++) {
  28877. var bone = this.bones[index];
  28878. var serializedBone = {
  28879. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  28880. name: bone.name,
  28881. matrix: bone.getLocalMatrix().toArray(),
  28882. rest: bone.getRestPose().toArray()
  28883. };
  28884. serializationObject.bones.push(serializedBone);
  28885. if (bone.length) {
  28886. serializedBone.length = bone.length;
  28887. }
  28888. if (bone.animations && bone.animations.length > 0) {
  28889. serializedBone.animation = bone.animations[0].serialize();
  28890. }
  28891. serializationObject.ranges = [];
  28892. for (var name in this._ranges) {
  28893. var range = {};
  28894. range.name = name;
  28895. range.from = this._ranges[name].from;
  28896. range.to = this._ranges[name].to;
  28897. serializationObject.ranges.push(range);
  28898. }
  28899. }
  28900. return serializationObject;
  28901. };
  28902. Skeleton.Parse = function (parsedSkeleton, scene) {
  28903. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  28904. if (parsedSkeleton.dimensionsAtRest) {
  28905. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  28906. }
  28907. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  28908. var index;
  28909. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  28910. var parsedBone = parsedSkeleton.bones[index];
  28911. var parentBone = null;
  28912. if (parsedBone.parentBoneIndex > -1) {
  28913. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  28914. }
  28915. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  28916. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  28917. if (parsedBone.length) {
  28918. bone.length = parsedBone.length;
  28919. }
  28920. if (parsedBone.animation) {
  28921. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  28922. }
  28923. }
  28924. // placed after bones, so createAnimationRange can cascade down
  28925. if (parsedSkeleton.ranges) {
  28926. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  28927. var data = parsedSkeleton.ranges[index];
  28928. skeleton.createAnimationRange(data.name, data.from, data.to);
  28929. }
  28930. }
  28931. return skeleton;
  28932. };
  28933. return Skeleton;
  28934. })();
  28935. BABYLON.Skeleton = Skeleton;
  28936. })(BABYLON || (BABYLON = {}));
  28937. var BABYLON;
  28938. (function (BABYLON) {
  28939. var PostProcess = (function () {
  28940. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  28941. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  28942. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  28943. this.name = name;
  28944. this.width = -1;
  28945. this.height = -1;
  28946. /*
  28947. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  28948. Can only be used on a single postprocess or on the last one of a chain.
  28949. */
  28950. this.enablePixelPerfectMode = false;
  28951. this._reusable = false;
  28952. this._textures = new BABYLON.SmartArray(2);
  28953. this._currentRenderTextureInd = 0;
  28954. this._scaleRatio = new BABYLON.Vector2(1, 1);
  28955. // Events
  28956. /**
  28957. * An event triggered when the postprocess is activated.
  28958. * @type {BABYLON.Observable}
  28959. */
  28960. this.onActivateObservable = new BABYLON.Observable();
  28961. /**
  28962. * An event triggered when the postprocess changes its size.
  28963. * @type {BABYLON.Observable}
  28964. */
  28965. this.onSizeChangedObservable = new BABYLON.Observable();
  28966. /**
  28967. * An event triggered when the postprocess applies its effect.
  28968. * @type {BABYLON.Observable}
  28969. */
  28970. this.onApplyObservable = new BABYLON.Observable();
  28971. /**
  28972. * An event triggered before rendering the postprocess
  28973. * @type {BABYLON.Observable}
  28974. */
  28975. this.onBeforeRenderObservable = new BABYLON.Observable();
  28976. /**
  28977. * An event triggered after rendering the postprocess
  28978. * @type {BABYLON.Observable}
  28979. */
  28980. this.onAfterRenderObservable = new BABYLON.Observable();
  28981. if (camera != null) {
  28982. this._camera = camera;
  28983. this._scene = camera.getScene();
  28984. camera.attachPostProcess(this);
  28985. this._engine = this._scene.getEngine();
  28986. }
  28987. else {
  28988. this._engine = engine;
  28989. }
  28990. this._options = options;
  28991. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  28992. this._reusable = reusable || false;
  28993. this._textureType = textureType;
  28994. this._samplers = samplers || [];
  28995. this._samplers.push("textureSampler");
  28996. this._fragmentUrl = fragmentUrl;
  28997. this._parameters = parameters || [];
  28998. this._parameters.push("scale");
  28999. this.updateEffect(defines);
  29000. }
  29001. Object.defineProperty(PostProcess.prototype, "onActivate", {
  29002. set: function (callback) {
  29003. if (this._onActivateObserver) {
  29004. this.onActivateObservable.remove(this._onActivateObserver);
  29005. }
  29006. this._onActivateObserver = this.onActivateObservable.add(callback);
  29007. },
  29008. enumerable: true,
  29009. configurable: true
  29010. });
  29011. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  29012. set: function (callback) {
  29013. if (this._onSizeChangedObserver) {
  29014. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  29015. }
  29016. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  29017. },
  29018. enumerable: true,
  29019. configurable: true
  29020. });
  29021. Object.defineProperty(PostProcess.prototype, "onApply", {
  29022. set: function (callback) {
  29023. if (this._onApplyObserver) {
  29024. this.onApplyObservable.remove(this._onApplyObserver);
  29025. }
  29026. this._onApplyObserver = this.onApplyObservable.add(callback);
  29027. },
  29028. enumerable: true,
  29029. configurable: true
  29030. });
  29031. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  29032. set: function (callback) {
  29033. if (this._onBeforeRenderObserver) {
  29034. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  29035. }
  29036. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  29037. },
  29038. enumerable: true,
  29039. configurable: true
  29040. });
  29041. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  29042. set: function (callback) {
  29043. if (this._onAfterRenderObserver) {
  29044. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  29045. }
  29046. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  29047. },
  29048. enumerable: true,
  29049. configurable: true
  29050. });
  29051. PostProcess.prototype.updateEffect = function (defines) {
  29052. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  29053. };
  29054. PostProcess.prototype.isReusable = function () {
  29055. return this._reusable;
  29056. };
  29057. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  29058. PostProcess.prototype.markTextureDirty = function () {
  29059. this.width = -1;
  29060. };
  29061. PostProcess.prototype.activate = function (camera, sourceTexture) {
  29062. camera = camera || this._camera;
  29063. var scene = camera.getScene();
  29064. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  29065. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  29066. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  29067. var desiredWidth = this._options.width || requiredWidth;
  29068. var desiredHeight = this._options.height || requiredHeight;
  29069. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  29070. if (!this._options.width) {
  29071. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  29072. }
  29073. if (!this._options.height) {
  29074. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  29075. }
  29076. }
  29077. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  29078. if (this._textures.length > 0) {
  29079. for (var i = 0; i < this._textures.length; i++) {
  29080. this._engine._releaseTexture(this._textures.data[i]);
  29081. }
  29082. this._textures.reset();
  29083. }
  29084. this.width = desiredWidth;
  29085. this.height = desiredHeight;
  29086. var textureSize = { width: this.width, height: this.height };
  29087. var textureOptions = {
  29088. generateMipMaps: false,
  29089. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  29090. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  29091. samplingMode: this.renderTargetSamplingMode,
  29092. type: this._textureType
  29093. };
  29094. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  29095. if (this._reusable) {
  29096. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  29097. }
  29098. this.onSizeChangedObservable.notifyObservers(this);
  29099. }
  29100. if (this.enablePixelPerfectMode) {
  29101. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  29102. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  29103. }
  29104. else {
  29105. this._scaleRatio.copyFromFloats(1, 1);
  29106. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  29107. }
  29108. this.onActivateObservable.notifyObservers(camera);
  29109. // Clear
  29110. if (this.clearColor) {
  29111. this._engine.clear(this.clearColor, true, true, true);
  29112. }
  29113. else {
  29114. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  29115. }
  29116. if (this._reusable) {
  29117. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  29118. }
  29119. };
  29120. Object.defineProperty(PostProcess.prototype, "isSupported", {
  29121. get: function () {
  29122. return this._effect.isSupported;
  29123. },
  29124. enumerable: true,
  29125. configurable: true
  29126. });
  29127. PostProcess.prototype.apply = function () {
  29128. // Check
  29129. if (!this._effect.isReady())
  29130. return null;
  29131. // States
  29132. this._engine.enableEffect(this._effect);
  29133. this._engine.setState(false);
  29134. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29135. this._engine.setDepthBuffer(false);
  29136. this._engine.setDepthWrite(false);
  29137. // Texture
  29138. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  29139. // Parameters
  29140. this._effect.setVector2("scale", this._scaleRatio);
  29141. this.onApplyObservable.notifyObservers(this._effect);
  29142. return this._effect;
  29143. };
  29144. PostProcess.prototype.dispose = function (camera) {
  29145. camera = camera || this._camera;
  29146. if (this._textures.length > 0) {
  29147. for (var i = 0; i < this._textures.length; i++) {
  29148. this._engine._releaseTexture(this._textures.data[i]);
  29149. }
  29150. this._textures.reset();
  29151. }
  29152. if (!camera) {
  29153. return;
  29154. }
  29155. camera.detachPostProcess(this);
  29156. var index = camera._postProcesses.indexOf(this);
  29157. if (index === 0 && camera._postProcesses.length > 0) {
  29158. this._camera._postProcesses[0].markTextureDirty();
  29159. }
  29160. this.onActivateObservable.clear();
  29161. this.onAfterRenderObservable.clear();
  29162. this.onApplyObservable.clear();
  29163. this.onBeforeRenderObservable.clear();
  29164. this.onSizeChangedObservable.clear();
  29165. };
  29166. return PostProcess;
  29167. })();
  29168. BABYLON.PostProcess = PostProcess;
  29169. })(BABYLON || (BABYLON = {}));
  29170. var BABYLON;
  29171. (function (BABYLON) {
  29172. var PostProcessManager = (function () {
  29173. function PostProcessManager(scene) {
  29174. this._vertexBuffers = {};
  29175. this._scene = scene;
  29176. }
  29177. PostProcessManager.prototype._prepareBuffers = function () {
  29178. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29179. return;
  29180. }
  29181. // VBO
  29182. var vertices = [];
  29183. vertices.push(1, 1);
  29184. vertices.push(-1, 1);
  29185. vertices.push(-1, -1);
  29186. vertices.push(1, -1);
  29187. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29188. // Indices
  29189. var indices = [];
  29190. indices.push(0);
  29191. indices.push(1);
  29192. indices.push(2);
  29193. indices.push(0);
  29194. indices.push(2);
  29195. indices.push(3);
  29196. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  29197. };
  29198. // Methods
  29199. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  29200. var postProcesses = this._scene.activeCamera._postProcesses;
  29201. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29202. return false;
  29203. }
  29204. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  29205. return true;
  29206. };
  29207. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  29208. var engine = this._scene.getEngine();
  29209. for (var index = 0; index < postProcesses.length; index++) {
  29210. if (index < postProcesses.length - 1) {
  29211. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29212. }
  29213. else {
  29214. if (targetTexture) {
  29215. engine.bindFramebuffer(targetTexture);
  29216. }
  29217. else {
  29218. engine.restoreDefaultFramebuffer();
  29219. }
  29220. }
  29221. var pp = postProcesses[index];
  29222. var effect = pp.apply();
  29223. if (effect) {
  29224. pp.onBeforeRenderObservable.notifyObservers(effect);
  29225. // VBOs
  29226. this._prepareBuffers();
  29227. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29228. // Draw order
  29229. engine.draw(true, 0, 6);
  29230. pp.onAfterRenderObservable.notifyObservers(effect);
  29231. }
  29232. }
  29233. // Restore depth buffer
  29234. engine.setDepthBuffer(true);
  29235. engine.setDepthWrite(true);
  29236. };
  29237. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  29238. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29239. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29240. return;
  29241. }
  29242. var engine = this._scene.getEngine();
  29243. for (var index = 0, len = postProcesses.length; index < len; index++) {
  29244. if (index < len - 1) {
  29245. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29246. }
  29247. else {
  29248. if (targetTexture) {
  29249. engine.bindFramebuffer(targetTexture, faceIndex);
  29250. }
  29251. else {
  29252. engine.restoreDefaultFramebuffer();
  29253. }
  29254. }
  29255. if (doNotPresent) {
  29256. break;
  29257. }
  29258. var pp = postProcesses[index];
  29259. var effect = pp.apply();
  29260. if (effect) {
  29261. pp.onBeforeRenderObservable.notifyObservers(effect);
  29262. // VBOs
  29263. this._prepareBuffers();
  29264. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29265. // Draw order
  29266. engine.draw(true, 0, 6);
  29267. pp.onAfterRenderObservable.notifyObservers(effect);
  29268. }
  29269. }
  29270. // Restore depth buffer
  29271. engine.setDepthBuffer(true);
  29272. engine.setDepthWrite(true);
  29273. };
  29274. PostProcessManager.prototype.dispose = function () {
  29275. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29276. if (buffer) {
  29277. buffer.dispose();
  29278. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29279. }
  29280. if (this._indexBuffer) {
  29281. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29282. this._indexBuffer = null;
  29283. }
  29284. };
  29285. return PostProcessManager;
  29286. })();
  29287. BABYLON.PostProcessManager = PostProcessManager;
  29288. })(BABYLON || (BABYLON = {}));
  29289. var BABYLON;
  29290. (function (BABYLON) {
  29291. var PassPostProcess = (function (_super) {
  29292. __extends(PassPostProcess, _super);
  29293. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  29294. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  29295. }
  29296. return PassPostProcess;
  29297. })(BABYLON.PostProcess);
  29298. BABYLON.PassPostProcess = PassPostProcess;
  29299. })(BABYLON || (BABYLON = {}));
  29300. var BABYLON;
  29301. (function (BABYLON) {
  29302. /**
  29303. * This is a holder class for the physics joint created by the physics plugin.
  29304. * It holds a set of functions to control the underlying joint.
  29305. */
  29306. var PhysicsJoint = (function () {
  29307. function PhysicsJoint(type, jointData) {
  29308. this.type = type;
  29309. this.jointData = jointData;
  29310. jointData.nativeParams = jointData.nativeParams || {};
  29311. }
  29312. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  29313. get: function () {
  29314. return this._physicsJoint;
  29315. },
  29316. set: function (newJoint) {
  29317. if (this._physicsJoint) {
  29318. }
  29319. this._physicsJoint = newJoint;
  29320. },
  29321. enumerable: true,
  29322. configurable: true
  29323. });
  29324. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  29325. set: function (physicsPlugin) {
  29326. this._physicsPlugin = physicsPlugin;
  29327. },
  29328. enumerable: true,
  29329. configurable: true
  29330. });
  29331. /**
  29332. * Execute a function that is physics-plugin specific.
  29333. * @param {Function} func the function that will be executed.
  29334. * It accepts two parameters: the physics world and the physics joint.
  29335. */
  29336. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  29337. func(this._physicsPlugin.world, this._physicsJoint);
  29338. };
  29339. //TODO check if the native joints are the same
  29340. //Joint Types
  29341. PhysicsJoint.DistanceJoint = 0;
  29342. PhysicsJoint.HingeJoint = 1;
  29343. PhysicsJoint.BallAndSocketJoint = 2;
  29344. PhysicsJoint.WheelJoint = 3;
  29345. PhysicsJoint.SliderJoint = 4;
  29346. //OIMO
  29347. PhysicsJoint.PrismaticJoint = 5;
  29348. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  29349. PhysicsJoint.UniversalJoint = 6;
  29350. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  29351. //Cannon
  29352. //Similar to a Ball-Joint. Different in params
  29353. PhysicsJoint.PointToPointJoint = 8;
  29354. //Cannon only at the moment
  29355. PhysicsJoint.SpringJoint = 9;
  29356. PhysicsJoint.LockJoint = 10;
  29357. return PhysicsJoint;
  29358. })();
  29359. BABYLON.PhysicsJoint = PhysicsJoint;
  29360. /**
  29361. * A class representing a physics distance joint.
  29362. */
  29363. var DistanceJoint = (function (_super) {
  29364. __extends(DistanceJoint, _super);
  29365. function DistanceJoint(jointData) {
  29366. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  29367. }
  29368. /**
  29369. * Update the predefined distance.
  29370. */
  29371. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  29372. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  29373. };
  29374. return DistanceJoint;
  29375. })(PhysicsJoint);
  29376. BABYLON.DistanceJoint = DistanceJoint;
  29377. var MotorEnabledJoint = (function (_super) {
  29378. __extends(MotorEnabledJoint, _super);
  29379. function MotorEnabledJoint(type, jointData) {
  29380. _super.call(this, type, jointData);
  29381. }
  29382. /**
  29383. * Set the motor values.
  29384. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29385. * @param {number} force the force to apply
  29386. * @param {number} maxForce max force for this motor.
  29387. */
  29388. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  29389. this._physicsPlugin.setMotor(this, force, maxForce);
  29390. };
  29391. /**
  29392. * Set the motor's limits.
  29393. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29394. */
  29395. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  29396. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  29397. };
  29398. return MotorEnabledJoint;
  29399. })(PhysicsJoint);
  29400. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  29401. /**
  29402. * This class represents a single hinge physics joint
  29403. */
  29404. var HingeJoint = (function (_super) {
  29405. __extends(HingeJoint, _super);
  29406. function HingeJoint(jointData) {
  29407. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  29408. }
  29409. /**
  29410. * Set the motor values.
  29411. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29412. * @param {number} force the force to apply
  29413. * @param {number} maxForce max force for this motor.
  29414. */
  29415. HingeJoint.prototype.setMotor = function (force, maxForce) {
  29416. this._physicsPlugin.setMotor(this, force, maxForce);
  29417. };
  29418. /**
  29419. * Set the motor's limits.
  29420. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29421. */
  29422. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  29423. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  29424. };
  29425. return HingeJoint;
  29426. })(MotorEnabledJoint);
  29427. BABYLON.HingeJoint = HingeJoint;
  29428. /**
  29429. * This class represents a dual hinge physics joint (same as wheel joint)
  29430. */
  29431. var Hinge2Joint = (function (_super) {
  29432. __extends(Hinge2Joint, _super);
  29433. function Hinge2Joint(jointData) {
  29434. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  29435. }
  29436. /**
  29437. * Set the motor values.
  29438. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29439. * @param {number} force the force to apply
  29440. * @param {number} maxForce max force for this motor.
  29441. * @param {motorIndex} the motor's index, 0 or 1.
  29442. */
  29443. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  29444. if (motorIndex === void 0) { motorIndex = 0; }
  29445. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  29446. };
  29447. /**
  29448. * Set the motor limits.
  29449. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29450. * @param {number} upperLimit the upper limit
  29451. * @param {number} lowerLimit lower limit
  29452. * @param {motorIndex} the motor's index, 0 or 1.
  29453. */
  29454. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  29455. if (motorIndex === void 0) { motorIndex = 0; }
  29456. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  29457. };
  29458. return Hinge2Joint;
  29459. })(MotorEnabledJoint);
  29460. BABYLON.Hinge2Joint = Hinge2Joint;
  29461. })(BABYLON || (BABYLON = {}));
  29462. var BABYLON;
  29463. (function (BABYLON) {
  29464. var PhysicsImpostor = (function () {
  29465. function PhysicsImpostor(object, type, _options, _scene) {
  29466. var _this = this;
  29467. if (_options === void 0) { _options = { mass: 0 }; }
  29468. this.object = object;
  29469. this.type = type;
  29470. this._options = _options;
  29471. this._scene = _scene;
  29472. this._bodyUpdateRequired = false;
  29473. this._onBeforePhysicsStepCallbacks = new Array();
  29474. this._onAfterPhysicsStepCallbacks = new Array();
  29475. this._onPhysicsCollideCallbacks = [];
  29476. this._deltaPosition = BABYLON.Vector3.Zero();
  29477. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  29478. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  29479. /**
  29480. * this function is executed by the physics engine.
  29481. */
  29482. this.beforeStep = function () {
  29483. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  29484. //conjugate deltaRotation
  29485. if (_this._deltaRotationConjugated) {
  29486. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  29487. }
  29488. else {
  29489. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  29490. }
  29491. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  29492. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  29493. func(_this);
  29494. });
  29495. };
  29496. /**
  29497. * this function is executed by the physics engine.
  29498. */
  29499. this.afterStep = function () {
  29500. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  29501. func(_this);
  29502. });
  29503. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  29504. _this.object.position.addInPlace(_this._deltaPosition);
  29505. if (_this._deltaRotation) {
  29506. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  29507. }
  29508. };
  29509. //event and body object due to cannon's event-based architecture.
  29510. this.onCollide = function (e) {
  29511. if (!_this._onPhysicsCollideCallbacks.length)
  29512. return;
  29513. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  29514. if (otherImpostor) {
  29515. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  29516. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  29517. }).forEach(function (obj) {
  29518. obj.callback(_this, otherImpostor);
  29519. });
  29520. }
  29521. };
  29522. //sanity check!
  29523. if (!this.object) {
  29524. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  29525. return;
  29526. }
  29527. //legacy support for old syntax.
  29528. if (!this._scene && object.getScene) {
  29529. this._scene = object.getScene();
  29530. }
  29531. this._physicsEngine = this._scene.getPhysicsEngine();
  29532. if (!this._physicsEngine) {
  29533. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  29534. }
  29535. else {
  29536. //set the object's quaternion, if not set
  29537. if (!this.object.rotationQuaternion) {
  29538. if (this.object.rotation) {
  29539. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  29540. }
  29541. else {
  29542. this.object.rotationQuaternion = new BABYLON.Quaternion();
  29543. }
  29544. }
  29545. //default options params
  29546. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  29547. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  29548. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  29549. this._joints = [];
  29550. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  29551. if (!this.object.parent) {
  29552. this._init();
  29553. }
  29554. }
  29555. }
  29556. /**
  29557. * This function will completly initialize this impostor.
  29558. * It will create a new body - but only if this mesh has no parent.
  29559. * If it has, this impostor will not be used other than to define the impostor
  29560. * of the child mesh.
  29561. */
  29562. PhysicsImpostor.prototype._init = function () {
  29563. this._physicsEngine.removeImpostor(this);
  29564. this.physicsBody = null;
  29565. this._parent = this._parent || this._getPhysicsParent();
  29566. if (!this.parent) {
  29567. this._physicsEngine.addImpostor(this);
  29568. }
  29569. };
  29570. PhysicsImpostor.prototype._getPhysicsParent = function () {
  29571. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  29572. var parentMesh = this.object.parent;
  29573. return parentMesh.physicsImpostor;
  29574. }
  29575. return;
  29576. };
  29577. /**
  29578. * Should a new body be generated.
  29579. */
  29580. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  29581. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  29582. };
  29583. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  29584. this.forceUpdate();
  29585. };
  29586. /**
  29587. * Force a regeneration of this or the parent's impostor's body.
  29588. * Use under cautious - This will remove all joints already implemented.
  29589. */
  29590. PhysicsImpostor.prototype.forceUpdate = function () {
  29591. this._init();
  29592. if (this.parent) {
  29593. this.parent.forceUpdate();
  29594. }
  29595. };
  29596. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  29597. /*public get mesh(): AbstractMesh {
  29598. return this._mesh;
  29599. }*/
  29600. /**
  29601. * Gets the body that holds this impostor. Either its own, or its parent.
  29602. */
  29603. get: function () {
  29604. return this._parent ? this._parent.physicsBody : this._physicsBody;
  29605. },
  29606. /**
  29607. * Set the physics body. Used mainly by the physics engine/plugin
  29608. */
  29609. set: function (physicsBody) {
  29610. if (this._physicsBody) {
  29611. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  29612. }
  29613. this._physicsBody = physicsBody;
  29614. this.resetUpdateFlags();
  29615. },
  29616. enumerable: true,
  29617. configurable: true
  29618. });
  29619. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  29620. get: function () {
  29621. return this._parent;
  29622. },
  29623. enumerable: true,
  29624. configurable: true
  29625. });
  29626. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  29627. this._bodyUpdateRequired = false;
  29628. };
  29629. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  29630. if (this.object.getBoundingInfo) {
  29631. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  29632. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  29633. }
  29634. else {
  29635. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  29636. }
  29637. };
  29638. PhysicsImpostor.prototype.getObjectCenter = function () {
  29639. if (this.object.getBoundingInfo) {
  29640. return this.object.getBoundingInfo().boundingBox.center;
  29641. }
  29642. else {
  29643. return this.object.position;
  29644. }
  29645. };
  29646. /**
  29647. * Get a specific parametes from the options parameter.
  29648. */
  29649. PhysicsImpostor.prototype.getParam = function (paramName) {
  29650. return this._options[paramName];
  29651. };
  29652. /**
  29653. * Sets a specific parameter in the options given to the physics plugin
  29654. */
  29655. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  29656. this._options[paramName] = value;
  29657. this._bodyUpdateRequired = true;
  29658. };
  29659. /**
  29660. * Specifically change the body's mass option. Won't recreate the physics body object
  29661. */
  29662. PhysicsImpostor.prototype.setMass = function (mass) {
  29663. if (this.getParam("mass") !== mass) {
  29664. this.setParam("mass", mass);
  29665. }
  29666. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  29667. };
  29668. PhysicsImpostor.prototype.getLinearVelocity = function () {
  29669. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  29670. };
  29671. /**
  29672. * Set the body's linear velocity.
  29673. */
  29674. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  29675. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  29676. };
  29677. PhysicsImpostor.prototype.getAngularVelocity = function () {
  29678. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  29679. };
  29680. /**
  29681. * Set the body's linear velocity.
  29682. */
  29683. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  29684. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  29685. };
  29686. /**
  29687. * Execute a function with the physics plugin native code.
  29688. * Provide a function the will have two variables - the world object and the physics body object.
  29689. */
  29690. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  29691. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  29692. };
  29693. /**
  29694. * Register a function that will be executed before the physics world is stepping forward.
  29695. */
  29696. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  29697. this._onBeforePhysicsStepCallbacks.push(func);
  29698. };
  29699. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  29700. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  29701. if (index > -1) {
  29702. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  29703. }
  29704. else {
  29705. BABYLON.Tools.Warn("Function to remove was not found");
  29706. }
  29707. };
  29708. /**
  29709. * Register a function that will be executed after the physics step
  29710. */
  29711. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  29712. this._onAfterPhysicsStepCallbacks.push(func);
  29713. };
  29714. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  29715. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  29716. if (index > -1) {
  29717. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  29718. }
  29719. else {
  29720. BABYLON.Tools.Warn("Function to remove was not found");
  29721. }
  29722. };
  29723. /**
  29724. * register a function that will be executed when this impostor collides against a different body.
  29725. */
  29726. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  29727. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  29728. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  29729. };
  29730. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  29731. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  29732. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  29733. if (index > -1) {
  29734. this._onPhysicsCollideCallbacks.splice(index, 1);
  29735. }
  29736. else {
  29737. BABYLON.Tools.Warn("Function to remove was not found");
  29738. }
  29739. };
  29740. /**
  29741. * Apply a force
  29742. */
  29743. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  29744. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  29745. };
  29746. /**
  29747. * Apply an impulse
  29748. */
  29749. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  29750. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  29751. };
  29752. /**
  29753. * A help function to create a joint.
  29754. */
  29755. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  29756. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  29757. this.addJoint(otherImpostor, joint);
  29758. };
  29759. /**
  29760. * Add a joint to this impostor with a different impostor.
  29761. */
  29762. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  29763. this._joints.push({
  29764. otherImpostor: otherImpostor,
  29765. joint: joint
  29766. });
  29767. this._physicsEngine.addJoint(this, otherImpostor, joint);
  29768. };
  29769. /**
  29770. * Will keep this body still, in a sleep mode.
  29771. */
  29772. PhysicsImpostor.prototype.sleep = function () {
  29773. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  29774. };
  29775. /**
  29776. * Wake the body up.
  29777. */
  29778. PhysicsImpostor.prototype.wakeUp = function () {
  29779. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  29780. };
  29781. PhysicsImpostor.prototype.clone = function (newObject) {
  29782. if (!newObject)
  29783. return null;
  29784. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  29785. };
  29786. PhysicsImpostor.prototype.dispose = function () {
  29787. var _this = this;
  29788. //no dispose if no physics engine is available.
  29789. if (!this._physicsEngine) {
  29790. return;
  29791. }
  29792. this._joints.forEach(function (j) {
  29793. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  29794. });
  29795. //dispose the physics body
  29796. this._physicsEngine.removeImpostor(this);
  29797. if (this.parent) {
  29798. this.parent.forceUpdate();
  29799. }
  29800. else {
  29801. }
  29802. };
  29803. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  29804. this._deltaPosition.copyFrom(position);
  29805. };
  29806. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  29807. if (!this._deltaRotation) {
  29808. this._deltaRotation = new BABYLON.Quaternion();
  29809. }
  29810. this._deltaRotation.copyFrom(rotation);
  29811. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  29812. };
  29813. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  29814. //Impostor types
  29815. PhysicsImpostor.NoImpostor = 0;
  29816. PhysicsImpostor.SphereImpostor = 1;
  29817. PhysicsImpostor.BoxImpostor = 2;
  29818. PhysicsImpostor.PlaneImpostor = 3;
  29819. PhysicsImpostor.MeshImpostor = 4;
  29820. PhysicsImpostor.CylinderImpostor = 7;
  29821. PhysicsImpostor.ParticleImpostor = 8;
  29822. PhysicsImpostor.HeightmapImpostor = 9;
  29823. return PhysicsImpostor;
  29824. })();
  29825. BABYLON.PhysicsImpostor = PhysicsImpostor;
  29826. })(BABYLON || (BABYLON = {}));
  29827. var BABYLON;
  29828. (function (BABYLON) {
  29829. var PhysicsEngine = (function () {
  29830. function PhysicsEngine(gravity, _physicsPlugin) {
  29831. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  29832. this._physicsPlugin = _physicsPlugin;
  29833. //new methods and parameters
  29834. this._impostors = [];
  29835. this._joints = [];
  29836. if (!this._physicsPlugin.isSupported()) {
  29837. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  29838. + "Please make sure it is included.");
  29839. }
  29840. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  29841. this.setGravity(gravity);
  29842. this.setTimeStep();
  29843. }
  29844. PhysicsEngine.prototype.setGravity = function (gravity) {
  29845. this.gravity = gravity;
  29846. this._physicsPlugin.setGravity(this.gravity);
  29847. };
  29848. /**
  29849. * Set the time step of the physics engine.
  29850. * default is 1/60.
  29851. * To slow it down, enter 1/600 for example.
  29852. * To speed it up, 1/30
  29853. * @param {number} newTimeStep the new timestep to apply to this world.
  29854. */
  29855. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  29856. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  29857. this._physicsPlugin.setTimeStep(newTimeStep);
  29858. };
  29859. PhysicsEngine.prototype.dispose = function () {
  29860. this._impostors.forEach(function (impostor) {
  29861. impostor.dispose();
  29862. });
  29863. this._physicsPlugin.dispose();
  29864. };
  29865. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  29866. return this._physicsPlugin.name;
  29867. };
  29868. /**
  29869. * Adding a new impostor for the impostor tracking.
  29870. * This will be done by the impostor itself.
  29871. * @param {PhysicsImpostor} impostor the impostor to add
  29872. */
  29873. PhysicsEngine.prototype.addImpostor = function (impostor) {
  29874. impostor.uniqueId = this._impostors.push(impostor);
  29875. //if no parent, generate the body
  29876. if (!impostor.parent) {
  29877. this._physicsPlugin.generatePhysicsBody(impostor);
  29878. }
  29879. };
  29880. /**
  29881. * Remove an impostor from the engine.
  29882. * This impostor and its mesh will not longer be updated by the physics engine.
  29883. * @param {PhysicsImpostor} impostor the impostor to remove
  29884. */
  29885. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  29886. var index = this._impostors.indexOf(impostor);
  29887. if (index > -1) {
  29888. var removed = this._impostors.splice(index, 1);
  29889. //Is it needed?
  29890. if (removed.length) {
  29891. //this will also remove it from the world.
  29892. removed[0].physicsBody = null;
  29893. }
  29894. }
  29895. };
  29896. /**
  29897. * Add a joint to the physics engine
  29898. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  29899. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  29900. * @param {PhysicsJoint} the joint that will connect both impostors.
  29901. */
  29902. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  29903. var impostorJoint = {
  29904. mainImpostor: mainImpostor,
  29905. connectedImpostor: connectedImpostor,
  29906. joint: joint
  29907. };
  29908. joint.physicsPlugin = this._physicsPlugin;
  29909. this._joints.push(impostorJoint);
  29910. this._physicsPlugin.generateJoint(impostorJoint);
  29911. };
  29912. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  29913. var matchingJoints = this._joints.filter(function (impostorJoint) {
  29914. return (impostorJoint.connectedImpostor === connectedImpostor
  29915. && impostorJoint.joint === joint
  29916. && impostorJoint.mainImpostor === mainImpostor);
  29917. });
  29918. if (matchingJoints.length) {
  29919. this._physicsPlugin.removeJoint(matchingJoints[0]);
  29920. }
  29921. };
  29922. /**
  29923. * Called by the scene. no need to call it.
  29924. */
  29925. PhysicsEngine.prototype._step = function (delta) {
  29926. var _this = this;
  29927. //check if any mesh has no body / requires an update
  29928. this._impostors.forEach(function (impostor) {
  29929. if (impostor.isBodyInitRequired()) {
  29930. _this._physicsPlugin.generatePhysicsBody(impostor);
  29931. }
  29932. });
  29933. if (delta > 0.1) {
  29934. delta = 0.1;
  29935. }
  29936. else if (delta <= 0) {
  29937. delta = 1.0 / 60.0;
  29938. }
  29939. this._physicsPlugin.executeStep(delta, this._impostors);
  29940. };
  29941. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  29942. return this._physicsPlugin;
  29943. };
  29944. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  29945. for (var i = 0; i < this._impostors.length; ++i) {
  29946. if (this._impostors[i].object === object) {
  29947. return this._impostors[i];
  29948. }
  29949. }
  29950. };
  29951. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  29952. for (var i = 0; i < this._impostors.length; ++i) {
  29953. if (this._impostors[i].physicsBody === body) {
  29954. return this._impostors[i];
  29955. }
  29956. }
  29957. };
  29958. // Statics, Legacy support.
  29959. /**
  29960. * @Deprecated
  29961. *
  29962. */
  29963. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  29964. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  29965. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  29966. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  29967. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  29968. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  29969. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  29970. PhysicsEngine.CapsuleImpostor = -1;
  29971. PhysicsEngine.ConeImpostor = -1;
  29972. PhysicsEngine.ConvexHullImpostor = -1;
  29973. PhysicsEngine.Epsilon = 0.001;
  29974. return PhysicsEngine;
  29975. })();
  29976. BABYLON.PhysicsEngine = PhysicsEngine;
  29977. })(BABYLON || (BABYLON = {}));
  29978. var BABYLON;
  29979. (function (BABYLON) {
  29980. var VertexData = (function () {
  29981. function VertexData() {
  29982. }
  29983. VertexData.prototype.set = function (data, kind) {
  29984. switch (kind) {
  29985. case BABYLON.VertexBuffer.PositionKind:
  29986. this.positions = data;
  29987. break;
  29988. case BABYLON.VertexBuffer.NormalKind:
  29989. this.normals = data;
  29990. break;
  29991. case BABYLON.VertexBuffer.UVKind:
  29992. this.uvs = data;
  29993. break;
  29994. case BABYLON.VertexBuffer.UV2Kind:
  29995. this.uvs2 = data;
  29996. break;
  29997. case BABYLON.VertexBuffer.UV3Kind:
  29998. this.uvs3 = data;
  29999. break;
  30000. case BABYLON.VertexBuffer.UV4Kind:
  30001. this.uvs4 = data;
  30002. break;
  30003. case BABYLON.VertexBuffer.UV5Kind:
  30004. this.uvs5 = data;
  30005. break;
  30006. case BABYLON.VertexBuffer.UV6Kind:
  30007. this.uvs6 = data;
  30008. break;
  30009. case BABYLON.VertexBuffer.ColorKind:
  30010. this.colors = data;
  30011. break;
  30012. case BABYLON.VertexBuffer.MatricesIndicesKind:
  30013. this.matricesIndices = data;
  30014. break;
  30015. case BABYLON.VertexBuffer.MatricesWeightsKind:
  30016. this.matricesWeights = data;
  30017. break;
  30018. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  30019. this.matricesIndicesExtra = data;
  30020. break;
  30021. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  30022. this.matricesWeightsExtra = data;
  30023. break;
  30024. }
  30025. };
  30026. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  30027. this._applyTo(mesh, updatable);
  30028. };
  30029. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  30030. this._applyTo(geometry, updatable);
  30031. };
  30032. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  30033. this._update(mesh);
  30034. };
  30035. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  30036. this._update(geometry);
  30037. };
  30038. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  30039. if (this.positions) {
  30040. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  30041. }
  30042. if (this.normals) {
  30043. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  30044. }
  30045. if (this.uvs) {
  30046. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  30047. }
  30048. if (this.uvs2) {
  30049. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  30050. }
  30051. if (this.uvs3) {
  30052. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  30053. }
  30054. if (this.uvs4) {
  30055. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  30056. }
  30057. if (this.uvs5) {
  30058. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  30059. }
  30060. if (this.uvs6) {
  30061. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  30062. }
  30063. if (this.colors) {
  30064. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  30065. }
  30066. if (this.matricesIndices) {
  30067. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  30068. }
  30069. if (this.matricesWeights) {
  30070. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  30071. }
  30072. if (this.matricesIndicesExtra) {
  30073. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  30074. }
  30075. if (this.matricesWeightsExtra) {
  30076. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  30077. }
  30078. if (this.indices) {
  30079. meshOrGeometry.setIndices(this.indices);
  30080. }
  30081. };
  30082. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  30083. if (this.positions) {
  30084. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  30085. }
  30086. if (this.normals) {
  30087. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  30088. }
  30089. if (this.uvs) {
  30090. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  30091. }
  30092. if (this.uvs2) {
  30093. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  30094. }
  30095. if (this.uvs3) {
  30096. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  30097. }
  30098. if (this.uvs4) {
  30099. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  30100. }
  30101. if (this.uvs5) {
  30102. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  30103. }
  30104. if (this.uvs6) {
  30105. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  30106. }
  30107. if (this.colors) {
  30108. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  30109. }
  30110. if (this.matricesIndices) {
  30111. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  30112. }
  30113. if (this.matricesWeights) {
  30114. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  30115. }
  30116. if (this.matricesIndicesExtra) {
  30117. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  30118. }
  30119. if (this.matricesWeightsExtra) {
  30120. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  30121. }
  30122. if (this.indices) {
  30123. meshOrGeometry.setIndices(this.indices);
  30124. }
  30125. };
  30126. VertexData.prototype.transform = function (matrix) {
  30127. var transformed = BABYLON.Vector3.Zero();
  30128. var index;
  30129. if (this.positions) {
  30130. var position = BABYLON.Vector3.Zero();
  30131. for (index = 0; index < this.positions.length; index += 3) {
  30132. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  30133. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  30134. this.positions[index] = transformed.x;
  30135. this.positions[index + 1] = transformed.y;
  30136. this.positions[index + 2] = transformed.z;
  30137. }
  30138. }
  30139. if (this.normals) {
  30140. var normal = BABYLON.Vector3.Zero();
  30141. for (index = 0; index < this.normals.length; index += 3) {
  30142. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  30143. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  30144. this.normals[index] = transformed.x;
  30145. this.normals[index + 1] = transformed.y;
  30146. this.normals[index + 2] = transformed.z;
  30147. }
  30148. }
  30149. };
  30150. VertexData.prototype.merge = function (other) {
  30151. if (other.indices) {
  30152. if (!this.indices) {
  30153. this.indices = [];
  30154. }
  30155. var offset = this.positions ? this.positions.length / 3 : 0;
  30156. for (var index = 0; index < other.indices.length; index++) {
  30157. //TODO check type - if Int32Array!
  30158. this.indices.push(other.indices[index] + offset);
  30159. }
  30160. }
  30161. this.positions = this._mergeElement(this.positions, other.positions);
  30162. this.normals = this._mergeElement(this.normals, other.normals);
  30163. this.uvs = this._mergeElement(this.uvs, other.uvs);
  30164. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  30165. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  30166. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  30167. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  30168. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  30169. this.colors = this._mergeElement(this.colors, other.colors);
  30170. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  30171. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  30172. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  30173. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  30174. };
  30175. VertexData.prototype._mergeElement = function (source, other) {
  30176. if (!other)
  30177. return source;
  30178. if (!source)
  30179. return other;
  30180. var len = other.length + source.length;
  30181. var isSrcTypedArray = source instanceof Float32Array;
  30182. var isOthTypedArray = other instanceof Float32Array;
  30183. // use non-loop method when the source is Float32Array
  30184. if (isSrcTypedArray) {
  30185. var ret32 = new Float32Array(len);
  30186. ret32.set(source);
  30187. ret32.set(other, source.length);
  30188. return ret32;
  30189. }
  30190. else if (!isOthTypedArray) {
  30191. return source.concat(other);
  30192. }
  30193. else {
  30194. var ret = source.slice(0); // copy source to a separate array
  30195. for (var i = 0, len = other.length; i < len; i++) {
  30196. ret.push(other[i]);
  30197. }
  30198. return ret;
  30199. }
  30200. };
  30201. VertexData.prototype.serialize = function () {
  30202. var serializationObject = this.serialize();
  30203. if (this.positions) {
  30204. serializationObject.positions = this.positions;
  30205. }
  30206. if (this.normals) {
  30207. serializationObject.normals = this.normals;
  30208. }
  30209. if (this.uvs) {
  30210. serializationObject.uvs = this.uvs;
  30211. }
  30212. if (this.uvs2) {
  30213. serializationObject.uvs2 = this.uvs2;
  30214. }
  30215. if (this.uvs3) {
  30216. serializationObject.uvs3 = this.uvs3;
  30217. }
  30218. if (this.uvs4) {
  30219. serializationObject.uvs4 = this.uvs4;
  30220. }
  30221. if (this.uvs5) {
  30222. serializationObject.uvs5 = this.uvs5;
  30223. }
  30224. if (this.uvs6) {
  30225. serializationObject.uvs6 = this.uvs6;
  30226. }
  30227. if (this.colors) {
  30228. serializationObject.colors = this.colors;
  30229. }
  30230. if (this.matricesIndices) {
  30231. serializationObject.matricesIndices = this.matricesIndices;
  30232. serializationObject.matricesIndices._isExpanded = true;
  30233. }
  30234. if (this.matricesWeights) {
  30235. serializationObject.matricesWeights = this.matricesWeights;
  30236. }
  30237. if (this.matricesIndicesExtra) {
  30238. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  30239. serializationObject.matricesIndicesExtra._isExpanded = true;
  30240. }
  30241. if (this.matricesWeightsExtra) {
  30242. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  30243. }
  30244. serializationObject.indices = this.indices;
  30245. return serializationObject;
  30246. };
  30247. // Statics
  30248. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  30249. return VertexData._ExtractFrom(mesh, copyWhenShared);
  30250. };
  30251. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  30252. return VertexData._ExtractFrom(geometry, copyWhenShared);
  30253. };
  30254. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  30255. var result = new VertexData();
  30256. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30257. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  30258. }
  30259. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30260. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  30261. }
  30262. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30263. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  30264. }
  30265. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30266. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  30267. }
  30268. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30269. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  30270. }
  30271. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30272. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  30273. }
  30274. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30275. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  30276. }
  30277. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30278. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  30279. }
  30280. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30281. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  30282. }
  30283. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30284. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  30285. }
  30286. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30287. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  30288. }
  30289. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  30290. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  30291. }
  30292. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  30293. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  30294. }
  30295. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  30296. return result;
  30297. };
  30298. VertexData.CreateRibbon = function (options) {
  30299. var pathArray = options.pathArray;
  30300. var closeArray = options.closeArray || false;
  30301. var closePath = options.closePath || false;
  30302. var invertUV = options.invertUV || false;
  30303. var defaultOffset = Math.floor(pathArray[0].length / 2);
  30304. var offset = options.offset || defaultOffset;
  30305. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  30306. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30307. var positions = [];
  30308. var indices = [];
  30309. var normals = [];
  30310. var uvs = [];
  30311. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  30312. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  30313. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  30314. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  30315. var minlg; // minimal length among all paths from pathArray
  30316. var lg = []; // array of path lengths : nb of vertex per path
  30317. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  30318. var p; // path iterator
  30319. var i; // point iterator
  30320. var j; // point iterator
  30321. // if single path in pathArray
  30322. if (pathArray.length < 2) {
  30323. var ar1 = [];
  30324. var ar2 = [];
  30325. for (i = 0; i < pathArray[0].length - offset; i++) {
  30326. ar1.push(pathArray[0][i]);
  30327. ar2.push(pathArray[0][i + offset]);
  30328. }
  30329. pathArray = [ar1, ar2];
  30330. }
  30331. // positions and horizontal distances (u)
  30332. var idc = 0;
  30333. var closePathCorr = (closePath) ? 1 : 0;
  30334. var path;
  30335. var l;
  30336. minlg = pathArray[0].length;
  30337. var vectlg;
  30338. var dist;
  30339. for (p = 0; p < pathArray.length; p++) {
  30340. uTotalDistance[p] = 0;
  30341. us[p] = [0];
  30342. path = pathArray[p];
  30343. l = path.length;
  30344. minlg = (minlg < l) ? minlg : l;
  30345. j = 0;
  30346. while (j < l) {
  30347. positions.push(path[j].x, path[j].y, path[j].z);
  30348. if (j > 0) {
  30349. vectlg = path[j].subtract(path[j - 1]).length();
  30350. dist = vectlg + uTotalDistance[p];
  30351. us[p].push(dist);
  30352. uTotalDistance[p] = dist;
  30353. }
  30354. j++;
  30355. }
  30356. if (closePath) {
  30357. j--;
  30358. positions.push(path[0].x, path[0].y, path[0].z);
  30359. vectlg = path[j].subtract(path[0]).length();
  30360. dist = vectlg + uTotalDistance[p];
  30361. us[p].push(dist);
  30362. uTotalDistance[p] = dist;
  30363. }
  30364. lg[p] = l + closePathCorr;
  30365. idx[p] = idc;
  30366. idc += (l + closePathCorr);
  30367. }
  30368. // vertical distances (v)
  30369. var path1;
  30370. var path2;
  30371. var vertex1;
  30372. var vertex2;
  30373. for (i = 0; i < minlg + closePathCorr; i++) {
  30374. vTotalDistance[i] = 0;
  30375. vs[i] = [0];
  30376. for (p = 0; p < pathArray.length - 1; p++) {
  30377. path1 = pathArray[p];
  30378. path2 = pathArray[p + 1];
  30379. if (i === minlg) {
  30380. vertex1 = path1[0];
  30381. vertex2 = path2[0];
  30382. }
  30383. else {
  30384. vertex1 = path1[i];
  30385. vertex2 = path2[i];
  30386. }
  30387. vectlg = vertex2.subtract(vertex1).length();
  30388. dist = vectlg + vTotalDistance[i];
  30389. vs[i].push(dist);
  30390. vTotalDistance[i] = dist;
  30391. }
  30392. if (closeArray) {
  30393. path1 = pathArray[p];
  30394. path2 = pathArray[0];
  30395. if (i === minlg) {
  30396. vertex2 = path2[0];
  30397. }
  30398. vectlg = vertex2.subtract(vertex1).length();
  30399. dist = vectlg + vTotalDistance[i];
  30400. vTotalDistance[i] = dist;
  30401. }
  30402. }
  30403. // uvs
  30404. var u;
  30405. var v;
  30406. for (p = 0; p < pathArray.length; p++) {
  30407. for (i = 0; i < minlg + closePathCorr; i++) {
  30408. u = us[p][i] / uTotalDistance[p];
  30409. v = vs[i][p] / vTotalDistance[i];
  30410. if (invertUV) {
  30411. uvs.push(v, u);
  30412. }
  30413. else {
  30414. uvs.push(u, v);
  30415. }
  30416. }
  30417. }
  30418. // indices
  30419. p = 0; // path index
  30420. var pi = 0; // positions array index
  30421. var l1 = lg[p] - 1; // path1 length
  30422. var l2 = lg[p + 1] - 1; // path2 length
  30423. var min = (l1 < l2) ? l1 : l2; // current path stop index
  30424. var shft = idx[1] - idx[0]; // shift
  30425. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  30426. while (pi <= min && p < path1nb) {
  30427. // 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
  30428. indices.push(pi, pi + shft, pi + 1);
  30429. indices.push(pi + shft + 1, pi + 1, pi + shft);
  30430. pi += 1;
  30431. if (pi === min) {
  30432. p++;
  30433. if (p === lg.length - 1) {
  30434. shft = idx[0] - idx[p];
  30435. l1 = lg[p] - 1;
  30436. l2 = lg[0] - 1;
  30437. }
  30438. else {
  30439. shft = idx[p + 1] - idx[p];
  30440. l1 = lg[p] - 1;
  30441. l2 = lg[p + 1] - 1;
  30442. }
  30443. pi = idx[p];
  30444. min = (l1 < l2) ? l1 + pi : l2 + pi;
  30445. }
  30446. }
  30447. // normals
  30448. VertexData.ComputeNormals(positions, indices, normals);
  30449. if (closePath) {
  30450. var indexFirst = 0;
  30451. var indexLast = 0;
  30452. for (p = 0; p < pathArray.length; p++) {
  30453. indexFirst = idx[p] * 3;
  30454. if (p + 1 < pathArray.length) {
  30455. indexLast = (idx[p + 1] - 1) * 3;
  30456. }
  30457. else {
  30458. indexLast = normals.length - 3;
  30459. }
  30460. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  30461. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  30462. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  30463. normals[indexLast] = normals[indexFirst];
  30464. normals[indexLast + 1] = normals[indexFirst + 1];
  30465. normals[indexLast + 2] = normals[indexFirst + 2];
  30466. }
  30467. }
  30468. // sides
  30469. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30470. // Result
  30471. var vertexData = new VertexData();
  30472. vertexData.indices = indices;
  30473. vertexData.positions = positions;
  30474. vertexData.normals = normals;
  30475. vertexData.uvs = uvs;
  30476. if (closePath) {
  30477. vertexData._idx = idx;
  30478. }
  30479. return vertexData;
  30480. };
  30481. VertexData.CreateBox = function (options) {
  30482. var normalsSource = [
  30483. new BABYLON.Vector3(0, 0, 1),
  30484. new BABYLON.Vector3(0, 0, -1),
  30485. new BABYLON.Vector3(1, 0, 0),
  30486. new BABYLON.Vector3(-1, 0, 0),
  30487. new BABYLON.Vector3(0, 1, 0),
  30488. new BABYLON.Vector3(0, -1, 0)
  30489. ];
  30490. var indices = [];
  30491. var positions = [];
  30492. var normals = [];
  30493. var uvs = [];
  30494. var width = options.width || options.size || 1;
  30495. var height = options.height || options.size || 1;
  30496. var depth = options.depth || options.size || 1;
  30497. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30498. var faceUV = options.faceUV || new Array(6);
  30499. var faceColors = options.faceColors;
  30500. var colors = [];
  30501. // default face colors and UV if undefined
  30502. for (var f = 0; f < 6; f++) {
  30503. if (faceUV[f] === undefined) {
  30504. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30505. }
  30506. if (faceColors && faceColors[f] === undefined) {
  30507. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30508. }
  30509. }
  30510. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  30511. // Create each face in turn.
  30512. for (var index = 0; index < normalsSource.length; index++) {
  30513. var normal = normalsSource[index];
  30514. // Get two vectors perpendicular to the face normal and to each other.
  30515. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  30516. var side2 = BABYLON.Vector3.Cross(normal, side1);
  30517. // Six indices (two triangles) per face.
  30518. var verticesLength = positions.length / 3;
  30519. indices.push(verticesLength);
  30520. indices.push(verticesLength + 1);
  30521. indices.push(verticesLength + 2);
  30522. indices.push(verticesLength);
  30523. indices.push(verticesLength + 2);
  30524. indices.push(verticesLength + 3);
  30525. // Four vertices per face.
  30526. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  30527. positions.push(vertex.x, vertex.y, vertex.z);
  30528. normals.push(normal.x, normal.y, normal.z);
  30529. uvs.push(faceUV[index].z, faceUV[index].w);
  30530. if (faceColors) {
  30531. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30532. }
  30533. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  30534. positions.push(vertex.x, vertex.y, vertex.z);
  30535. normals.push(normal.x, normal.y, normal.z);
  30536. uvs.push(faceUV[index].x, faceUV[index].w);
  30537. if (faceColors) {
  30538. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30539. }
  30540. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  30541. positions.push(vertex.x, vertex.y, vertex.z);
  30542. normals.push(normal.x, normal.y, normal.z);
  30543. uvs.push(faceUV[index].x, faceUV[index].y);
  30544. if (faceColors) {
  30545. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30546. }
  30547. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  30548. positions.push(vertex.x, vertex.y, vertex.z);
  30549. normals.push(normal.x, normal.y, normal.z);
  30550. uvs.push(faceUV[index].z, faceUV[index].y);
  30551. if (faceColors) {
  30552. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30553. }
  30554. }
  30555. // sides
  30556. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30557. // Result
  30558. var vertexData = new VertexData();
  30559. vertexData.indices = indices;
  30560. vertexData.positions = positions;
  30561. vertexData.normals = normals;
  30562. vertexData.uvs = uvs;
  30563. if (faceColors) {
  30564. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30565. vertexData.colors = totalColors;
  30566. }
  30567. return vertexData;
  30568. };
  30569. VertexData.CreateSphere = function (options) {
  30570. var segments = options.segments || 32;
  30571. var diameterX = options.diameterX || options.diameter || 1;
  30572. var diameterY = options.diameterY || options.diameter || 1;
  30573. var diameterZ = options.diameterZ || options.diameter || 1;
  30574. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30575. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  30576. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30577. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  30578. var totalZRotationSteps = 2 + segments;
  30579. var totalYRotationSteps = 2 * totalZRotationSteps;
  30580. var indices = [];
  30581. var positions = [];
  30582. var normals = [];
  30583. var uvs = [];
  30584. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  30585. var normalizedZ = zRotationStep / totalZRotationSteps;
  30586. var angleZ = normalizedZ * Math.PI * slice;
  30587. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  30588. var normalizedY = yRotationStep / totalYRotationSteps;
  30589. var angleY = normalizedY * Math.PI * 2 * arc;
  30590. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  30591. var rotationY = BABYLON.Matrix.RotationY(angleY);
  30592. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  30593. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  30594. var vertex = complete.multiply(radius);
  30595. var normal = complete.divide(radius).normalize();
  30596. positions.push(vertex.x, vertex.y, vertex.z);
  30597. normals.push(normal.x, normal.y, normal.z);
  30598. uvs.push(normalizedY, normalizedZ);
  30599. }
  30600. if (zRotationStep > 0) {
  30601. var verticesCount = positions.length / 3;
  30602. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  30603. indices.push((firstIndex));
  30604. indices.push((firstIndex + 1));
  30605. indices.push(firstIndex + totalYRotationSteps + 1);
  30606. indices.push((firstIndex + totalYRotationSteps + 1));
  30607. indices.push((firstIndex + 1));
  30608. indices.push((firstIndex + totalYRotationSteps + 2));
  30609. }
  30610. }
  30611. }
  30612. // Sides
  30613. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30614. // Result
  30615. var vertexData = new VertexData();
  30616. vertexData.indices = indices;
  30617. vertexData.positions = positions;
  30618. vertexData.normals = normals;
  30619. vertexData.uvs = uvs;
  30620. return vertexData;
  30621. };
  30622. // Cylinder and cone
  30623. VertexData.CreateCylinder = function (options) {
  30624. var height = options.height || 2;
  30625. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  30626. var diameterBottom = options.diameterBottom || options.diameter || 1;
  30627. var tessellation = options.tessellation || 24;
  30628. var subdivisions = options.subdivisions || 1;
  30629. var hasRings = options.hasRings;
  30630. var enclose = options.enclose;
  30631. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30632. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30633. var faceUV = options.faceUV || new Array(3);
  30634. var faceColors = options.faceColors;
  30635. // default face colors and UV if undefined
  30636. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  30637. var ringNb = (hasRings) ? subdivisions : 1;
  30638. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  30639. var f;
  30640. for (f = 0; f < surfaceNb; f++) {
  30641. if (faceColors && faceColors[f] === undefined) {
  30642. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30643. }
  30644. }
  30645. for (f = 0; f < surfaceNb; f++) {
  30646. if (faceUV && faceUV[f] === undefined) {
  30647. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30648. }
  30649. }
  30650. var indices = [];
  30651. var positions = [];
  30652. var normals = [];
  30653. var uvs = [];
  30654. var colors = [];
  30655. var angle_step = Math.PI * 2 * arc / tessellation;
  30656. var angle;
  30657. var h;
  30658. var radius;
  30659. var tan = (diameterBottom - diameterTop) / 2 / height;
  30660. var ringVertex = BABYLON.Vector3.Zero();
  30661. var ringNormal = BABYLON.Vector3.Zero();
  30662. var ringFirstVertex = BABYLON.Vector3.Zero();
  30663. var ringFirstNormal = BABYLON.Vector3.Zero();
  30664. var quadNormal = BABYLON.Vector3.Zero();
  30665. var Y = BABYLON.Axis.Y;
  30666. // positions, normals, uvs
  30667. var i;
  30668. var j;
  30669. var r;
  30670. var ringIdx = 1;
  30671. var s = 1; // surface index
  30672. var cs = 0;
  30673. var v = 0;
  30674. for (i = 0; i <= subdivisions; i++) {
  30675. h = i / subdivisions;
  30676. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  30677. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  30678. for (r = 0; r < ringIdx; r++) {
  30679. if (hasRings) {
  30680. s += r;
  30681. }
  30682. if (enclose) {
  30683. s += 2 * r;
  30684. }
  30685. for (j = 0; j <= tessellation; j++) {
  30686. angle = j * angle_step;
  30687. // position
  30688. ringVertex.x = Math.cos(-angle) * radius;
  30689. ringVertex.y = -height / 2 + h * height;
  30690. ringVertex.z = Math.sin(-angle) * radius;
  30691. // normal
  30692. if (diameterTop === 0 && i === subdivisions) {
  30693. // if no top cap, reuse former normals
  30694. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  30695. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  30696. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  30697. }
  30698. else {
  30699. ringNormal.x = ringVertex.x;
  30700. ringNormal.z = ringVertex.z;
  30701. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  30702. ringNormal.normalize();
  30703. }
  30704. // keep first ring vertex values for enclose
  30705. if (j === 0) {
  30706. ringFirstVertex.copyFrom(ringVertex);
  30707. ringFirstNormal.copyFrom(ringNormal);
  30708. }
  30709. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30710. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  30711. if (hasRings) {
  30712. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  30713. }
  30714. else {
  30715. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  30716. }
  30717. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  30718. if (faceColors) {
  30719. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  30720. }
  30721. }
  30722. // if enclose, add four vertices and their dedicated normals
  30723. if (arc !== 1 && enclose) {
  30724. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30725. positions.push(0, ringVertex.y, 0);
  30726. positions.push(0, ringVertex.y, 0);
  30727. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  30728. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  30729. quadNormal.normalize();
  30730. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30731. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  30732. quadNormal.normalize();
  30733. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30734. if (hasRings) {
  30735. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  30736. }
  30737. else {
  30738. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  30739. }
  30740. uvs.push(faceUV[s + 1].x, v);
  30741. uvs.push(faceUV[s + 1].z, v);
  30742. if (hasRings) {
  30743. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  30744. }
  30745. else {
  30746. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  30747. }
  30748. uvs.push(faceUV[s + 2].x, v);
  30749. uvs.push(faceUV[s + 2].z, v);
  30750. if (faceColors) {
  30751. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30752. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30753. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30754. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30755. }
  30756. }
  30757. if (cs !== s) {
  30758. cs = s;
  30759. }
  30760. }
  30761. }
  30762. // indices
  30763. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  30764. var s;
  30765. i = 0;
  30766. for (s = 0; s < subdivisions; s++) {
  30767. for (j = 0; j < tessellation; j++) {
  30768. var i0 = i * (e + 1) + j;
  30769. var i1 = (i + 1) * (e + 1) + j;
  30770. var i2 = i * (e + 1) + (j + 1);
  30771. var i3 = (i + 1) * (e + 1) + (j + 1);
  30772. indices.push(i0, i1, i2);
  30773. indices.push(i3, i2, i1);
  30774. }
  30775. if (arc !== 1 && enclose) {
  30776. indices.push(i0 + 2, i1 + 2, i2 + 2);
  30777. indices.push(i3 + 2, i2 + 2, i1 + 2);
  30778. indices.push(i0 + 4, i1 + 4, i2 + 4);
  30779. indices.push(i3 + 4, i2 + 4, i1 + 4);
  30780. }
  30781. i = (hasRings) ? (i + 2) : (i + 1);
  30782. }
  30783. // Caps
  30784. var createCylinderCap = function (isTop) {
  30785. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  30786. if (radius === 0) {
  30787. return;
  30788. }
  30789. // Cap positions, normals & uvs
  30790. var angle;
  30791. var circleVector;
  30792. var i;
  30793. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  30794. var c;
  30795. if (faceColors) {
  30796. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  30797. }
  30798. // cap center
  30799. var vbase = positions.length / 3;
  30800. var offset = isTop ? height / 2 : -height / 2;
  30801. var center = new BABYLON.Vector3(0, offset, 0);
  30802. positions.push(center.x, center.y, center.z);
  30803. normals.push(0, isTop ? 1 : -1, 0);
  30804. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  30805. if (faceColors) {
  30806. colors.push(c.r, c.g, c.b, c.a);
  30807. }
  30808. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  30809. for (i = 0; i <= tessellation; i++) {
  30810. angle = Math.PI * 2 * i * arc / tessellation;
  30811. var cos = Math.cos(-angle);
  30812. var sin = Math.sin(-angle);
  30813. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  30814. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  30815. positions.push(circleVector.x, circleVector.y, circleVector.z);
  30816. normals.push(0, isTop ? 1 : -1, 0);
  30817. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  30818. if (faceColors) {
  30819. colors.push(c.r, c.g, c.b, c.a);
  30820. }
  30821. }
  30822. // Cap indices
  30823. for (i = 0; i < tessellation; i++) {
  30824. if (!isTop) {
  30825. indices.push(vbase);
  30826. indices.push(vbase + (i + 1));
  30827. indices.push(vbase + (i + 2));
  30828. }
  30829. else {
  30830. indices.push(vbase);
  30831. indices.push(vbase + (i + 2));
  30832. indices.push(vbase + (i + 1));
  30833. }
  30834. }
  30835. };
  30836. // add caps to geometry
  30837. createCylinderCap(false);
  30838. createCylinderCap(true);
  30839. // Sides
  30840. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30841. var vertexData = new VertexData();
  30842. vertexData.indices = indices;
  30843. vertexData.positions = positions;
  30844. vertexData.normals = normals;
  30845. vertexData.uvs = uvs;
  30846. if (faceColors) {
  30847. vertexData.colors = colors;
  30848. }
  30849. return vertexData;
  30850. };
  30851. VertexData.CreateTorus = function (options) {
  30852. var indices = [];
  30853. var positions = [];
  30854. var normals = [];
  30855. var uvs = [];
  30856. var diameter = options.diameter || 1;
  30857. var thickness = options.thickness || 0.5;
  30858. var tessellation = options.tessellation || 16;
  30859. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30860. var stride = tessellation + 1;
  30861. for (var i = 0; i <= tessellation; i++) {
  30862. var u = i / tessellation;
  30863. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30864. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30865. for (var j = 0; j <= tessellation; j++) {
  30866. var v = 1 - j / tessellation;
  30867. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30868. var dx = Math.cos(innerAngle);
  30869. var dy = Math.sin(innerAngle);
  30870. // Create a vertex.
  30871. var normal = new BABYLON.Vector3(dx, dy, 0);
  30872. var position = normal.scale(thickness / 2);
  30873. var textureCoordinate = new BABYLON.Vector2(u, v);
  30874. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30875. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30876. positions.push(position.x, position.y, position.z);
  30877. normals.push(normal.x, normal.y, normal.z);
  30878. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30879. // And create indices for two triangles.
  30880. var nextI = (i + 1) % stride;
  30881. var nextJ = (j + 1) % stride;
  30882. indices.push(i * stride + j);
  30883. indices.push(i * stride + nextJ);
  30884. indices.push(nextI * stride + j);
  30885. indices.push(i * stride + nextJ);
  30886. indices.push(nextI * stride + nextJ);
  30887. indices.push(nextI * stride + j);
  30888. }
  30889. }
  30890. // Sides
  30891. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30892. // Result
  30893. var vertexData = new VertexData();
  30894. vertexData.indices = indices;
  30895. vertexData.positions = positions;
  30896. vertexData.normals = normals;
  30897. vertexData.uvs = uvs;
  30898. return vertexData;
  30899. };
  30900. VertexData.CreateLineSystem = function (options) {
  30901. var indices = [];
  30902. var positions = [];
  30903. var lines = options.lines;
  30904. var idx = 0;
  30905. for (var l = 0; l < lines.length; l++) {
  30906. var points = lines[l];
  30907. for (var index = 0; index < points.length; index++) {
  30908. positions.push(points[index].x, points[index].y, points[index].z);
  30909. if (index > 0) {
  30910. indices.push(idx - 1);
  30911. indices.push(idx);
  30912. }
  30913. idx++;
  30914. }
  30915. }
  30916. var vertexData = new VertexData();
  30917. vertexData.indices = indices;
  30918. vertexData.positions = positions;
  30919. return vertexData;
  30920. };
  30921. VertexData.CreateDashedLines = function (options) {
  30922. var dashSize = options.dashSize || 3;
  30923. var gapSize = options.gapSize || 1;
  30924. var dashNb = options.dashNb || 200;
  30925. var points = options.points;
  30926. var positions = new Array();
  30927. var indices = new Array();
  30928. var curvect = BABYLON.Vector3.Zero();
  30929. var lg = 0;
  30930. var nb = 0;
  30931. var shft = 0;
  30932. var dashshft = 0;
  30933. var curshft = 0;
  30934. var idx = 0;
  30935. var i = 0;
  30936. for (i = 0; i < points.length - 1; i++) {
  30937. points[i + 1].subtractToRef(points[i], curvect);
  30938. lg += curvect.length();
  30939. }
  30940. shft = lg / dashNb;
  30941. dashshft = dashSize * shft / (dashSize + gapSize);
  30942. for (i = 0; i < points.length - 1; i++) {
  30943. points[i + 1].subtractToRef(points[i], curvect);
  30944. nb = Math.floor(curvect.length() / shft);
  30945. curvect.normalize();
  30946. for (var j = 0; j < nb; j++) {
  30947. curshft = shft * j;
  30948. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  30949. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  30950. indices.push(idx, idx + 1);
  30951. idx += 2;
  30952. }
  30953. }
  30954. // Result
  30955. var vertexData = new VertexData();
  30956. vertexData.positions = positions;
  30957. vertexData.indices = indices;
  30958. return vertexData;
  30959. };
  30960. VertexData.CreateGround = function (options) {
  30961. var indices = [];
  30962. var positions = [];
  30963. var normals = [];
  30964. var uvs = [];
  30965. var row, col;
  30966. var width = options.width || 1;
  30967. var height = options.height || 1;
  30968. var subdivisions = options.subdivisions || 1;
  30969. for (row = 0; row <= subdivisions; row++) {
  30970. for (col = 0; col <= subdivisions; col++) {
  30971. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  30972. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30973. positions.push(position.x, position.y, position.z);
  30974. normals.push(normal.x, normal.y, normal.z);
  30975. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  30976. }
  30977. }
  30978. for (row = 0; row < subdivisions; row++) {
  30979. for (col = 0; col < subdivisions; col++) {
  30980. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  30981. indices.push(col + 1 + row * (subdivisions + 1));
  30982. indices.push(col + row * (subdivisions + 1));
  30983. indices.push(col + (row + 1) * (subdivisions + 1));
  30984. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  30985. indices.push(col + row * (subdivisions + 1));
  30986. }
  30987. }
  30988. // Result
  30989. var vertexData = new VertexData();
  30990. vertexData.indices = indices;
  30991. vertexData.positions = positions;
  30992. vertexData.normals = normals;
  30993. vertexData.uvs = uvs;
  30994. return vertexData;
  30995. };
  30996. VertexData.CreateTiledGround = function (options) {
  30997. var xmin = options.xmin || -1.0;
  30998. var zmin = options.zmin || -1.0;
  30999. var xmax = options.xmax || 1.0;
  31000. var zmax = options.zmax || 1.0;
  31001. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  31002. var precision = options.precision || { w: 1, h: 1 };
  31003. var indices = [];
  31004. var positions = [];
  31005. var normals = [];
  31006. var uvs = [];
  31007. var row, col, tileRow, tileCol;
  31008. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  31009. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  31010. precision.w = (precision.w < 1) ? 1 : precision.w;
  31011. precision.h = (precision.h < 1) ? 1 : precision.h;
  31012. var tileSize = {
  31013. 'w': (xmax - xmin) / subdivisions.w,
  31014. 'h': (zmax - zmin) / subdivisions.h
  31015. };
  31016. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  31017. // Indices
  31018. var base = positions.length / 3;
  31019. var rowLength = precision.w + 1;
  31020. for (row = 0; row < precision.h; row++) {
  31021. for (col = 0; col < precision.w; col++) {
  31022. var square = [
  31023. base + col + row * rowLength,
  31024. base + (col + 1) + row * rowLength,
  31025. base + (col + 1) + (row + 1) * rowLength,
  31026. base + col + (row + 1) * rowLength
  31027. ];
  31028. indices.push(square[1]);
  31029. indices.push(square[2]);
  31030. indices.push(square[3]);
  31031. indices.push(square[0]);
  31032. indices.push(square[1]);
  31033. indices.push(square[3]);
  31034. }
  31035. }
  31036. // Position, normals and uvs
  31037. var position = BABYLON.Vector3.Zero();
  31038. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31039. for (row = 0; row <= precision.h; row++) {
  31040. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  31041. for (col = 0; col <= precision.w; col++) {
  31042. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  31043. position.y = 0;
  31044. positions.push(position.x, position.y, position.z);
  31045. normals.push(normal.x, normal.y, normal.z);
  31046. uvs.push(col / precision.w, row / precision.h);
  31047. }
  31048. }
  31049. }
  31050. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  31051. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  31052. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  31053. }
  31054. }
  31055. // Result
  31056. var vertexData = new VertexData();
  31057. vertexData.indices = indices;
  31058. vertexData.positions = positions;
  31059. vertexData.normals = normals;
  31060. vertexData.uvs = uvs;
  31061. return vertexData;
  31062. };
  31063. VertexData.CreateGroundFromHeightMap = function (options) {
  31064. var indices = [];
  31065. var positions = [];
  31066. var normals = [];
  31067. var uvs = [];
  31068. var row, col;
  31069. // Vertices
  31070. for (row = 0; row <= options.subdivisions; row++) {
  31071. for (col = 0; col <= options.subdivisions; col++) {
  31072. 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));
  31073. // Compute height
  31074. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  31075. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  31076. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  31077. var r = options.buffer[pos] / 255.0;
  31078. var g = options.buffer[pos + 1] / 255.0;
  31079. var b = options.buffer[pos + 2] / 255.0;
  31080. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  31081. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  31082. // Add vertex
  31083. positions.push(position.x, position.y, position.z);
  31084. normals.push(0, 0, 0);
  31085. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  31086. }
  31087. }
  31088. // Indices
  31089. for (row = 0; row < options.subdivisions; row++) {
  31090. for (col = 0; col < options.subdivisions; col++) {
  31091. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31092. indices.push(col + 1 + row * (options.subdivisions + 1));
  31093. indices.push(col + row * (options.subdivisions + 1));
  31094. indices.push(col + (row + 1) * (options.subdivisions + 1));
  31095. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31096. indices.push(col + row * (options.subdivisions + 1));
  31097. }
  31098. }
  31099. // Normals
  31100. VertexData.ComputeNormals(positions, indices, normals);
  31101. // Result
  31102. var vertexData = new VertexData();
  31103. vertexData.indices = indices;
  31104. vertexData.positions = positions;
  31105. vertexData.normals = normals;
  31106. vertexData.uvs = uvs;
  31107. return vertexData;
  31108. };
  31109. VertexData.CreatePlane = function (options) {
  31110. var indices = [];
  31111. var positions = [];
  31112. var normals = [];
  31113. var uvs = [];
  31114. var width = options.width || options.size || 1;
  31115. var height = options.height || options.size || 1;
  31116. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31117. // Vertices
  31118. var halfWidth = width / 2.0;
  31119. var halfHeight = height / 2.0;
  31120. positions.push(-halfWidth, -halfHeight, 0);
  31121. normals.push(0, 0, -1.0);
  31122. uvs.push(0.0, 0.0);
  31123. positions.push(halfWidth, -halfHeight, 0);
  31124. normals.push(0, 0, -1.0);
  31125. uvs.push(1.0, 0.0);
  31126. positions.push(halfWidth, halfHeight, 0);
  31127. normals.push(0, 0, -1.0);
  31128. uvs.push(1.0, 1.0);
  31129. positions.push(-halfWidth, halfHeight, 0);
  31130. normals.push(0, 0, -1.0);
  31131. uvs.push(0.0, 1.0);
  31132. // Indices
  31133. indices.push(0);
  31134. indices.push(1);
  31135. indices.push(2);
  31136. indices.push(0);
  31137. indices.push(2);
  31138. indices.push(3);
  31139. // Sides
  31140. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31141. // Result
  31142. var vertexData = new VertexData();
  31143. vertexData.indices = indices;
  31144. vertexData.positions = positions;
  31145. vertexData.normals = normals;
  31146. vertexData.uvs = uvs;
  31147. return vertexData;
  31148. };
  31149. VertexData.CreateDisc = function (options) {
  31150. var positions = [];
  31151. var indices = [];
  31152. var normals = [];
  31153. var uvs = [];
  31154. var radius = options.radius || 0.5;
  31155. var tessellation = options.tessellation || 64;
  31156. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31157. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31158. // positions and uvs
  31159. positions.push(0, 0, 0); // disc center first
  31160. uvs.push(0.5, 0.5);
  31161. var theta = Math.PI * 2 * arc;
  31162. var step = theta / tessellation;
  31163. for (var a = 0; a < theta; a += step) {
  31164. var x = Math.cos(a);
  31165. var y = Math.sin(a);
  31166. var u = (x + 1) / 2;
  31167. var v = (1 - y) / 2;
  31168. positions.push(radius * x, radius * y, 0);
  31169. uvs.push(u, v);
  31170. }
  31171. if (arc === 1) {
  31172. positions.push(positions[3], positions[4], positions[5]); // close the circle
  31173. uvs.push(uvs[2], uvs[3]);
  31174. }
  31175. //indices
  31176. var vertexNb = positions.length / 3;
  31177. for (var i = 1; i < vertexNb - 1; i++) {
  31178. indices.push(i + 1, 0, i);
  31179. }
  31180. // result
  31181. VertexData.ComputeNormals(positions, indices, normals);
  31182. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31183. var vertexData = new VertexData();
  31184. vertexData.indices = indices;
  31185. vertexData.positions = positions;
  31186. vertexData.normals = normals;
  31187. vertexData.uvs = uvs;
  31188. return vertexData;
  31189. };
  31190. VertexData.CreateIcoSphere = function (options) {
  31191. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31192. var radius = options.radius || 1;
  31193. var flat = (options.flat === undefined) ? true : options.flat;
  31194. var subdivisions = options.subdivisions || 4;
  31195. var radiusX = options.radiusX || radius;
  31196. var radiusY = options.radiusY || radius;
  31197. var radiusZ = options.radiusZ || radius;
  31198. var t = (1 + Math.sqrt(5)) / 2;
  31199. // 12 vertex x,y,z
  31200. var ico_vertices = [
  31201. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  31202. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  31203. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  31204. ];
  31205. // index of 3 vertex makes a face of icopshere
  31206. var ico_indices = [
  31207. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  31208. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  31209. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  31210. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  31211. ];
  31212. // vertex for uv have aliased position, not for UV
  31213. var vertices_unalias_id = [
  31214. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  31215. // vertex alias
  31216. 0,
  31217. 2,
  31218. 3,
  31219. 3,
  31220. 3,
  31221. 4,
  31222. 7,
  31223. 8,
  31224. 9,
  31225. 9,
  31226. 10,
  31227. 11 // 23: B + 12
  31228. ];
  31229. // uv as integer step (not pixels !)
  31230. var ico_vertexuv = [
  31231. 5, 1, 3, 1, 6, 4, 0, 0,
  31232. 5, 3, 4, 2, 2, 2, 4, 0,
  31233. 2, 0, 1, 1, 6, 0, 6, 2,
  31234. // vertex alias (for same vertex on different faces)
  31235. 0, 4,
  31236. 3, 3,
  31237. 4, 4,
  31238. 3, 1,
  31239. 4, 2,
  31240. 4, 4,
  31241. 0, 2,
  31242. 1, 1,
  31243. 2, 2,
  31244. 3, 3,
  31245. 1, 3,
  31246. 2, 4 // 23: B + 12
  31247. ];
  31248. // Vertices[0, 1, ...9, A, B] : position on UV plane
  31249. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  31250. // First island of uv mapping
  31251. // v = 4h 3+ 2
  31252. // v = 3h 9+ 4
  31253. // v = 2h 9+ 5 B
  31254. // v = 1h 9 1 0
  31255. // v = 0h 3 8 7 A
  31256. // u = 0 1 2 3 4 5 6 *a
  31257. // Second island of uv mapping
  31258. // v = 4h 0+ B+ 4+
  31259. // v = 3h A+ 2+
  31260. // v = 2h 7+ 6 3+
  31261. // v = 1h 8+ 3+
  31262. // v = 0h
  31263. // u = 0 1 2 3 4 5 6 *a
  31264. // Face layout on texture UV mapping
  31265. // ============
  31266. // \ 4 /\ 16 / ======
  31267. // \ / \ / /\ 11 /
  31268. // \/ 7 \/ / \ /
  31269. // ======= / 10 \/
  31270. // /\ 17 /\ =======
  31271. // / \ / \ \ 15 /\
  31272. // / 8 \/ 12 \ \ / \
  31273. // ============ \/ 6 \
  31274. // \ 18 /\ ============
  31275. // \ / \ \ 5 /\ 0 /
  31276. // \/ 13 \ \ / \ /
  31277. // ======= \/ 1 \/
  31278. // =============
  31279. // /\ 19 /\ 2 /\
  31280. // / \ / \ / \
  31281. // / 14 \/ 9 \/ 3 \
  31282. // ===================
  31283. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  31284. var ustep = 138 / 1024;
  31285. var vstep = 239 / 1024;
  31286. var uoffset = 60 / 1024;
  31287. var voffset = 26 / 1024;
  31288. // Second island should have margin, not to touch the first island
  31289. // avoid any borderline artefact in pixel rounding
  31290. var island_u_offset = -40 / 1024;
  31291. var island_v_offset = +20 / 1024;
  31292. // face is either island 0 or 1 :
  31293. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  31294. var island = [
  31295. 0, 0, 0, 0, 1,
  31296. 0, 0, 1, 1, 0,
  31297. 0, 0, 1, 1, 0,
  31298. 0, 1, 1, 1, 0 // 15 - 19
  31299. ];
  31300. var indices = [];
  31301. var positions = [];
  31302. var normals = [];
  31303. var uvs = [];
  31304. var current_indice = 0;
  31305. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  31306. var face_vertex_pos = new Array(3);
  31307. var face_vertex_uv = new Array(3);
  31308. var v012;
  31309. for (v012 = 0; v012 < 3; v012++) {
  31310. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  31311. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  31312. }
  31313. // create all with normals
  31314. for (var face = 0; face < 20; face++) {
  31315. // 3 vertex per face
  31316. for (v012 = 0; v012 < 3; v012++) {
  31317. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  31318. var v_id = ico_indices[3 * face + v012];
  31319. // vertex have 3D position (x,y,z)
  31320. 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]);
  31321. // Normalize to get normal, then scale to radius
  31322. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  31323. // uv Coordinates from vertex ID
  31324. 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);
  31325. }
  31326. // Subdivide the face (interpolate pos, norm, uv)
  31327. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  31328. // - norm is linear interpolation of vertex corner normal
  31329. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  31330. // - uv is linear interpolation
  31331. //
  31332. // Topology is as below for sub-divide by 2
  31333. // vertex shown as v0,v1,v2
  31334. // interp index is i1 to progress in range [v0,v1[
  31335. // interp index is i2 to progress in range [v0,v2[
  31336. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  31337. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31338. //
  31339. //
  31340. // i2 v2
  31341. // ^ ^
  31342. // / / \
  31343. // / / \
  31344. // / / \
  31345. // / / (0,1) \
  31346. // / #---------\
  31347. // / / \ (0,0)'/ \
  31348. // / / \ / \
  31349. // / / \ / \
  31350. // / / (0,0) \ / (1,0) \
  31351. // / #---------#---------\
  31352. // v0 v1
  31353. //
  31354. // --------------------> i1
  31355. //
  31356. // interp of (i1,i2):
  31357. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  31358. // along i1 : lerp(x0,x1, i1/(S-i2))
  31359. //
  31360. // centroid of triangle is needed to get help normal computation
  31361. // (c1,c2) are used for centroid location
  31362. var interp_vertex = function (i1, i2, c1, c2) {
  31363. // vertex is interpolated from
  31364. // - face_vertex_pos[0..2]
  31365. // - face_vertex_uv[0..2]
  31366. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  31367. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  31368. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  31369. pos_interp.normalize();
  31370. var vertex_normal;
  31371. if (flat) {
  31372. // in flat mode, recalculate normal as face centroid normal
  31373. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  31374. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  31375. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  31376. }
  31377. else {
  31378. // in smooth mode, recalculate normal from each single vertex position
  31379. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  31380. }
  31381. // Vertex normal need correction due to X,Y,Z radius scaling
  31382. vertex_normal.x /= radiusX;
  31383. vertex_normal.y /= radiusY;
  31384. vertex_normal.z /= radiusZ;
  31385. vertex_normal.normalize();
  31386. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  31387. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  31388. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  31389. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  31390. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  31391. uvs.push(uv_interp.x, uv_interp.y);
  31392. // push each vertex has member of a face
  31393. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  31394. indices.push(current_indice);
  31395. current_indice++;
  31396. };
  31397. for (var i2 = 0; i2 < subdivisions; i2++) {
  31398. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  31399. // face : (i1,i2) for /\ :
  31400. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  31401. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31402. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31403. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31404. if (i1 + i2 + 1 < subdivisions) {
  31405. // face : (i1,i2)' for \/ :
  31406. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31407. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31408. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31409. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31410. }
  31411. }
  31412. }
  31413. }
  31414. // Sides
  31415. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31416. // Result
  31417. var vertexData = new VertexData();
  31418. vertexData.indices = indices;
  31419. vertexData.positions = positions;
  31420. vertexData.normals = normals;
  31421. vertexData.uvs = uvs;
  31422. return vertexData;
  31423. };
  31424. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  31425. VertexData.CreatePolyhedron = function (options) {
  31426. // provided polyhedron types :
  31427. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  31428. // 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)
  31429. var polyhedra = [];
  31430. 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]] };
  31431. 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]] };
  31432. polyhedra[2] = {
  31433. 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]],
  31434. 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]]
  31435. };
  31436. polyhedra[3] = {
  31437. 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]],
  31438. 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]]
  31439. };
  31440. polyhedra[4] = {
  31441. 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]],
  31442. 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]]
  31443. };
  31444. 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]] };
  31445. 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]] };
  31446. 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]] };
  31447. 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]] };
  31448. 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]] };
  31449. 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]] };
  31450. 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]] };
  31451. 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]] };
  31452. 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]] };
  31453. polyhedra[14] = {
  31454. 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]],
  31455. 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]]
  31456. };
  31457. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  31458. var size = options.size;
  31459. var sizeX = options.sizeX || size || 1;
  31460. var sizeY = options.sizeY || size || 1;
  31461. var sizeZ = options.sizeZ || size || 1;
  31462. var data = options.custom || polyhedra[type];
  31463. var nbfaces = data.face.length;
  31464. var faceUV = options.faceUV || new Array(nbfaces);
  31465. var faceColors = options.faceColors;
  31466. var flat = (options.flat === undefined) ? true : options.flat;
  31467. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31468. var positions = [];
  31469. var indices = [];
  31470. var normals = [];
  31471. var uvs = [];
  31472. var colors = [];
  31473. var index = 0;
  31474. var faceIdx = 0; // face cursor in the array "indexes"
  31475. var indexes = [];
  31476. var i = 0;
  31477. var f = 0;
  31478. var u, v, ang, x, y, tmp;
  31479. // default face colors and UV if undefined
  31480. if (flat) {
  31481. for (f = 0; f < nbfaces; f++) {
  31482. if (faceColors && faceColors[f] === undefined) {
  31483. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31484. }
  31485. if (faceUV && faceUV[f] === undefined) {
  31486. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31487. }
  31488. }
  31489. }
  31490. if (!flat) {
  31491. for (i = 0; i < data.vertex.length; i++) {
  31492. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  31493. uvs.push(0, 0);
  31494. }
  31495. for (f = 0; f < nbfaces; f++) {
  31496. for (i = 0; i < data.face[f].length - 2; i++) {
  31497. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  31498. }
  31499. }
  31500. }
  31501. else {
  31502. for (f = 0; f < nbfaces; f++) {
  31503. var fl = data.face[f].length; // number of vertices of the current face
  31504. ang = 2 * Math.PI / fl;
  31505. x = 0.5 * Math.tan(ang / 2);
  31506. y = 0.5;
  31507. // positions, uvs, colors
  31508. for (i = 0; i < fl; i++) {
  31509. // positions
  31510. 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);
  31511. indexes.push(index);
  31512. index++;
  31513. // uvs
  31514. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  31515. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  31516. uvs.push(u, v);
  31517. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  31518. y = x * Math.sin(ang) + y * Math.cos(ang);
  31519. x = tmp;
  31520. // colors
  31521. if (faceColors) {
  31522. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  31523. }
  31524. }
  31525. // indices from indexes
  31526. for (i = 0; i < fl - 2; i++) {
  31527. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  31528. }
  31529. faceIdx += fl;
  31530. }
  31531. }
  31532. VertexData.ComputeNormals(positions, indices, normals);
  31533. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31534. var vertexData = new VertexData();
  31535. vertexData.positions = positions;
  31536. vertexData.indices = indices;
  31537. vertexData.normals = normals;
  31538. vertexData.uvs = uvs;
  31539. if (faceColors && flat) {
  31540. vertexData.colors = colors;
  31541. }
  31542. return vertexData;
  31543. };
  31544. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  31545. VertexData.CreateTorusKnot = function (options) {
  31546. var indices = [];
  31547. var positions = [];
  31548. var normals = [];
  31549. var uvs = [];
  31550. var radius = options.radius || 2;
  31551. var tube = options.tube || 0.5;
  31552. var radialSegments = options.radialSegments || 32;
  31553. var tubularSegments = options.tubularSegments || 32;
  31554. var p = options.p || 2;
  31555. var q = options.q || 3;
  31556. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31557. // Helper
  31558. var getPos = function (angle) {
  31559. var cu = Math.cos(angle);
  31560. var su = Math.sin(angle);
  31561. var quOverP = q / p * angle;
  31562. var cs = Math.cos(quOverP);
  31563. var tx = radius * (2 + cs) * 0.5 * cu;
  31564. var ty = radius * (2 + cs) * su * 0.5;
  31565. var tz = radius * Math.sin(quOverP) * 0.5;
  31566. return new BABYLON.Vector3(tx, ty, tz);
  31567. };
  31568. // Vertices
  31569. var i;
  31570. var j;
  31571. for (i = 0; i <= radialSegments; i++) {
  31572. var modI = i % radialSegments;
  31573. var u = modI / radialSegments * 2 * p * Math.PI;
  31574. var p1 = getPos(u);
  31575. var p2 = getPos(u + 0.01);
  31576. var tang = p2.subtract(p1);
  31577. var n = p2.add(p1);
  31578. var bitan = BABYLON.Vector3.Cross(tang, n);
  31579. n = BABYLON.Vector3.Cross(bitan, tang);
  31580. bitan.normalize();
  31581. n.normalize();
  31582. for (j = 0; j < tubularSegments; j++) {
  31583. var modJ = j % tubularSegments;
  31584. var v = modJ / tubularSegments * 2 * Math.PI;
  31585. var cx = -tube * Math.cos(v);
  31586. var cy = tube * Math.sin(v);
  31587. positions.push(p1.x + cx * n.x + cy * bitan.x);
  31588. positions.push(p1.y + cx * n.y + cy * bitan.y);
  31589. positions.push(p1.z + cx * n.z + cy * bitan.z);
  31590. uvs.push(i / radialSegments);
  31591. uvs.push(j / tubularSegments);
  31592. }
  31593. }
  31594. for (i = 0; i < radialSegments; i++) {
  31595. for (j = 0; j < tubularSegments; j++) {
  31596. var jNext = (j + 1) % tubularSegments;
  31597. var a = i * tubularSegments + j;
  31598. var b = (i + 1) * tubularSegments + j;
  31599. var c = (i + 1) * tubularSegments + jNext;
  31600. var d = i * tubularSegments + jNext;
  31601. indices.push(d);
  31602. indices.push(b);
  31603. indices.push(a);
  31604. indices.push(d);
  31605. indices.push(c);
  31606. indices.push(b);
  31607. }
  31608. }
  31609. // Normals
  31610. VertexData.ComputeNormals(positions, indices, normals);
  31611. // Sides
  31612. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31613. // Result
  31614. var vertexData = new VertexData();
  31615. vertexData.indices = indices;
  31616. vertexData.positions = positions;
  31617. vertexData.normals = normals;
  31618. vertexData.uvs = uvs;
  31619. return vertexData;
  31620. };
  31621. // Tools
  31622. /**
  31623. * @param {any} - positions (number[] or Float32Array)
  31624. * @param {any} - indices (number[] or Uint16Array)
  31625. * @param {any} - normals (number[] or Float32Array)
  31626. */
  31627. VertexData.ComputeNormals = function (positions, indices, normals) {
  31628. var index = 0;
  31629. var p1p2x = 0.0;
  31630. var p1p2y = 0.0;
  31631. var p1p2z = 0.0;
  31632. var p3p2x = 0.0;
  31633. var p3p2y = 0.0;
  31634. var p3p2z = 0.0;
  31635. var faceNormalx = 0.0;
  31636. var faceNormaly = 0.0;
  31637. var faceNormalz = 0.0;
  31638. var length = 0.0;
  31639. var i1 = 0;
  31640. var i2 = 0;
  31641. var i3 = 0;
  31642. for (index = 0; index < positions.length; index++) {
  31643. normals[index] = 0.0;
  31644. }
  31645. // indice triplet = 1 face
  31646. var nbFaces = indices.length / 3;
  31647. for (index = 0; index < nbFaces; index++) {
  31648. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  31649. i2 = indices[index * 3 + 1];
  31650. i3 = indices[index * 3 + 2];
  31651. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  31652. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  31653. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  31654. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  31655. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  31656. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  31657. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  31658. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  31659. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  31660. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31661. length = (length === 0) ? 1.0 : length;
  31662. faceNormalx /= length; // normalize this normal
  31663. faceNormaly /= length;
  31664. faceNormalz /= length;
  31665. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  31666. normals[i1 * 3 + 1] += faceNormaly;
  31667. normals[i1 * 3 + 2] += faceNormalz;
  31668. normals[i2 * 3] += faceNormalx;
  31669. normals[i2 * 3 + 1] += faceNormaly;
  31670. normals[i2 * 3 + 2] += faceNormalz;
  31671. normals[i3 * 3] += faceNormalx;
  31672. normals[i3 * 3 + 1] += faceNormaly;
  31673. normals[i3 * 3 + 2] += faceNormalz;
  31674. }
  31675. // last normalization of each normal
  31676. for (index = 0; index < normals.length / 3; index++) {
  31677. faceNormalx = normals[index * 3];
  31678. faceNormaly = normals[index * 3 + 1];
  31679. faceNormalz = normals[index * 3 + 2];
  31680. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31681. length = (length === 0) ? 1.0 : length;
  31682. faceNormalx /= length;
  31683. faceNormaly /= length;
  31684. faceNormalz /= length;
  31685. normals[index * 3] = faceNormalx;
  31686. normals[index * 3 + 1] = faceNormaly;
  31687. normals[index * 3 + 2] = faceNormalz;
  31688. }
  31689. };
  31690. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  31691. var li = indices.length;
  31692. var ln = normals.length;
  31693. var i;
  31694. var n;
  31695. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31696. switch (sideOrientation) {
  31697. case BABYLON.Mesh.FRONTSIDE:
  31698. // nothing changed
  31699. break;
  31700. case BABYLON.Mesh.BACKSIDE:
  31701. var tmp;
  31702. // indices
  31703. for (i = 0; i < li; i += 3) {
  31704. tmp = indices[i];
  31705. indices[i] = indices[i + 2];
  31706. indices[i + 2] = tmp;
  31707. }
  31708. // normals
  31709. for (n = 0; n < ln; n++) {
  31710. normals[n] = -normals[n];
  31711. }
  31712. break;
  31713. case BABYLON.Mesh.DOUBLESIDE:
  31714. // positions
  31715. var lp = positions.length;
  31716. var l = lp / 3;
  31717. for (var p = 0; p < lp; p++) {
  31718. positions[lp + p] = positions[p];
  31719. }
  31720. // indices
  31721. for (i = 0; i < li; i += 3) {
  31722. indices[i + li] = indices[i + 2] + l;
  31723. indices[i + 1 + li] = indices[i + 1] + l;
  31724. indices[i + 2 + li] = indices[i] + l;
  31725. }
  31726. // normals
  31727. for (n = 0; n < ln; n++) {
  31728. normals[ln + n] = -normals[n];
  31729. }
  31730. // uvs
  31731. var lu = uvs.length;
  31732. for (var u = 0; u < lu; u++) {
  31733. uvs[u + lu] = uvs[u];
  31734. }
  31735. break;
  31736. }
  31737. };
  31738. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  31739. var vertexData = new VertexData();
  31740. // positions
  31741. var positions = parsedVertexData.positions;
  31742. if (positions) {
  31743. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  31744. }
  31745. // normals
  31746. var normals = parsedVertexData.normals;
  31747. if (normals) {
  31748. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  31749. }
  31750. // uvs
  31751. var uvs = parsedVertexData.uvs;
  31752. if (uvs) {
  31753. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  31754. }
  31755. // uv2s
  31756. var uv2s = parsedVertexData.uv2s;
  31757. if (uv2s) {
  31758. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  31759. }
  31760. // uv3s
  31761. var uv3s = parsedVertexData.uv3s;
  31762. if (uv3s) {
  31763. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  31764. }
  31765. // uv4s
  31766. var uv4s = parsedVertexData.uv4s;
  31767. if (uv4s) {
  31768. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  31769. }
  31770. // uv5s
  31771. var uv5s = parsedVertexData.uv5s;
  31772. if (uv5s) {
  31773. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  31774. }
  31775. // uv6s
  31776. var uv6s = parsedVertexData.uv6s;
  31777. if (uv6s) {
  31778. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  31779. }
  31780. // colors
  31781. var colors = parsedVertexData.colors;
  31782. if (colors) {
  31783. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  31784. }
  31785. // matricesIndices
  31786. var matricesIndices = parsedVertexData.matricesIndices;
  31787. if (matricesIndices) {
  31788. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  31789. }
  31790. // matricesWeights
  31791. var matricesWeights = parsedVertexData.matricesWeights;
  31792. if (matricesWeights) {
  31793. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  31794. }
  31795. // indices
  31796. var indices = parsedVertexData.indices;
  31797. if (indices) {
  31798. vertexData.indices = indices;
  31799. }
  31800. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  31801. };
  31802. return VertexData;
  31803. })();
  31804. BABYLON.VertexData = VertexData;
  31805. })(BABYLON || (BABYLON = {}));
  31806. var BABYLON;
  31807. (function (BABYLON) {
  31808. var Tags = (function () {
  31809. function Tags() {
  31810. }
  31811. Tags.EnableFor = function (obj) {
  31812. obj._tags = obj._tags || {};
  31813. obj.hasTags = function () {
  31814. return Tags.HasTags(obj);
  31815. };
  31816. obj.addTags = function (tagsString) {
  31817. return Tags.AddTagsTo(obj, tagsString);
  31818. };
  31819. obj.removeTags = function (tagsString) {
  31820. return Tags.RemoveTagsFrom(obj, tagsString);
  31821. };
  31822. obj.matchesTagsQuery = function (tagsQuery) {
  31823. return Tags.MatchesQuery(obj, tagsQuery);
  31824. };
  31825. };
  31826. Tags.DisableFor = function (obj) {
  31827. delete obj._tags;
  31828. delete obj.hasTags;
  31829. delete obj.addTags;
  31830. delete obj.removeTags;
  31831. delete obj.matchesTagsQuery;
  31832. };
  31833. Tags.HasTags = function (obj) {
  31834. if (!obj._tags) {
  31835. return false;
  31836. }
  31837. return !BABYLON.Tools.IsEmpty(obj._tags);
  31838. };
  31839. Tags.GetTags = function (obj, asString) {
  31840. if (asString === void 0) { asString = true; }
  31841. if (!obj._tags) {
  31842. return null;
  31843. }
  31844. if (asString) {
  31845. var tagsArray = [];
  31846. for (var tag in obj._tags) {
  31847. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  31848. tagsArray.push(tag);
  31849. }
  31850. }
  31851. return tagsArray.join(" ");
  31852. }
  31853. else {
  31854. return obj._tags;
  31855. }
  31856. };
  31857. // the tags 'true' and 'false' are reserved and cannot be used as tags
  31858. // a tag cannot start with '||', '&&', and '!'
  31859. // it cannot contain whitespaces
  31860. Tags.AddTagsTo = function (obj, tagsString) {
  31861. if (!tagsString) {
  31862. return;
  31863. }
  31864. if (typeof tagsString !== "string") {
  31865. return;
  31866. }
  31867. var tags = tagsString.split(" ");
  31868. for (var t in tags) {
  31869. Tags._AddTagTo(obj, tags[t]);
  31870. }
  31871. };
  31872. Tags._AddTagTo = function (obj, tag) {
  31873. tag = tag.trim();
  31874. if (tag === "" || tag === "true" || tag === "false") {
  31875. return;
  31876. }
  31877. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  31878. return;
  31879. }
  31880. Tags.EnableFor(obj);
  31881. obj._tags[tag] = true;
  31882. };
  31883. Tags.RemoveTagsFrom = function (obj, tagsString) {
  31884. if (!Tags.HasTags(obj)) {
  31885. return;
  31886. }
  31887. var tags = tagsString.split(" ");
  31888. for (var t in tags) {
  31889. Tags._RemoveTagFrom(obj, tags[t]);
  31890. }
  31891. };
  31892. Tags._RemoveTagFrom = function (obj, tag) {
  31893. delete obj._tags[tag];
  31894. };
  31895. Tags.MatchesQuery = function (obj, tagsQuery) {
  31896. if (tagsQuery === undefined) {
  31897. return true;
  31898. }
  31899. if (tagsQuery === "") {
  31900. return Tags.HasTags(obj);
  31901. }
  31902. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  31903. };
  31904. return Tags;
  31905. })();
  31906. BABYLON.Tags = Tags;
  31907. })(BABYLON || (BABYLON = {}));
  31908. var BABYLON;
  31909. (function (BABYLON) {
  31910. var Internals;
  31911. (function (Internals) {
  31912. var AndOrNotEvaluator = (function () {
  31913. function AndOrNotEvaluator() {
  31914. }
  31915. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  31916. if (!query.match(/\([^\(\)]*\)/g)) {
  31917. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  31918. }
  31919. else {
  31920. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  31921. // remove parenthesis
  31922. r = r.slice(1, r.length - 1);
  31923. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  31924. });
  31925. }
  31926. if (query === "true") {
  31927. return true;
  31928. }
  31929. if (query === "false") {
  31930. return false;
  31931. }
  31932. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  31933. };
  31934. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  31935. evaluateCallback = evaluateCallback || (function (r) {
  31936. return r === "true" ? true : false;
  31937. });
  31938. var result;
  31939. var or = parenthesisContent.split("||");
  31940. for (var i in or) {
  31941. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  31942. var and = ori.split("&&");
  31943. if (and.length > 1) {
  31944. for (var j = 0; j < and.length; ++j) {
  31945. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  31946. if (andj !== "true" && andj !== "false") {
  31947. if (andj[0] === "!") {
  31948. result = !evaluateCallback(andj.substring(1));
  31949. }
  31950. else {
  31951. result = evaluateCallback(andj);
  31952. }
  31953. }
  31954. else {
  31955. result = andj === "true" ? true : false;
  31956. }
  31957. if (!result) {
  31958. ori = "false";
  31959. break;
  31960. }
  31961. }
  31962. }
  31963. if (result || ori === "true") {
  31964. result = true;
  31965. break;
  31966. }
  31967. // result equals false (or undefined)
  31968. if (ori !== "true" && ori !== "false") {
  31969. if (ori[0] === "!") {
  31970. result = !evaluateCallback(ori.substring(1));
  31971. }
  31972. else {
  31973. result = evaluateCallback(ori);
  31974. }
  31975. }
  31976. else {
  31977. result = ori === "true" ? true : false;
  31978. }
  31979. }
  31980. // the whole parenthesis scope is replaced by 'true' or 'false'
  31981. return result ? "true" : "false";
  31982. };
  31983. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  31984. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  31985. // remove whitespaces
  31986. r = r.replace(/[\s]/g, function () { return ""; });
  31987. return r.length % 2 ? "!" : "";
  31988. });
  31989. booleanString = booleanString.trim();
  31990. if (booleanString === "!true") {
  31991. booleanString = "false";
  31992. }
  31993. else if (booleanString === "!false") {
  31994. booleanString = "true";
  31995. }
  31996. return booleanString;
  31997. };
  31998. return AndOrNotEvaluator;
  31999. })();
  32000. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  32001. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32002. })(BABYLON || (BABYLON = {}));
  32003. var BABYLON;
  32004. (function (BABYLON) {
  32005. var PostProcessRenderPass = (function () {
  32006. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  32007. this._enabled = true;
  32008. this._refCount = 0;
  32009. this._name = name;
  32010. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  32011. this.setRenderList(renderList);
  32012. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  32013. this._renderTexture.onAfterRenderObservable.add(afterRender);
  32014. this._scene = scene;
  32015. this._renderList = renderList;
  32016. }
  32017. // private
  32018. PostProcessRenderPass.prototype._incRefCount = function () {
  32019. if (this._refCount === 0) {
  32020. this._scene.customRenderTargets.push(this._renderTexture);
  32021. }
  32022. return ++this._refCount;
  32023. };
  32024. PostProcessRenderPass.prototype._decRefCount = function () {
  32025. this._refCount--;
  32026. if (this._refCount <= 0) {
  32027. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  32028. }
  32029. return this._refCount;
  32030. };
  32031. PostProcessRenderPass.prototype._update = function () {
  32032. this.setRenderList(this._renderList);
  32033. };
  32034. // public
  32035. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  32036. this._renderTexture.renderList = renderList;
  32037. };
  32038. PostProcessRenderPass.prototype.getRenderTexture = function () {
  32039. return this._renderTexture;
  32040. };
  32041. return PostProcessRenderPass;
  32042. })();
  32043. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  32044. })(BABYLON || (BABYLON = {}));
  32045. var BABYLON;
  32046. (function (BABYLON) {
  32047. var PostProcessRenderEffect = (function () {
  32048. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  32049. this._engine = engine;
  32050. this._name = name;
  32051. this._singleInstance = singleInstance || true;
  32052. this._getPostProcess = getPostProcess;
  32053. this._cameras = [];
  32054. this._indicesForCamera = [];
  32055. this._postProcesses = {};
  32056. this._renderPasses = {};
  32057. this._renderEffectAsPasses = {};
  32058. }
  32059. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  32060. get: function () {
  32061. for (var index in this._postProcesses) {
  32062. if (!this._postProcesses[index].isSupported) {
  32063. return false;
  32064. }
  32065. }
  32066. return true;
  32067. },
  32068. enumerable: true,
  32069. configurable: true
  32070. });
  32071. PostProcessRenderEffect.prototype._update = function () {
  32072. for (var renderPassName in this._renderPasses) {
  32073. this._renderPasses[renderPassName]._update();
  32074. }
  32075. };
  32076. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  32077. this._renderPasses[renderPass._name] = renderPass;
  32078. this._linkParameters();
  32079. };
  32080. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  32081. delete this._renderPasses[renderPass._name];
  32082. this._linkParameters();
  32083. };
  32084. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  32085. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  32086. this._linkParameters();
  32087. };
  32088. PostProcessRenderEffect.prototype.getPass = function (passName) {
  32089. for (var renderPassName in this._renderPasses) {
  32090. if (renderPassName === passName) {
  32091. return this._renderPasses[passName];
  32092. }
  32093. }
  32094. };
  32095. PostProcessRenderEffect.prototype.emptyPasses = function () {
  32096. this._renderPasses = {};
  32097. this._linkParameters();
  32098. };
  32099. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  32100. var cameraKey;
  32101. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32102. for (var i = 0; i < _cam.length; i++) {
  32103. var camera = _cam[i];
  32104. var cameraName = camera.name;
  32105. if (this._singleInstance) {
  32106. cameraKey = 0;
  32107. }
  32108. else {
  32109. cameraKey = cameraName;
  32110. }
  32111. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  32112. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  32113. if (!this._indicesForCamera[cameraName]) {
  32114. this._indicesForCamera[cameraName] = [];
  32115. }
  32116. this._indicesForCamera[cameraName].push(index);
  32117. if (this._cameras.indexOf(camera) === -1) {
  32118. this._cameras[cameraName] = camera;
  32119. }
  32120. for (var passName in this._renderPasses) {
  32121. this._renderPasses[passName]._incRefCount();
  32122. }
  32123. }
  32124. this._linkParameters();
  32125. };
  32126. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  32127. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32128. for (var i = 0; i < _cam.length; i++) {
  32129. var camera = _cam[i];
  32130. var cameraName = camera.name;
  32131. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  32132. var index = this._cameras.indexOf(cameraName);
  32133. this._indicesForCamera.splice(index, 1);
  32134. this._cameras.splice(index, 1);
  32135. for (var passName in this._renderPasses) {
  32136. this._renderPasses[passName]._decRefCount();
  32137. }
  32138. }
  32139. };
  32140. PostProcessRenderEffect.prototype._enable = function (cameras) {
  32141. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32142. for (var i = 0; i < _cam.length; i++) {
  32143. var camera = _cam[i];
  32144. var cameraName = camera.name;
  32145. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  32146. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  32147. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  32148. }
  32149. }
  32150. for (var passName in this._renderPasses) {
  32151. this._renderPasses[passName]._incRefCount();
  32152. }
  32153. }
  32154. };
  32155. PostProcessRenderEffect.prototype._disable = function (cameras) {
  32156. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32157. for (var i = 0; i < _cam.length; i++) {
  32158. var camera = _cam[i];
  32159. var cameraName = camera.Name;
  32160. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  32161. for (var passName in this._renderPasses) {
  32162. this._renderPasses[passName]._decRefCount();
  32163. }
  32164. }
  32165. };
  32166. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  32167. if (this._singleInstance) {
  32168. return this._postProcesses[0];
  32169. }
  32170. else {
  32171. return this._postProcesses[camera.name];
  32172. }
  32173. };
  32174. PostProcessRenderEffect.prototype._linkParameters = function () {
  32175. var _this = this;
  32176. for (var index in this._postProcesses) {
  32177. if (this.applyParameters) {
  32178. this.applyParameters(this._postProcesses[index]);
  32179. }
  32180. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  32181. _this._linkTextures(effect);
  32182. });
  32183. }
  32184. };
  32185. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  32186. for (var renderPassName in this._renderPasses) {
  32187. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  32188. }
  32189. for (var renderEffectName in this._renderEffectAsPasses) {
  32190. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  32191. }
  32192. };
  32193. return PostProcessRenderEffect;
  32194. })();
  32195. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  32196. })(BABYLON || (BABYLON = {}));
  32197. var BABYLON;
  32198. (function (BABYLON) {
  32199. var PostProcessRenderPipeline = (function () {
  32200. function PostProcessRenderPipeline(engine, name) {
  32201. this._engine = engine;
  32202. this._name = name;
  32203. this._renderEffects = {};
  32204. this._renderEffectsForIsolatedPass = {};
  32205. this._cameras = [];
  32206. }
  32207. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  32208. get: function () {
  32209. for (var renderEffectName in this._renderEffects) {
  32210. if (!this._renderEffects[renderEffectName].isSupported) {
  32211. return false;
  32212. }
  32213. }
  32214. return true;
  32215. },
  32216. enumerable: true,
  32217. configurable: true
  32218. });
  32219. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  32220. this._renderEffects[renderEffect._name] = renderEffect;
  32221. };
  32222. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  32223. var renderEffects = this._renderEffects[renderEffectName];
  32224. if (!renderEffects) {
  32225. return;
  32226. }
  32227. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  32228. };
  32229. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  32230. var renderEffects = this._renderEffects[renderEffectName];
  32231. if (!renderEffects) {
  32232. return;
  32233. }
  32234. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  32235. };
  32236. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  32237. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32238. var indicesToDelete = [];
  32239. var i;
  32240. for (i = 0; i < _cam.length; i++) {
  32241. var camera = _cam[i];
  32242. var cameraName = camera.name;
  32243. if (this._cameras.indexOf(camera) === -1) {
  32244. this._cameras[cameraName] = camera;
  32245. }
  32246. else if (unique) {
  32247. indicesToDelete.push(i);
  32248. }
  32249. }
  32250. for (i = 0; i < indicesToDelete.length; i++) {
  32251. cameras.splice(indicesToDelete[i], 1);
  32252. }
  32253. for (var renderEffectName in this._renderEffects) {
  32254. this._renderEffects[renderEffectName]._attachCameras(_cam);
  32255. }
  32256. };
  32257. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  32258. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32259. for (var renderEffectName in this._renderEffects) {
  32260. this._renderEffects[renderEffectName]._detachCameras(_cam);
  32261. }
  32262. for (var i = 0; i < _cam.length; i++) {
  32263. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  32264. }
  32265. };
  32266. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  32267. var _this = this;
  32268. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32269. var pass = null;
  32270. var renderEffectName;
  32271. for (renderEffectName in this._renderEffects) {
  32272. pass = this._renderEffects[renderEffectName].getPass(passName);
  32273. if (pass != null) {
  32274. break;
  32275. }
  32276. }
  32277. if (pass === null) {
  32278. return;
  32279. }
  32280. for (renderEffectName in this._renderEffects) {
  32281. this._renderEffects[renderEffectName]._disable(_cam);
  32282. }
  32283. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  32284. for (var i = 0; i < _cam.length; i++) {
  32285. var camera = _cam[i];
  32286. var cameraName = camera.name;
  32287. 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); });
  32288. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  32289. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  32290. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  32291. }
  32292. };
  32293. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  32294. var _this = this;
  32295. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32296. for (var i = 0; i < _cam.length; i++) {
  32297. var camera = _cam[i];
  32298. var cameraName = camera.name;
  32299. 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); });
  32300. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  32301. }
  32302. for (var renderEffectName in this._renderEffects) {
  32303. this._renderEffects[renderEffectName]._enable(_cam);
  32304. }
  32305. };
  32306. PostProcessRenderPipeline.prototype._update = function () {
  32307. for (var renderEffectName in this._renderEffects) {
  32308. this._renderEffects[renderEffectName]._update();
  32309. }
  32310. for (var i = 0; i < this._cameras.length; i++) {
  32311. var cameraName = this._cameras[i].name;
  32312. if (this._renderEffectsForIsolatedPass[cameraName]) {
  32313. this._renderEffectsForIsolatedPass[cameraName]._update();
  32314. }
  32315. }
  32316. };
  32317. PostProcessRenderPipeline.prototype.dispose = function () {
  32318. // Must be implemented by children
  32319. };
  32320. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  32321. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  32322. return PostProcessRenderPipeline;
  32323. })();
  32324. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  32325. })(BABYLON || (BABYLON = {}));
  32326. var BABYLON;
  32327. (function (BABYLON) {
  32328. var PostProcessRenderPipelineManager = (function () {
  32329. function PostProcessRenderPipelineManager() {
  32330. this._renderPipelines = {};
  32331. }
  32332. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  32333. this._renderPipelines[renderPipeline._name] = renderPipeline;
  32334. };
  32335. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  32336. var renderPipeline = this._renderPipelines[renderPipelineName];
  32337. if (!renderPipeline) {
  32338. return;
  32339. }
  32340. renderPipeline._attachCameras(cameras, unique);
  32341. };
  32342. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  32343. var renderPipeline = this._renderPipelines[renderPipelineName];
  32344. if (!renderPipeline) {
  32345. return;
  32346. }
  32347. renderPipeline._detachCameras(cameras);
  32348. };
  32349. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  32350. var renderPipeline = this._renderPipelines[renderPipelineName];
  32351. if (!renderPipeline) {
  32352. return;
  32353. }
  32354. renderPipeline._enableEffect(renderEffectName, cameras);
  32355. };
  32356. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  32357. var renderPipeline = this._renderPipelines[renderPipelineName];
  32358. if (!renderPipeline) {
  32359. return;
  32360. }
  32361. renderPipeline._disableEffect(renderEffectName, cameras);
  32362. };
  32363. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  32364. var renderPipeline = this._renderPipelines[renderPipelineName];
  32365. if (!renderPipeline) {
  32366. return;
  32367. }
  32368. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  32369. };
  32370. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  32371. var renderPipeline = this._renderPipelines[renderPipelineName];
  32372. if (!renderPipeline) {
  32373. return;
  32374. }
  32375. renderPipeline._disableDisplayOnlyPass(cameras);
  32376. };
  32377. PostProcessRenderPipelineManager.prototype.update = function () {
  32378. for (var renderPipelineName in this._renderPipelines) {
  32379. var pipeline = this._renderPipelines[renderPipelineName];
  32380. if (!pipeline.isSupported) {
  32381. pipeline.dispose();
  32382. delete this._renderPipelines[renderPipelineName];
  32383. }
  32384. else {
  32385. pipeline._update();
  32386. }
  32387. }
  32388. };
  32389. return PostProcessRenderPipelineManager;
  32390. })();
  32391. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  32392. })(BABYLON || (BABYLON = {}));
  32393. var BABYLON;
  32394. (function (BABYLON) {
  32395. var BoundingBoxRenderer = (function () {
  32396. function BoundingBoxRenderer(scene) {
  32397. this.frontColor = new BABYLON.Color3(1, 1, 1);
  32398. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  32399. this.showBackLines = true;
  32400. this.renderList = new BABYLON.SmartArray(32);
  32401. this._vertexBuffers = {};
  32402. this._scene = scene;
  32403. }
  32404. BoundingBoxRenderer.prototype._prepareRessources = function () {
  32405. if (this._colorShader) {
  32406. return;
  32407. }
  32408. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  32409. attributes: [BABYLON.VertexBuffer.PositionKind],
  32410. uniforms: ["worldViewProjection", "color"]
  32411. });
  32412. var engine = this._scene.getEngine();
  32413. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  32414. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  32415. 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]);
  32416. };
  32417. BoundingBoxRenderer.prototype.reset = function () {
  32418. this.renderList.reset();
  32419. };
  32420. BoundingBoxRenderer.prototype.render = function () {
  32421. if (this.renderList.length === 0) {
  32422. return;
  32423. }
  32424. this._prepareRessources();
  32425. if (!this._colorShader.isReady()) {
  32426. return;
  32427. }
  32428. var engine = this._scene.getEngine();
  32429. engine.setDepthWrite(false);
  32430. this._colorShader._preBind();
  32431. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  32432. var boundingBox = this.renderList.data[boundingBoxIndex];
  32433. var min = boundingBox.minimum;
  32434. var max = boundingBox.maximum;
  32435. var diff = max.subtract(min);
  32436. var median = min.add(diff.scale(0.5));
  32437. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  32438. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  32439. .multiply(boundingBox.getWorldMatrix());
  32440. // VBOs
  32441. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  32442. if (this.showBackLines) {
  32443. // Back
  32444. engine.setDepthFunctionToGreaterOrEqual();
  32445. this._scene.resetCachedMaterial();
  32446. this._colorShader.setColor4("color", this.backColor.toColor4());
  32447. this._colorShader.bind(worldMatrix);
  32448. // Draw order
  32449. engine.draw(false, 0, 24);
  32450. }
  32451. // Front
  32452. engine.setDepthFunctionToLess();
  32453. this._scene.resetCachedMaterial();
  32454. this._colorShader.setColor4("color", this.frontColor.toColor4());
  32455. this._colorShader.bind(worldMatrix);
  32456. // Draw order
  32457. engine.draw(false, 0, 24);
  32458. }
  32459. this._colorShader.unbind();
  32460. engine.setDepthFunctionToLessOrEqual();
  32461. engine.setDepthWrite(true);
  32462. };
  32463. BoundingBoxRenderer.prototype.dispose = function () {
  32464. if (!this._colorShader) {
  32465. return;
  32466. }
  32467. this._colorShader.dispose();
  32468. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32469. if (buffer) {
  32470. buffer.dispose();
  32471. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32472. }
  32473. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32474. };
  32475. return BoundingBoxRenderer;
  32476. })();
  32477. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  32478. })(BABYLON || (BABYLON = {}));
  32479. var BABYLON;
  32480. (function (BABYLON) {
  32481. var Condition = (function () {
  32482. function Condition(actionManager) {
  32483. this._actionManager = actionManager;
  32484. }
  32485. Condition.prototype.isValid = function () {
  32486. return true;
  32487. };
  32488. Condition.prototype._getProperty = function (propertyPath) {
  32489. return this._actionManager._getProperty(propertyPath);
  32490. };
  32491. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  32492. return this._actionManager._getEffectiveTarget(target, propertyPath);
  32493. };
  32494. Condition.prototype.serialize = function () {
  32495. };
  32496. Condition.prototype._serialize = function (serializedCondition) {
  32497. return {
  32498. type: 2,
  32499. children: [],
  32500. name: serializedCondition.name,
  32501. properties: serializedCondition.properties
  32502. };
  32503. };
  32504. return Condition;
  32505. })();
  32506. BABYLON.Condition = Condition;
  32507. var ValueCondition = (function (_super) {
  32508. __extends(ValueCondition, _super);
  32509. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  32510. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  32511. _super.call(this, actionManager);
  32512. this.propertyPath = propertyPath;
  32513. this.value = value;
  32514. this.operator = operator;
  32515. this._target = target;
  32516. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  32517. this._property = this._getProperty(this.propertyPath);
  32518. }
  32519. Object.defineProperty(ValueCondition, "IsEqual", {
  32520. get: function () {
  32521. return ValueCondition._IsEqual;
  32522. },
  32523. enumerable: true,
  32524. configurable: true
  32525. });
  32526. Object.defineProperty(ValueCondition, "IsDifferent", {
  32527. get: function () {
  32528. return ValueCondition._IsDifferent;
  32529. },
  32530. enumerable: true,
  32531. configurable: true
  32532. });
  32533. Object.defineProperty(ValueCondition, "IsGreater", {
  32534. get: function () {
  32535. return ValueCondition._IsGreater;
  32536. },
  32537. enumerable: true,
  32538. configurable: true
  32539. });
  32540. Object.defineProperty(ValueCondition, "IsLesser", {
  32541. get: function () {
  32542. return ValueCondition._IsLesser;
  32543. },
  32544. enumerable: true,
  32545. configurable: true
  32546. });
  32547. // Methods
  32548. ValueCondition.prototype.isValid = function () {
  32549. switch (this.operator) {
  32550. case ValueCondition.IsGreater:
  32551. return this._effectiveTarget[this._property] > this.value;
  32552. case ValueCondition.IsLesser:
  32553. return this._effectiveTarget[this._property] < this.value;
  32554. case ValueCondition.IsEqual:
  32555. case ValueCondition.IsDifferent:
  32556. var check;
  32557. if (this.value.equals) {
  32558. check = this.value.equals(this._effectiveTarget[this._property]);
  32559. }
  32560. else {
  32561. check = this.value === this._effectiveTarget[this._property];
  32562. }
  32563. return this.operator === ValueCondition.IsEqual ? check : !check;
  32564. }
  32565. return false;
  32566. };
  32567. ValueCondition.prototype.serialize = function () {
  32568. return this._serialize({
  32569. name: "ValueCondition",
  32570. properties: [
  32571. BABYLON.Action._GetTargetProperty(this._target),
  32572. { name: "propertyPath", value: this.propertyPath },
  32573. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  32574. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  32575. ]
  32576. });
  32577. };
  32578. ValueCondition.GetOperatorName = function (operator) {
  32579. switch (operator) {
  32580. case ValueCondition._IsEqual: return "IsEqual";
  32581. case ValueCondition._IsDifferent: return "IsDifferent";
  32582. case ValueCondition._IsGreater: return "IsGreater";
  32583. case ValueCondition._IsLesser: return "IsLesser";
  32584. default: return "";
  32585. }
  32586. };
  32587. // Statics
  32588. ValueCondition._IsEqual = 0;
  32589. ValueCondition._IsDifferent = 1;
  32590. ValueCondition._IsGreater = 2;
  32591. ValueCondition._IsLesser = 3;
  32592. return ValueCondition;
  32593. })(Condition);
  32594. BABYLON.ValueCondition = ValueCondition;
  32595. var PredicateCondition = (function (_super) {
  32596. __extends(PredicateCondition, _super);
  32597. function PredicateCondition(actionManager, predicate) {
  32598. _super.call(this, actionManager);
  32599. this.predicate = predicate;
  32600. }
  32601. PredicateCondition.prototype.isValid = function () {
  32602. return this.predicate();
  32603. };
  32604. return PredicateCondition;
  32605. })(Condition);
  32606. BABYLON.PredicateCondition = PredicateCondition;
  32607. var StateCondition = (function (_super) {
  32608. __extends(StateCondition, _super);
  32609. function StateCondition(actionManager, target, value) {
  32610. _super.call(this, actionManager);
  32611. this.value = value;
  32612. this._target = target;
  32613. }
  32614. // Methods
  32615. StateCondition.prototype.isValid = function () {
  32616. return this._target.state === this.value;
  32617. };
  32618. StateCondition.prototype.serialize = function () {
  32619. return this._serialize({
  32620. name: "StateCondition",
  32621. properties: [
  32622. BABYLON.Action._GetTargetProperty(this._target),
  32623. { name: "value", value: this.value }
  32624. ]
  32625. });
  32626. };
  32627. return StateCondition;
  32628. })(Condition);
  32629. BABYLON.StateCondition = StateCondition;
  32630. })(BABYLON || (BABYLON = {}));
  32631. var BABYLON;
  32632. (function (BABYLON) {
  32633. var Action = (function () {
  32634. function Action(triggerOptions, condition) {
  32635. this.triggerOptions = triggerOptions;
  32636. if (triggerOptions.parameter) {
  32637. this.trigger = triggerOptions.trigger;
  32638. this._triggerParameter = triggerOptions.parameter;
  32639. }
  32640. else {
  32641. this.trigger = triggerOptions;
  32642. }
  32643. this._nextActiveAction = this;
  32644. this._condition = condition;
  32645. }
  32646. // Methods
  32647. Action.prototype._prepare = function () {
  32648. };
  32649. Action.prototype.getTriggerParameter = function () {
  32650. return this._triggerParameter;
  32651. };
  32652. Action.prototype._executeCurrent = function (evt) {
  32653. if (this._nextActiveAction._condition) {
  32654. var condition = this._nextActiveAction._condition;
  32655. var currentRenderId = this._actionManager.getScene().getRenderId();
  32656. // We cache the current evaluation for the current frame
  32657. if (condition._evaluationId === currentRenderId) {
  32658. if (!condition._currentResult) {
  32659. return;
  32660. }
  32661. }
  32662. else {
  32663. condition._evaluationId = currentRenderId;
  32664. if (!condition.isValid()) {
  32665. condition._currentResult = false;
  32666. return;
  32667. }
  32668. condition._currentResult = true;
  32669. }
  32670. }
  32671. this._nextActiveAction.execute(evt);
  32672. this.skipToNextActiveAction();
  32673. };
  32674. Action.prototype.execute = function (evt) {
  32675. };
  32676. Action.prototype.skipToNextActiveAction = function () {
  32677. if (this._nextActiveAction._child) {
  32678. if (!this._nextActiveAction._child._actionManager) {
  32679. this._nextActiveAction._child._actionManager = this._actionManager;
  32680. }
  32681. this._nextActiveAction = this._nextActiveAction._child;
  32682. }
  32683. else {
  32684. this._nextActiveAction = this;
  32685. }
  32686. };
  32687. Action.prototype.then = function (action) {
  32688. this._child = action;
  32689. action._actionManager = this._actionManager;
  32690. action._prepare();
  32691. return action;
  32692. };
  32693. Action.prototype._getProperty = function (propertyPath) {
  32694. return this._actionManager._getProperty(propertyPath);
  32695. };
  32696. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  32697. return this._actionManager._getEffectiveTarget(target, propertyPath);
  32698. };
  32699. Action.prototype.serialize = function (parent) {
  32700. };
  32701. // Called by BABYLON.Action objects in serialize(...). Internal use
  32702. Action.prototype._serialize = function (serializedAction, parent) {
  32703. var serializationObject = {
  32704. type: 1,
  32705. children: [],
  32706. name: serializedAction.name,
  32707. properties: serializedAction.properties || []
  32708. };
  32709. // Serialize child
  32710. if (this._child) {
  32711. this._child.serialize(serializationObject);
  32712. }
  32713. // Check if "this" has a condition
  32714. if (this._condition) {
  32715. var serializedCondition = this._condition.serialize();
  32716. serializedCondition.children.push(serializationObject);
  32717. if (parent) {
  32718. parent.children.push(serializedCondition);
  32719. }
  32720. return serializedCondition;
  32721. }
  32722. if (parent) {
  32723. parent.children.push(serializationObject);
  32724. }
  32725. return serializationObject;
  32726. };
  32727. Action._SerializeValueAsString = function (value) {
  32728. if (typeof value === "number") {
  32729. return value.toString();
  32730. }
  32731. if (typeof value === "boolean") {
  32732. return value ? "true" : "false";
  32733. }
  32734. if (value instanceof BABYLON.Vector2) {
  32735. return value.x + ", " + value.y;
  32736. }
  32737. if (value instanceof BABYLON.Vector3) {
  32738. return value.x + ", " + value.y + ", " + value.z;
  32739. }
  32740. if (value instanceof BABYLON.Color3) {
  32741. return value.r + ", " + value.g + ", " + value.b;
  32742. }
  32743. if (value instanceof BABYLON.Color4) {
  32744. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  32745. }
  32746. return value; // string
  32747. };
  32748. Action._GetTargetProperty = function (target) {
  32749. return {
  32750. name: "target",
  32751. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  32752. : target instanceof BABYLON.Light ? "LightProperties"
  32753. : target instanceof BABYLON.Camera ? "CameraProperties"
  32754. : "SceneProperties",
  32755. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  32756. };
  32757. };
  32758. return Action;
  32759. })();
  32760. BABYLON.Action = Action;
  32761. })(BABYLON || (BABYLON = {}));
  32762. var BABYLON;
  32763. (function (BABYLON) {
  32764. /**
  32765. * ActionEvent is the event beint sent when an action is triggered.
  32766. */
  32767. var ActionEvent = (function () {
  32768. /**
  32769. * @constructor
  32770. * @param source The mesh or sprite that triggered the action.
  32771. * @param pointerX The X mouse cursor position at the time of the event
  32772. * @param pointerY The Y mouse cursor position at the time of the event
  32773. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  32774. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  32775. */
  32776. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  32777. this.source = source;
  32778. this.pointerX = pointerX;
  32779. this.pointerY = pointerY;
  32780. this.meshUnderPointer = meshUnderPointer;
  32781. this.sourceEvent = sourceEvent;
  32782. this.additionalData = additionalData;
  32783. }
  32784. /**
  32785. * Helper function to auto-create an ActionEvent from a source mesh.
  32786. * @param source The source mesh that triggered the event
  32787. * @param evt {Event} The original (browser) event
  32788. */
  32789. ActionEvent.CreateNew = function (source, evt, additionalData) {
  32790. var scene = source.getScene();
  32791. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  32792. };
  32793. /**
  32794. * Helper function to auto-create an ActionEvent from a source mesh.
  32795. * @param source The source sprite that triggered the event
  32796. * @param scene Scene associated with the sprite
  32797. * @param evt {Event} The original (browser) event
  32798. */
  32799. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  32800. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  32801. };
  32802. /**
  32803. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  32804. * @param scene the scene where the event occurred
  32805. * @param evt {Event} The original (browser) event
  32806. */
  32807. ActionEvent.CreateNewFromScene = function (scene, evt) {
  32808. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  32809. };
  32810. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  32811. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  32812. };
  32813. return ActionEvent;
  32814. })();
  32815. BABYLON.ActionEvent = ActionEvent;
  32816. /**
  32817. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  32818. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  32819. */
  32820. var ActionManager = (function () {
  32821. function ActionManager(scene) {
  32822. // Members
  32823. this.actions = new Array();
  32824. this._scene = scene;
  32825. scene._actionManagers.push(this);
  32826. }
  32827. Object.defineProperty(ActionManager, "NothingTrigger", {
  32828. get: function () {
  32829. return ActionManager._NothingTrigger;
  32830. },
  32831. enumerable: true,
  32832. configurable: true
  32833. });
  32834. Object.defineProperty(ActionManager, "OnPickTrigger", {
  32835. get: function () {
  32836. return ActionManager._OnPickTrigger;
  32837. },
  32838. enumerable: true,
  32839. configurable: true
  32840. });
  32841. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  32842. get: function () {
  32843. return ActionManager._OnLeftPickTrigger;
  32844. },
  32845. enumerable: true,
  32846. configurable: true
  32847. });
  32848. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  32849. get: function () {
  32850. return ActionManager._OnRightPickTrigger;
  32851. },
  32852. enumerable: true,
  32853. configurable: true
  32854. });
  32855. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  32856. get: function () {
  32857. return ActionManager._OnCenterPickTrigger;
  32858. },
  32859. enumerable: true,
  32860. configurable: true
  32861. });
  32862. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  32863. get: function () {
  32864. return ActionManager._OnPickDownTrigger;
  32865. },
  32866. enumerable: true,
  32867. configurable: true
  32868. });
  32869. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  32870. get: function () {
  32871. return ActionManager._OnPickUpTrigger;
  32872. },
  32873. enumerable: true,
  32874. configurable: true
  32875. });
  32876. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  32877. /// This trigger will only be raised if you also declared a OnPickDown
  32878. get: function () {
  32879. return ActionManager._OnPickOutTrigger;
  32880. },
  32881. enumerable: true,
  32882. configurable: true
  32883. });
  32884. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  32885. get: function () {
  32886. return ActionManager._OnLongPressTrigger;
  32887. },
  32888. enumerable: true,
  32889. configurable: true
  32890. });
  32891. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  32892. get: function () {
  32893. return ActionManager._OnPointerOverTrigger;
  32894. },
  32895. enumerable: true,
  32896. configurable: true
  32897. });
  32898. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  32899. get: function () {
  32900. return ActionManager._OnPointerOutTrigger;
  32901. },
  32902. enumerable: true,
  32903. configurable: true
  32904. });
  32905. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  32906. get: function () {
  32907. return ActionManager._OnEveryFrameTrigger;
  32908. },
  32909. enumerable: true,
  32910. configurable: true
  32911. });
  32912. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  32913. get: function () {
  32914. return ActionManager._OnIntersectionEnterTrigger;
  32915. },
  32916. enumerable: true,
  32917. configurable: true
  32918. });
  32919. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  32920. get: function () {
  32921. return ActionManager._OnIntersectionExitTrigger;
  32922. },
  32923. enumerable: true,
  32924. configurable: true
  32925. });
  32926. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  32927. get: function () {
  32928. return ActionManager._OnKeyDownTrigger;
  32929. },
  32930. enumerable: true,
  32931. configurable: true
  32932. });
  32933. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  32934. get: function () {
  32935. return ActionManager._OnKeyUpTrigger;
  32936. },
  32937. enumerable: true,
  32938. configurable: true
  32939. });
  32940. // Methods
  32941. ActionManager.prototype.dispose = function () {
  32942. var index = this._scene._actionManagers.indexOf(this);
  32943. if (index > -1) {
  32944. this._scene._actionManagers.splice(index, 1);
  32945. }
  32946. };
  32947. ActionManager.prototype.getScene = function () {
  32948. return this._scene;
  32949. };
  32950. /**
  32951. * Does this action manager handles actions of any of the given triggers
  32952. * @param {number[]} triggers - the triggers to be tested
  32953. * @return {boolean} whether one (or more) of the triggers is handeled
  32954. */
  32955. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  32956. for (var index = 0; index < this.actions.length; index++) {
  32957. var action = this.actions[index];
  32958. if (triggers.indexOf(action.trigger) > -1) {
  32959. return true;
  32960. }
  32961. }
  32962. return false;
  32963. };
  32964. /**
  32965. * Does this action manager handles actions of a given trigger
  32966. * @param {number} trigger - the trigger to be tested
  32967. * @return {boolean} whether the trigger is handeled
  32968. */
  32969. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  32970. for (var index = 0; index < this.actions.length; index++) {
  32971. var action = this.actions[index];
  32972. if (action.trigger === trigger) {
  32973. return true;
  32974. }
  32975. }
  32976. return false;
  32977. };
  32978. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  32979. /**
  32980. * Does this action manager has pointer triggers
  32981. * @return {boolean} whether or not it has pointer triggers
  32982. */
  32983. get: function () {
  32984. for (var index = 0; index < this.actions.length; index++) {
  32985. var action = this.actions[index];
  32986. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  32987. return true;
  32988. }
  32989. }
  32990. return false;
  32991. },
  32992. enumerable: true,
  32993. configurable: true
  32994. });
  32995. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  32996. /**
  32997. * Does this action manager has pick triggers
  32998. * @return {boolean} whether or not it has pick triggers
  32999. */
  33000. get: function () {
  33001. for (var index = 0; index < this.actions.length; index++) {
  33002. var action = this.actions[index];
  33003. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  33004. return true;
  33005. }
  33006. }
  33007. return false;
  33008. },
  33009. enumerable: true,
  33010. configurable: true
  33011. });
  33012. /**
  33013. * Registers an action to this action manager
  33014. * @param {BABYLON.Action} action - the action to be registered
  33015. * @return {BABYLON.Action} the action amended (prepared) after registration
  33016. */
  33017. ActionManager.prototype.registerAction = function (action) {
  33018. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  33019. if (this.getScene().actionManager !== this) {
  33020. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  33021. return null;
  33022. }
  33023. }
  33024. this.actions.push(action);
  33025. action._actionManager = this;
  33026. action._prepare();
  33027. return action;
  33028. };
  33029. /**
  33030. * Process a specific trigger
  33031. * @param {number} trigger - the trigger to process
  33032. * @param evt {BABYLON.ActionEvent} the event details to be processed
  33033. */
  33034. ActionManager.prototype.processTrigger = function (trigger, evt) {
  33035. for (var index = 0; index < this.actions.length; index++) {
  33036. var action = this.actions[index];
  33037. if (action.trigger === trigger) {
  33038. if (trigger === ActionManager.OnKeyUpTrigger
  33039. || trigger === ActionManager.OnKeyDownTrigger) {
  33040. var parameter = action.getTriggerParameter();
  33041. if (parameter) {
  33042. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  33043. var actualkey = String.fromCharCode(unicode).toLowerCase();
  33044. if (actualkey !== parameter.toLowerCase()) {
  33045. continue;
  33046. }
  33047. }
  33048. }
  33049. action._executeCurrent(evt);
  33050. }
  33051. }
  33052. };
  33053. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  33054. var properties = propertyPath.split(".");
  33055. for (var index = 0; index < properties.length - 1; index++) {
  33056. target = target[properties[index]];
  33057. }
  33058. return target;
  33059. };
  33060. ActionManager.prototype._getProperty = function (propertyPath) {
  33061. var properties = propertyPath.split(".");
  33062. return properties[properties.length - 1];
  33063. };
  33064. ActionManager.prototype.serialize = function (name) {
  33065. var root = {
  33066. children: [],
  33067. name: name,
  33068. type: 3,
  33069. properties: [] // Empty for root but required
  33070. };
  33071. for (var i = 0; i < this.actions.length; i++) {
  33072. var triggerObject = {
  33073. type: 0,
  33074. children: [],
  33075. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  33076. properties: []
  33077. };
  33078. var triggerOptions = this.actions[i].triggerOptions;
  33079. if (triggerOptions && typeof triggerOptions !== "number") {
  33080. if (triggerOptions.parameter instanceof BABYLON.Node) {
  33081. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  33082. }
  33083. else {
  33084. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  33085. }
  33086. }
  33087. // Serialize child action, recursively
  33088. this.actions[i].serialize(triggerObject);
  33089. // Add serialized trigger
  33090. root.children.push(triggerObject);
  33091. }
  33092. return root;
  33093. };
  33094. ActionManager.Parse = function (parsedActions, object, scene) {
  33095. var actionManager = new BABYLON.ActionManager(scene);
  33096. if (object === null)
  33097. scene.actionManager = actionManager;
  33098. else
  33099. object.actionManager = actionManager;
  33100. // instanciate a new object
  33101. var instanciate = function (name, params) {
  33102. var newInstance = Object.create(BABYLON[name].prototype);
  33103. newInstance.constructor.apply(newInstance, params);
  33104. return newInstance;
  33105. };
  33106. var parseParameter = function (name, value, target, propertyPath) {
  33107. if (propertyPath === null) {
  33108. // String, boolean or float
  33109. var floatValue = parseFloat(value);
  33110. if (value === "true" || value === "false")
  33111. return value === "true";
  33112. else
  33113. return isNaN(floatValue) ? value : floatValue;
  33114. }
  33115. var effectiveTarget = propertyPath.split(".");
  33116. var values = value.split(",");
  33117. // Get effective Target
  33118. for (var i = 0; i < effectiveTarget.length; i++) {
  33119. target = target[effectiveTarget[i]];
  33120. }
  33121. // Return appropriate value with its type
  33122. if (typeof (target) === "boolean")
  33123. return values[0] === "true";
  33124. if (typeof (target) === "string")
  33125. return values[0];
  33126. // Parameters with multiple values such as Vector3 etc.
  33127. var split = new Array();
  33128. for (var i = 0; i < values.length; i++)
  33129. split.push(parseFloat(values[i]));
  33130. if (target instanceof BABYLON.Vector3)
  33131. return BABYLON.Vector3.FromArray(split);
  33132. if (target instanceof BABYLON.Vector4)
  33133. return BABYLON.Vector4.FromArray(split);
  33134. if (target instanceof BABYLON.Color3)
  33135. return BABYLON.Color3.FromArray(split);
  33136. if (target instanceof BABYLON.Color4)
  33137. return BABYLON.Color4.FromArray(split);
  33138. return parseFloat(values[0]);
  33139. };
  33140. // traverse graph per trigger
  33141. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  33142. if (combineArray === void 0) { combineArray = null; }
  33143. if (parsedAction.detached)
  33144. return;
  33145. var parameters = new Array();
  33146. var target = null;
  33147. var propertyPath = null;
  33148. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  33149. // Parameters
  33150. if (parsedAction.type === 2)
  33151. parameters.push(actionManager);
  33152. else
  33153. parameters.push(trigger);
  33154. if (combine) {
  33155. var actions = new Array();
  33156. for (var j = 0; j < parsedAction.combine.length; j++) {
  33157. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  33158. }
  33159. parameters.push(actions);
  33160. }
  33161. else {
  33162. for (var i = 0; i < parsedAction.properties.length; i++) {
  33163. var value = parsedAction.properties[i].value;
  33164. var name = parsedAction.properties[i].name;
  33165. var targetType = parsedAction.properties[i].targetType;
  33166. if (name === "target")
  33167. if (targetType !== null && targetType === "SceneProperties")
  33168. value = target = scene;
  33169. else
  33170. value = target = scene.getNodeByName(value);
  33171. else if (name === "parent")
  33172. value = scene.getNodeByName(value);
  33173. else if (name === "sound")
  33174. value = scene.getSoundByName(value);
  33175. else if (name !== "propertyPath") {
  33176. if (parsedAction.type === 2 && name === "operator")
  33177. value = BABYLON.ValueCondition[value];
  33178. else
  33179. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  33180. }
  33181. else {
  33182. propertyPath = value;
  33183. }
  33184. parameters.push(value);
  33185. }
  33186. }
  33187. if (combineArray === null) {
  33188. parameters.push(condition);
  33189. }
  33190. else {
  33191. parameters.push(null);
  33192. }
  33193. // If interpolate value action
  33194. if (parsedAction.name === "InterpolateValueAction") {
  33195. var param = parameters[parameters.length - 2];
  33196. parameters[parameters.length - 1] = param;
  33197. parameters[parameters.length - 2] = condition;
  33198. }
  33199. // Action or condition(s) and not CombineAction
  33200. var newAction = instanciate(parsedAction.name, parameters);
  33201. if (newAction instanceof BABYLON.Condition && condition !== null) {
  33202. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  33203. if (action)
  33204. action.then(nothing);
  33205. else
  33206. actionManager.registerAction(nothing);
  33207. action = nothing;
  33208. }
  33209. if (combineArray === null) {
  33210. if (newAction instanceof BABYLON.Condition) {
  33211. condition = newAction;
  33212. newAction = action;
  33213. }
  33214. else {
  33215. condition = null;
  33216. if (action)
  33217. action.then(newAction);
  33218. else
  33219. actionManager.registerAction(newAction);
  33220. }
  33221. }
  33222. else {
  33223. combineArray.push(newAction);
  33224. }
  33225. for (var i = 0; i < parsedAction.children.length; i++)
  33226. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  33227. };
  33228. // triggers
  33229. for (var i = 0; i < parsedActions.children.length; i++) {
  33230. var triggerParams;
  33231. var trigger = parsedActions.children[i];
  33232. if (trigger.properties.length > 0) {
  33233. var param = trigger.properties[0].value;
  33234. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  33235. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  33236. }
  33237. else
  33238. triggerParams = BABYLON.ActionManager[trigger.name];
  33239. for (var j = 0; j < trigger.children.length; j++) {
  33240. if (!trigger.detached)
  33241. traverse(trigger.children[j], triggerParams, null, null);
  33242. }
  33243. }
  33244. };
  33245. ActionManager.GetTriggerName = function (trigger) {
  33246. switch (trigger) {
  33247. case 0: return "NothingTrigger";
  33248. case 1: return "OnPickTrigger";
  33249. case 2: return "OnLeftPickTrigger";
  33250. case 3: return "OnRightPickTrigger";
  33251. case 4: return "OnCenterPickTrigger";
  33252. case 5: return "OnPickDownTrigger";
  33253. case 6: return "OnPickUpTrigger";
  33254. case 7: return "OnLongPressTrigger";
  33255. case 8: return "OnPointerOverTrigger";
  33256. case 9: return "OnPointerOutTrigger";
  33257. case 10: return "OnEveryFrameTrigger";
  33258. case 11: return "OnIntersectionEnterTrigger";
  33259. case 12: return "OnIntersectionExitTrigger";
  33260. case 13: return "OnKeyDownTrigger";
  33261. case 14: return "OnKeyUpTrigger";
  33262. case 15: return "OnPickOutTrigger";
  33263. default: return "";
  33264. }
  33265. };
  33266. // Statics
  33267. ActionManager._NothingTrigger = 0;
  33268. ActionManager._OnPickTrigger = 1;
  33269. ActionManager._OnLeftPickTrigger = 2;
  33270. ActionManager._OnRightPickTrigger = 3;
  33271. ActionManager._OnCenterPickTrigger = 4;
  33272. ActionManager._OnPickDownTrigger = 5;
  33273. ActionManager._OnPickUpTrigger = 6;
  33274. ActionManager._OnLongPressTrigger = 7;
  33275. ActionManager._OnPointerOverTrigger = 8;
  33276. ActionManager._OnPointerOutTrigger = 9;
  33277. ActionManager._OnEveryFrameTrigger = 10;
  33278. ActionManager._OnIntersectionEnterTrigger = 11;
  33279. ActionManager._OnIntersectionExitTrigger = 12;
  33280. ActionManager._OnKeyDownTrigger = 13;
  33281. ActionManager._OnKeyUpTrigger = 14;
  33282. ActionManager._OnPickOutTrigger = 15;
  33283. ActionManager.DragMovementThreshold = 10; // in pixels
  33284. ActionManager.LongPressDelay = 500; // in milliseconds
  33285. return ActionManager;
  33286. })();
  33287. BABYLON.ActionManager = ActionManager;
  33288. })(BABYLON || (BABYLON = {}));
  33289. var BABYLON;
  33290. (function (BABYLON) {
  33291. var InterpolateValueAction = (function (_super) {
  33292. __extends(InterpolateValueAction, _super);
  33293. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  33294. if (duration === void 0) { duration = 1000; }
  33295. _super.call(this, triggerOptions, condition);
  33296. this.propertyPath = propertyPath;
  33297. this.value = value;
  33298. this.duration = duration;
  33299. this.stopOtherAnimations = stopOtherAnimations;
  33300. this.onInterpolationDone = onInterpolationDone;
  33301. this._target = this._effectiveTarget = target;
  33302. }
  33303. InterpolateValueAction.prototype._prepare = function () {
  33304. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33305. this._property = this._getProperty(this.propertyPath);
  33306. };
  33307. InterpolateValueAction.prototype.execute = function () {
  33308. var scene = this._actionManager.getScene();
  33309. var keys = [
  33310. {
  33311. frame: 0,
  33312. value: this._effectiveTarget[this._property]
  33313. }, {
  33314. frame: 100,
  33315. value: this.value
  33316. }
  33317. ];
  33318. var dataType;
  33319. if (typeof this.value === "number") {
  33320. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  33321. }
  33322. else if (this.value instanceof BABYLON.Color3) {
  33323. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  33324. }
  33325. else if (this.value instanceof BABYLON.Vector3) {
  33326. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  33327. }
  33328. else if (this.value instanceof BABYLON.Matrix) {
  33329. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  33330. }
  33331. else if (this.value instanceof BABYLON.Quaternion) {
  33332. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  33333. }
  33334. else {
  33335. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  33336. return;
  33337. }
  33338. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  33339. animation.setKeys(keys);
  33340. if (this.stopOtherAnimations) {
  33341. scene.stopAnimation(this._effectiveTarget);
  33342. }
  33343. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  33344. };
  33345. InterpolateValueAction.prototype.serialize = function (parent) {
  33346. return _super.prototype._serialize.call(this, {
  33347. name: "InterpolateValueAction",
  33348. properties: [
  33349. BABYLON.Action._GetTargetProperty(this._target),
  33350. { name: "propertyPath", value: this.propertyPath },
  33351. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  33352. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  33353. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  33354. ]
  33355. }, parent);
  33356. };
  33357. return InterpolateValueAction;
  33358. })(BABYLON.Action);
  33359. BABYLON.InterpolateValueAction = InterpolateValueAction;
  33360. })(BABYLON || (BABYLON = {}));
  33361. var BABYLON;
  33362. (function (BABYLON) {
  33363. var SwitchBooleanAction = (function (_super) {
  33364. __extends(SwitchBooleanAction, _super);
  33365. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  33366. _super.call(this, triggerOptions, condition);
  33367. this.propertyPath = propertyPath;
  33368. this._target = this._effectiveTarget = target;
  33369. }
  33370. SwitchBooleanAction.prototype._prepare = function () {
  33371. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33372. this._property = this._getProperty(this.propertyPath);
  33373. };
  33374. SwitchBooleanAction.prototype.execute = function () {
  33375. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  33376. };
  33377. SwitchBooleanAction.prototype.serialize = function (parent) {
  33378. return _super.prototype._serialize.call(this, {
  33379. name: "SwitchBooleanAction",
  33380. properties: [
  33381. BABYLON.Action._GetTargetProperty(this._target),
  33382. { name: "propertyPath", value: this.propertyPath }
  33383. ]
  33384. }, parent);
  33385. };
  33386. return SwitchBooleanAction;
  33387. })(BABYLON.Action);
  33388. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  33389. var SetStateAction = (function (_super) {
  33390. __extends(SetStateAction, _super);
  33391. function SetStateAction(triggerOptions, target, value, condition) {
  33392. _super.call(this, triggerOptions, condition);
  33393. this.value = value;
  33394. this._target = target;
  33395. }
  33396. SetStateAction.prototype.execute = function () {
  33397. this._target.state = this.value;
  33398. };
  33399. SetStateAction.prototype.serialize = function (parent) {
  33400. return _super.prototype._serialize.call(this, {
  33401. name: "SetStateAction",
  33402. properties: [
  33403. BABYLON.Action._GetTargetProperty(this._target),
  33404. { name: "value", value: this.value }
  33405. ]
  33406. }, parent);
  33407. };
  33408. return SetStateAction;
  33409. })(BABYLON.Action);
  33410. BABYLON.SetStateAction = SetStateAction;
  33411. var SetValueAction = (function (_super) {
  33412. __extends(SetValueAction, _super);
  33413. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  33414. _super.call(this, triggerOptions, condition);
  33415. this.propertyPath = propertyPath;
  33416. this.value = value;
  33417. this._target = this._effectiveTarget = target;
  33418. }
  33419. SetValueAction.prototype._prepare = function () {
  33420. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33421. this._property = this._getProperty(this.propertyPath);
  33422. };
  33423. SetValueAction.prototype.execute = function () {
  33424. this._effectiveTarget[this._property] = this.value;
  33425. if (this._target.markAsDirty) {
  33426. this._target.markAsDirty(this._property);
  33427. }
  33428. };
  33429. SetValueAction.prototype.serialize = function (parent) {
  33430. return _super.prototype._serialize.call(this, {
  33431. name: "SetValueAction",
  33432. properties: [
  33433. BABYLON.Action._GetTargetProperty(this._target),
  33434. { name: "propertyPath", value: this.propertyPath },
  33435. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  33436. ]
  33437. }, parent);
  33438. };
  33439. return SetValueAction;
  33440. })(BABYLON.Action);
  33441. BABYLON.SetValueAction = SetValueAction;
  33442. var IncrementValueAction = (function (_super) {
  33443. __extends(IncrementValueAction, _super);
  33444. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  33445. _super.call(this, triggerOptions, condition);
  33446. this.propertyPath = propertyPath;
  33447. this.value = value;
  33448. this._target = this._effectiveTarget = target;
  33449. }
  33450. IncrementValueAction.prototype._prepare = function () {
  33451. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33452. this._property = this._getProperty(this.propertyPath);
  33453. if (typeof this._effectiveTarget[this._property] !== "number") {
  33454. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  33455. }
  33456. };
  33457. IncrementValueAction.prototype.execute = function () {
  33458. this._effectiveTarget[this._property] += this.value;
  33459. if (this._target.markAsDirty) {
  33460. this._target.markAsDirty(this._property);
  33461. }
  33462. };
  33463. IncrementValueAction.prototype.serialize = function (parent) {
  33464. return _super.prototype._serialize.call(this, {
  33465. name: "IncrementValueAction",
  33466. properties: [
  33467. BABYLON.Action._GetTargetProperty(this._target),
  33468. { name: "propertyPath", value: this.propertyPath },
  33469. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  33470. ]
  33471. }, parent);
  33472. };
  33473. return IncrementValueAction;
  33474. })(BABYLON.Action);
  33475. BABYLON.IncrementValueAction = IncrementValueAction;
  33476. var PlayAnimationAction = (function (_super) {
  33477. __extends(PlayAnimationAction, _super);
  33478. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  33479. _super.call(this, triggerOptions, condition);
  33480. this.from = from;
  33481. this.to = to;
  33482. this.loop = loop;
  33483. this._target = target;
  33484. }
  33485. PlayAnimationAction.prototype._prepare = function () {
  33486. };
  33487. PlayAnimationAction.prototype.execute = function () {
  33488. var scene = this._actionManager.getScene();
  33489. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  33490. };
  33491. PlayAnimationAction.prototype.serialize = function (parent) {
  33492. return _super.prototype._serialize.call(this, {
  33493. name: "PlayAnimationAction",
  33494. properties: [
  33495. BABYLON.Action._GetTargetProperty(this._target),
  33496. { name: "from", value: String(this.from) },
  33497. { name: "to", value: String(this.to) },
  33498. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  33499. ]
  33500. }, parent);
  33501. };
  33502. return PlayAnimationAction;
  33503. })(BABYLON.Action);
  33504. BABYLON.PlayAnimationAction = PlayAnimationAction;
  33505. var StopAnimationAction = (function (_super) {
  33506. __extends(StopAnimationAction, _super);
  33507. function StopAnimationAction(triggerOptions, target, condition) {
  33508. _super.call(this, triggerOptions, condition);
  33509. this._target = target;
  33510. }
  33511. StopAnimationAction.prototype._prepare = function () {
  33512. };
  33513. StopAnimationAction.prototype.execute = function () {
  33514. var scene = this._actionManager.getScene();
  33515. scene.stopAnimation(this._target);
  33516. };
  33517. StopAnimationAction.prototype.serialize = function (parent) {
  33518. return _super.prototype._serialize.call(this, {
  33519. name: "StopAnimationAction",
  33520. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  33521. }, parent);
  33522. };
  33523. return StopAnimationAction;
  33524. })(BABYLON.Action);
  33525. BABYLON.StopAnimationAction = StopAnimationAction;
  33526. var DoNothingAction = (function (_super) {
  33527. __extends(DoNothingAction, _super);
  33528. function DoNothingAction(triggerOptions, condition) {
  33529. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  33530. _super.call(this, triggerOptions, condition);
  33531. }
  33532. DoNothingAction.prototype.execute = function () {
  33533. };
  33534. DoNothingAction.prototype.serialize = function (parent) {
  33535. return _super.prototype._serialize.call(this, {
  33536. name: "DoNothingAction",
  33537. properties: []
  33538. }, parent);
  33539. };
  33540. return DoNothingAction;
  33541. })(BABYLON.Action);
  33542. BABYLON.DoNothingAction = DoNothingAction;
  33543. var CombineAction = (function (_super) {
  33544. __extends(CombineAction, _super);
  33545. function CombineAction(triggerOptions, children, condition) {
  33546. _super.call(this, triggerOptions, condition);
  33547. this.children = children;
  33548. }
  33549. CombineAction.prototype._prepare = function () {
  33550. for (var index = 0; index < this.children.length; index++) {
  33551. this.children[index]._actionManager = this._actionManager;
  33552. this.children[index]._prepare();
  33553. }
  33554. };
  33555. CombineAction.prototype.execute = function (evt) {
  33556. for (var index = 0; index < this.children.length; index++) {
  33557. this.children[index].execute(evt);
  33558. }
  33559. };
  33560. CombineAction.prototype.serialize = function (parent) {
  33561. var serializationObject = _super.prototype._serialize.call(this, {
  33562. name: "CombineAction",
  33563. properties: [],
  33564. combine: []
  33565. }, parent);
  33566. for (var i = 0; i < this.children.length; i++) {
  33567. serializationObject.combine.push(this.children[i].serialize(null));
  33568. }
  33569. return serializationObject;
  33570. };
  33571. return CombineAction;
  33572. })(BABYLON.Action);
  33573. BABYLON.CombineAction = CombineAction;
  33574. var ExecuteCodeAction = (function (_super) {
  33575. __extends(ExecuteCodeAction, _super);
  33576. function ExecuteCodeAction(triggerOptions, func, condition) {
  33577. _super.call(this, triggerOptions, condition);
  33578. this.func = func;
  33579. }
  33580. ExecuteCodeAction.prototype.execute = function (evt) {
  33581. this.func(evt);
  33582. };
  33583. return ExecuteCodeAction;
  33584. })(BABYLON.Action);
  33585. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  33586. var SetParentAction = (function (_super) {
  33587. __extends(SetParentAction, _super);
  33588. function SetParentAction(triggerOptions, target, parent, condition) {
  33589. _super.call(this, triggerOptions, condition);
  33590. this._target = target;
  33591. this._parent = parent;
  33592. }
  33593. SetParentAction.prototype._prepare = function () {
  33594. };
  33595. SetParentAction.prototype.execute = function () {
  33596. if (this._target.parent === this._parent) {
  33597. return;
  33598. }
  33599. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  33600. invertParentWorldMatrix.invert();
  33601. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  33602. this._target.parent = this._parent;
  33603. };
  33604. SetParentAction.prototype.serialize = function (parent) {
  33605. return _super.prototype._serialize.call(this, {
  33606. name: "SetParentAction",
  33607. properties: [
  33608. BABYLON.Action._GetTargetProperty(this._target),
  33609. BABYLON.Action._GetTargetProperty(this._parent),
  33610. ]
  33611. }, parent);
  33612. };
  33613. return SetParentAction;
  33614. })(BABYLON.Action);
  33615. BABYLON.SetParentAction = SetParentAction;
  33616. var PlaySoundAction = (function (_super) {
  33617. __extends(PlaySoundAction, _super);
  33618. function PlaySoundAction(triggerOptions, sound, condition) {
  33619. _super.call(this, triggerOptions, condition);
  33620. this._sound = sound;
  33621. }
  33622. PlaySoundAction.prototype._prepare = function () {
  33623. };
  33624. PlaySoundAction.prototype.execute = function () {
  33625. if (this._sound !== undefined)
  33626. this._sound.play();
  33627. };
  33628. PlaySoundAction.prototype.serialize = function (parent) {
  33629. return _super.prototype._serialize.call(this, {
  33630. name: "PlaySoundAction",
  33631. properties: [{ name: "sound", value: this._sound.name }]
  33632. }, parent);
  33633. };
  33634. return PlaySoundAction;
  33635. })(BABYLON.Action);
  33636. BABYLON.PlaySoundAction = PlaySoundAction;
  33637. var StopSoundAction = (function (_super) {
  33638. __extends(StopSoundAction, _super);
  33639. function StopSoundAction(triggerOptions, sound, condition) {
  33640. _super.call(this, triggerOptions, condition);
  33641. this._sound = sound;
  33642. }
  33643. StopSoundAction.prototype._prepare = function () {
  33644. };
  33645. StopSoundAction.prototype.execute = function () {
  33646. if (this._sound !== undefined)
  33647. this._sound.stop();
  33648. };
  33649. StopSoundAction.prototype.serialize = function (parent) {
  33650. return _super.prototype._serialize.call(this, {
  33651. name: "StopSoundAction",
  33652. properties: [{ name: "sound", value: this._sound.name }]
  33653. }, parent);
  33654. };
  33655. return StopSoundAction;
  33656. })(BABYLON.Action);
  33657. BABYLON.StopSoundAction = StopSoundAction;
  33658. })(BABYLON || (BABYLON = {}));
  33659. var BABYLON;
  33660. (function (BABYLON) {
  33661. var Geometry = (function () {
  33662. function Geometry(id, scene, vertexData, updatable, mesh) {
  33663. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33664. this._totalVertices = 0;
  33665. this._isDisposed = false;
  33666. this.id = id;
  33667. this._engine = scene.getEngine();
  33668. this._meshes = [];
  33669. this._scene = scene;
  33670. //Init vertex buffer cache
  33671. this._vertexBuffers = {};
  33672. this._indices = [];
  33673. // vertexData
  33674. if (vertexData) {
  33675. this.setAllVerticesData(vertexData, updatable);
  33676. }
  33677. else {
  33678. this._totalVertices = 0;
  33679. this._indices = [];
  33680. }
  33681. // applyToMesh
  33682. if (mesh) {
  33683. if (mesh instanceof BABYLON.LinesMesh) {
  33684. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  33685. this.updateExtend();
  33686. }
  33687. this.applyToMesh(mesh);
  33688. mesh.computeWorldMatrix(true);
  33689. }
  33690. }
  33691. Object.defineProperty(Geometry.prototype, "boundingBias", {
  33692. /**
  33693. * 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
  33694. * @returns The Bias Vector
  33695. */
  33696. get: function () {
  33697. return this._boundingBias;
  33698. },
  33699. set: function (value) {
  33700. if (this._boundingBias && this._boundingBias.equals(value)) {
  33701. return;
  33702. }
  33703. this._boundingBias = value.clone();
  33704. this.updateBoundingInfo(true, null);
  33705. },
  33706. enumerable: true,
  33707. configurable: true
  33708. });
  33709. Object.defineProperty(Geometry.prototype, "extend", {
  33710. get: function () {
  33711. return this._extend;
  33712. },
  33713. enumerable: true,
  33714. configurable: true
  33715. });
  33716. Geometry.prototype.getScene = function () {
  33717. return this._scene;
  33718. };
  33719. Geometry.prototype.getEngine = function () {
  33720. return this._engine;
  33721. };
  33722. Geometry.prototype.isReady = function () {
  33723. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  33724. };
  33725. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  33726. vertexData.applyToGeometry(this, updatable);
  33727. this.notifyUpdate();
  33728. };
  33729. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  33730. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  33731. this.setVerticesBuffer(buffer);
  33732. };
  33733. Geometry.prototype.setVerticesBuffer = function (buffer) {
  33734. var kind = buffer.getKind();
  33735. if (this._vertexBuffers[kind]) {
  33736. this._vertexBuffers[kind].dispose();
  33737. }
  33738. this._vertexBuffers[kind] = buffer;
  33739. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33740. var data = buffer.getData();
  33741. var stride = buffer.getStrideSize();
  33742. this._totalVertices = data.length / stride;
  33743. this.updateExtend(data, stride);
  33744. var meshes = this._meshes;
  33745. var numOfMeshes = meshes.length;
  33746. for (var index = 0; index < numOfMeshes; index++) {
  33747. var mesh = meshes[index];
  33748. mesh._resetPointsArrayCache();
  33749. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33750. mesh._createGlobalSubMesh();
  33751. mesh.computeWorldMatrix(true);
  33752. }
  33753. }
  33754. this.notifyUpdate(kind);
  33755. };
  33756. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  33757. var vertexBuffer = this.getVertexBuffer(kind);
  33758. if (!vertexBuffer) {
  33759. return;
  33760. }
  33761. vertexBuffer.updateDirectly(data, offset);
  33762. this.notifyUpdate(kind);
  33763. };
  33764. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  33765. var vertexBuffer = this.getVertexBuffer(kind);
  33766. if (!vertexBuffer) {
  33767. return;
  33768. }
  33769. vertexBuffer.update(data);
  33770. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33771. var stride = vertexBuffer.getStrideSize();
  33772. this._totalVertices = data.length / stride;
  33773. this.updateBoundingInfo(updateExtends, data);
  33774. }
  33775. this.notifyUpdate(kind);
  33776. };
  33777. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  33778. if (updateExtends) {
  33779. this.updateExtend(data);
  33780. }
  33781. var meshes = this._meshes;
  33782. var numOfMeshes = meshes.length;
  33783. for (var index = 0; index < numOfMeshes; index++) {
  33784. var mesh = meshes[index];
  33785. mesh._resetPointsArrayCache();
  33786. if (updateExtends) {
  33787. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33788. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  33789. var subMesh = mesh.subMeshes[subIndex];
  33790. subMesh.refreshBoundingInfo();
  33791. }
  33792. }
  33793. }
  33794. };
  33795. Geometry.prototype.getTotalVertices = function () {
  33796. if (!this.isReady()) {
  33797. return 0;
  33798. }
  33799. return this._totalVertices;
  33800. };
  33801. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  33802. var vertexBuffer = this.getVertexBuffer(kind);
  33803. if (!vertexBuffer) {
  33804. return null;
  33805. }
  33806. var orig = vertexBuffer.getData();
  33807. if (!copyWhenShared || this._meshes.length === 1) {
  33808. return orig;
  33809. }
  33810. else {
  33811. var len = orig.length;
  33812. var copy = [];
  33813. for (var i = 0; i < len; i++) {
  33814. copy.push(orig[i]);
  33815. }
  33816. return copy;
  33817. }
  33818. };
  33819. Geometry.prototype.getVertexBuffer = function (kind) {
  33820. if (!this.isReady()) {
  33821. return null;
  33822. }
  33823. return this._vertexBuffers[kind];
  33824. };
  33825. Geometry.prototype.getVertexBuffers = function () {
  33826. if (!this.isReady()) {
  33827. return null;
  33828. }
  33829. return this._vertexBuffers;
  33830. };
  33831. Geometry.prototype.isVerticesDataPresent = function (kind) {
  33832. if (!this._vertexBuffers) {
  33833. if (this._delayInfo) {
  33834. return this._delayInfo.indexOf(kind) !== -1;
  33835. }
  33836. return false;
  33837. }
  33838. return this._vertexBuffers[kind] !== undefined;
  33839. };
  33840. Geometry.prototype.getVerticesDataKinds = function () {
  33841. var result = [];
  33842. var kind;
  33843. if (!this._vertexBuffers && this._delayInfo) {
  33844. for (kind in this._delayInfo) {
  33845. result.push(kind);
  33846. }
  33847. }
  33848. else {
  33849. for (kind in this._vertexBuffers) {
  33850. result.push(kind);
  33851. }
  33852. }
  33853. return result;
  33854. };
  33855. Geometry.prototype.setIndices = function (indices, totalVertices) {
  33856. if (this._indexBuffer) {
  33857. this._engine._releaseBuffer(this._indexBuffer);
  33858. }
  33859. this._indices = indices;
  33860. if (this._meshes.length !== 0 && this._indices) {
  33861. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33862. }
  33863. if (totalVertices !== undefined) {
  33864. this._totalVertices = totalVertices;
  33865. }
  33866. var meshes = this._meshes;
  33867. var numOfMeshes = meshes.length;
  33868. for (var index = 0; index < numOfMeshes; index++) {
  33869. meshes[index]._createGlobalSubMesh();
  33870. }
  33871. this.notifyUpdate();
  33872. };
  33873. Geometry.prototype.getTotalIndices = function () {
  33874. if (!this.isReady()) {
  33875. return 0;
  33876. }
  33877. return this._indices.length;
  33878. };
  33879. Geometry.prototype.getIndices = function (copyWhenShared) {
  33880. if (!this.isReady()) {
  33881. return null;
  33882. }
  33883. var orig = this._indices;
  33884. if (!copyWhenShared || this._meshes.length === 1) {
  33885. return orig;
  33886. }
  33887. else {
  33888. var len = orig.length;
  33889. var copy = [];
  33890. for (var i = 0; i < len; i++) {
  33891. copy.push(orig[i]);
  33892. }
  33893. return copy;
  33894. }
  33895. };
  33896. Geometry.prototype.getIndexBuffer = function () {
  33897. if (!this.isReady()) {
  33898. return null;
  33899. }
  33900. return this._indexBuffer;
  33901. };
  33902. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  33903. var meshes = this._meshes;
  33904. var index = meshes.indexOf(mesh);
  33905. if (index === -1) {
  33906. return;
  33907. }
  33908. for (var kind in this._vertexBuffers) {
  33909. this._vertexBuffers[kind].dispose();
  33910. }
  33911. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  33912. this._indexBuffer = null;
  33913. }
  33914. meshes.splice(index, 1);
  33915. mesh._geometry = null;
  33916. if (meshes.length === 0 && shouldDispose) {
  33917. this.dispose();
  33918. }
  33919. };
  33920. Geometry.prototype.applyToMesh = function (mesh) {
  33921. if (mesh._geometry === this) {
  33922. return;
  33923. }
  33924. var previousGeometry = mesh._geometry;
  33925. if (previousGeometry) {
  33926. previousGeometry.releaseForMesh(mesh);
  33927. }
  33928. var meshes = this._meshes;
  33929. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  33930. mesh._geometry = this;
  33931. this._scene.pushGeometry(this);
  33932. meshes.push(mesh);
  33933. if (this.isReady()) {
  33934. this._applyToMesh(mesh);
  33935. }
  33936. else {
  33937. mesh._boundingInfo = this._boundingInfo;
  33938. }
  33939. };
  33940. Geometry.prototype.updateExtend = function (data, stride) {
  33941. if (data === void 0) { data = null; }
  33942. if (!data) {
  33943. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  33944. }
  33945. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  33946. };
  33947. Geometry.prototype._applyToMesh = function (mesh) {
  33948. var numOfMeshes = this._meshes.length;
  33949. // vertexBuffers
  33950. for (var kind in this._vertexBuffers) {
  33951. if (numOfMeshes === 1) {
  33952. this._vertexBuffers[kind].create();
  33953. }
  33954. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  33955. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33956. mesh._resetPointsArrayCache();
  33957. if (!this._extend) {
  33958. this.updateExtend(this._vertexBuffers[kind].getData());
  33959. }
  33960. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33961. mesh._createGlobalSubMesh();
  33962. //bounding info was just created again, world matrix should be applied again.
  33963. mesh._updateBoundingInfo();
  33964. }
  33965. }
  33966. // indexBuffer
  33967. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  33968. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33969. }
  33970. if (this._indexBuffer) {
  33971. this._indexBuffer.references = numOfMeshes;
  33972. }
  33973. };
  33974. Geometry.prototype.notifyUpdate = function (kind) {
  33975. if (this.onGeometryUpdated) {
  33976. this.onGeometryUpdated(this, kind);
  33977. }
  33978. };
  33979. Geometry.prototype.load = function (scene, onLoaded) {
  33980. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33981. return;
  33982. }
  33983. if (this.isReady()) {
  33984. if (onLoaded) {
  33985. onLoaded();
  33986. }
  33987. return;
  33988. }
  33989. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33990. this._queueLoad(scene, onLoaded);
  33991. };
  33992. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  33993. var _this = this;
  33994. scene._addPendingData(this);
  33995. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  33996. _this._delayLoadingFunction(JSON.parse(data), _this);
  33997. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33998. _this._delayInfo = [];
  33999. scene._removePendingData(_this);
  34000. var meshes = _this._meshes;
  34001. var numOfMeshes = meshes.length;
  34002. for (var index = 0; index < numOfMeshes; index++) {
  34003. _this._applyToMesh(meshes[index]);
  34004. }
  34005. if (onLoaded) {
  34006. onLoaded();
  34007. }
  34008. }, function () { }, scene.database);
  34009. };
  34010. /**
  34011. * Invert the geometry to move from a right handed system to a left handed one.
  34012. */
  34013. Geometry.prototype.toLeftHanded = function () {
  34014. // Flip faces
  34015. var tIndices = this.getIndices(false);
  34016. if (tIndices != null && tIndices.length > 0) {
  34017. for (var i = 0; i < tIndices.length; i += 3) {
  34018. var tTemp = tIndices[i + 0];
  34019. tIndices[i + 0] = tIndices[i + 2];
  34020. tIndices[i + 2] = tTemp;
  34021. }
  34022. this.setIndices(tIndices);
  34023. }
  34024. // Negate position.z
  34025. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34026. if (tPositions != null && tPositions.length > 0) {
  34027. for (var i = 0; i < tPositions.length; i += 3) {
  34028. tPositions[i + 2] = -tPositions[i + 2];
  34029. }
  34030. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34031. }
  34032. // Negate normal.z
  34033. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34034. if (tNormals != null && tNormals.length > 0) {
  34035. for (var i = 0; i < tNormals.length; i += 3) {
  34036. tNormals[i + 2] = -tNormals[i + 2];
  34037. }
  34038. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34039. }
  34040. };
  34041. Geometry.prototype.isDisposed = function () {
  34042. return this._isDisposed;
  34043. };
  34044. Geometry.prototype.dispose = function () {
  34045. var meshes = this._meshes;
  34046. var numOfMeshes = meshes.length;
  34047. var index;
  34048. for (index = 0; index < numOfMeshes; index++) {
  34049. this.releaseForMesh(meshes[index]);
  34050. }
  34051. this._meshes = [];
  34052. for (var kind in this._vertexBuffers) {
  34053. this._vertexBuffers[kind].dispose();
  34054. }
  34055. this._vertexBuffers = {};
  34056. this._totalVertices = 0;
  34057. if (this._indexBuffer) {
  34058. this._engine._releaseBuffer(this._indexBuffer);
  34059. }
  34060. this._indexBuffer = null;
  34061. this._indices = [];
  34062. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34063. this.delayLoadingFile = null;
  34064. this._delayLoadingFunction = null;
  34065. this._delayInfo = [];
  34066. this._boundingInfo = null;
  34067. this._scene.removeGeometry(this);
  34068. this._isDisposed = true;
  34069. };
  34070. Geometry.prototype.copy = function (id) {
  34071. var vertexData = new BABYLON.VertexData();
  34072. vertexData.indices = [];
  34073. var indices = this.getIndices();
  34074. for (var index = 0; index < indices.length; index++) {
  34075. vertexData.indices.push(indices[index]);
  34076. }
  34077. var updatable = false;
  34078. var stopChecking = false;
  34079. var kind;
  34080. for (kind in this._vertexBuffers) {
  34081. // using slice() to make a copy of the array and not just reference it
  34082. var data = this.getVerticesData(kind);
  34083. if (data instanceof Float32Array) {
  34084. vertexData.set(new Float32Array(data), kind);
  34085. }
  34086. else {
  34087. vertexData.set(data.slice(0), kind);
  34088. }
  34089. if (!stopChecking) {
  34090. updatable = this.getVertexBuffer(kind).isUpdatable();
  34091. stopChecking = !updatable;
  34092. }
  34093. }
  34094. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  34095. geometry.delayLoadState = this.delayLoadState;
  34096. geometry.delayLoadingFile = this.delayLoadingFile;
  34097. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34098. for (kind in this._delayInfo) {
  34099. geometry._delayInfo = geometry._delayInfo || [];
  34100. geometry._delayInfo.push(kind);
  34101. }
  34102. // Bounding info
  34103. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34104. return geometry;
  34105. };
  34106. Geometry.prototype.serialize = function () {
  34107. var serializationObject = {};
  34108. serializationObject.id = this.id;
  34109. if (BABYLON.Tags.HasTags(this)) {
  34110. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34111. }
  34112. return serializationObject;
  34113. };
  34114. Geometry.prototype.serializeVerticeData = function () {
  34115. var serializationObject = this.serialize();
  34116. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34117. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34118. }
  34119. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34120. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34121. }
  34122. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34123. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34124. }
  34125. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34126. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  34127. }
  34128. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34129. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  34130. }
  34131. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34132. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  34133. }
  34134. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34135. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  34136. }
  34137. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34138. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  34139. }
  34140. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34141. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  34142. }
  34143. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34144. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34145. serializationObject.matricesIndices._isExpanded = true;
  34146. }
  34147. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34148. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34149. }
  34150. serializationObject.indices = this.getIndices();
  34151. return serializationObject;
  34152. };
  34153. // Statics
  34154. Geometry.ExtractFromMesh = function (mesh, id) {
  34155. var geometry = mesh._geometry;
  34156. if (!geometry) {
  34157. return null;
  34158. }
  34159. return geometry.copy(id);
  34160. };
  34161. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  34162. // be aware Math.random() could cause collisions
  34163. Geometry.RandomId = function () {
  34164. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  34165. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  34166. return v.toString(16);
  34167. });
  34168. };
  34169. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  34170. var scene = mesh.getScene();
  34171. // Geometry
  34172. var geometryId = parsedGeometry.geometryId;
  34173. if (geometryId) {
  34174. var geometry = scene.getGeometryByID(geometryId);
  34175. if (geometry) {
  34176. geometry.applyToMesh(mesh);
  34177. }
  34178. }
  34179. else if (parsedGeometry instanceof ArrayBuffer) {
  34180. var binaryInfo = mesh._binaryInfo;
  34181. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  34182. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  34183. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  34184. }
  34185. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  34186. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  34187. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  34188. }
  34189. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  34190. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  34191. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  34192. }
  34193. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  34194. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  34195. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  34196. }
  34197. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  34198. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  34199. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  34200. }
  34201. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  34202. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  34203. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  34204. }
  34205. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  34206. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  34207. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  34208. }
  34209. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  34210. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  34211. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  34212. }
  34213. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  34214. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  34215. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  34216. }
  34217. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  34218. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  34219. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  34220. }
  34221. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  34222. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  34223. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  34224. }
  34225. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  34226. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  34227. mesh.setIndices(indicesData);
  34228. }
  34229. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  34230. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  34231. mesh.subMeshes = [];
  34232. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  34233. var materialIndex = subMeshesData[(i * 5) + 0];
  34234. var verticesStart = subMeshesData[(i * 5) + 1];
  34235. var verticesCount = subMeshesData[(i * 5) + 2];
  34236. var indexStart = subMeshesData[(i * 5) + 3];
  34237. var indexCount = subMeshesData[(i * 5) + 4];
  34238. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  34239. }
  34240. }
  34241. }
  34242. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  34243. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  34244. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  34245. if (parsedGeometry.uvs) {
  34246. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  34247. }
  34248. if (parsedGeometry.uvs2) {
  34249. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  34250. }
  34251. if (parsedGeometry.uvs3) {
  34252. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  34253. }
  34254. if (parsedGeometry.uvs4) {
  34255. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  34256. }
  34257. if (parsedGeometry.uvs5) {
  34258. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  34259. }
  34260. if (parsedGeometry.uvs6) {
  34261. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  34262. }
  34263. if (parsedGeometry.colors) {
  34264. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  34265. }
  34266. if (parsedGeometry.matricesIndices) {
  34267. if (!parsedGeometry.matricesIndices._isExpanded) {
  34268. var floatIndices = [];
  34269. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  34270. var matricesIndex = parsedGeometry.matricesIndices[i];
  34271. floatIndices.push(matricesIndex & 0x000000FF);
  34272. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34273. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34274. floatIndices.push(matricesIndex >> 24);
  34275. }
  34276. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  34277. }
  34278. else {
  34279. delete parsedGeometry.matricesIndices._isExpanded;
  34280. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  34281. }
  34282. }
  34283. if (parsedGeometry.matricesIndicesExtra) {
  34284. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  34285. var floatIndices = [];
  34286. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  34287. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  34288. floatIndices.push(matricesIndex & 0x000000FF);
  34289. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34290. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34291. floatIndices.push(matricesIndex >> 24);
  34292. }
  34293. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  34294. }
  34295. else {
  34296. delete parsedGeometry.matricesIndices._isExpanded;
  34297. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  34298. }
  34299. }
  34300. if (parsedGeometry.matricesWeights) {
  34301. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  34302. }
  34303. if (parsedGeometry.matricesWeightsExtra) {
  34304. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  34305. }
  34306. mesh.setIndices(parsedGeometry.indices);
  34307. }
  34308. // SubMeshes
  34309. if (parsedGeometry.subMeshes) {
  34310. mesh.subMeshes = [];
  34311. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  34312. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  34313. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  34314. }
  34315. }
  34316. // Flat shading
  34317. if (mesh._shouldGenerateFlatShading) {
  34318. mesh.convertToFlatShadedMesh();
  34319. delete mesh._shouldGenerateFlatShading;
  34320. }
  34321. // Update
  34322. mesh.computeWorldMatrix(true);
  34323. // Octree
  34324. if (scene['_selectionOctree']) {
  34325. scene['_selectionOctree'].addMesh(mesh);
  34326. }
  34327. };
  34328. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  34329. if (scene.getGeometryByID(parsedVertexData.id)) {
  34330. return null; // null since geometry could be something else than a box...
  34331. }
  34332. var geometry = new Geometry(parsedVertexData.id, scene);
  34333. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  34334. if (parsedVertexData.delayLoadingFile) {
  34335. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  34336. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  34337. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  34338. geometry._delayInfo = [];
  34339. if (parsedVertexData.hasUVs) {
  34340. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  34341. }
  34342. if (parsedVertexData.hasUVs2) {
  34343. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  34344. }
  34345. if (parsedVertexData.hasUVs3) {
  34346. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  34347. }
  34348. if (parsedVertexData.hasUVs4) {
  34349. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  34350. }
  34351. if (parsedVertexData.hasUVs5) {
  34352. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  34353. }
  34354. if (parsedVertexData.hasUVs6) {
  34355. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  34356. }
  34357. if (parsedVertexData.hasColors) {
  34358. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  34359. }
  34360. if (parsedVertexData.hasMatricesIndices) {
  34361. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34362. }
  34363. if (parsedVertexData.hasMatricesWeights) {
  34364. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34365. }
  34366. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  34367. }
  34368. else {
  34369. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  34370. }
  34371. scene.pushGeometry(geometry, true);
  34372. return geometry;
  34373. };
  34374. return Geometry;
  34375. })();
  34376. BABYLON.Geometry = Geometry;
  34377. /////// Primitives //////////////////////////////////////////////
  34378. var Geometry;
  34379. (function (Geometry) {
  34380. var Primitives;
  34381. (function (Primitives) {
  34382. /// Abstract class
  34383. var _Primitive = (function (_super) {
  34384. __extends(_Primitive, _super);
  34385. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  34386. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  34387. this._canBeRegenerated = _canBeRegenerated;
  34388. this._beingRegenerated = true;
  34389. this.regenerate();
  34390. this._beingRegenerated = false;
  34391. }
  34392. _Primitive.prototype.canBeRegenerated = function () {
  34393. return this._canBeRegenerated;
  34394. };
  34395. _Primitive.prototype.regenerate = function () {
  34396. if (!this._canBeRegenerated) {
  34397. return;
  34398. }
  34399. this._beingRegenerated = true;
  34400. this.setAllVerticesData(this._regenerateVertexData(), false);
  34401. this._beingRegenerated = false;
  34402. };
  34403. _Primitive.prototype.asNewGeometry = function (id) {
  34404. return _super.prototype.copy.call(this, id);
  34405. };
  34406. // overrides
  34407. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  34408. if (!this._beingRegenerated) {
  34409. return;
  34410. }
  34411. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  34412. };
  34413. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  34414. if (!this._beingRegenerated) {
  34415. return;
  34416. }
  34417. _super.prototype.setVerticesData.call(this, kind, data, false);
  34418. };
  34419. // to override
  34420. // protected
  34421. _Primitive.prototype._regenerateVertexData = function () {
  34422. throw new Error("Abstract method");
  34423. };
  34424. _Primitive.prototype.copy = function (id) {
  34425. throw new Error("Must be overriden in sub-classes.");
  34426. };
  34427. _Primitive.prototype.serialize = function () {
  34428. var serializationObject = _super.prototype.serialize.call(this);
  34429. serializationObject.canBeRegenerated = this.canBeRegenerated();
  34430. return serializationObject;
  34431. };
  34432. return _Primitive;
  34433. })(Geometry);
  34434. Primitives._Primitive = _Primitive;
  34435. var Ribbon = (function (_super) {
  34436. __extends(Ribbon, _super);
  34437. // Members
  34438. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  34439. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34440. _super.call(this, id, scene, canBeRegenerated, mesh);
  34441. this.pathArray = pathArray;
  34442. this.closeArray = closeArray;
  34443. this.closePath = closePath;
  34444. this.offset = offset;
  34445. this.side = side;
  34446. }
  34447. Ribbon.prototype._regenerateVertexData = function () {
  34448. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  34449. };
  34450. Ribbon.prototype.copy = function (id) {
  34451. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  34452. };
  34453. return Ribbon;
  34454. })(_Primitive);
  34455. Primitives.Ribbon = Ribbon;
  34456. var Box = (function (_super) {
  34457. __extends(Box, _super);
  34458. // Members
  34459. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  34460. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34461. _super.call(this, id, scene, canBeRegenerated, mesh);
  34462. this.size = size;
  34463. this.side = side;
  34464. }
  34465. Box.prototype._regenerateVertexData = function () {
  34466. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  34467. };
  34468. Box.prototype.copy = function (id) {
  34469. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  34470. };
  34471. Box.prototype.serialize = function () {
  34472. var serializationObject = _super.prototype.serialize.call(this);
  34473. serializationObject.size = this.size;
  34474. return serializationObject;
  34475. };
  34476. Box.Parse = function (parsedBox, scene) {
  34477. if (scene.getGeometryByID(parsedBox.id)) {
  34478. return null; // null since geometry could be something else than a box...
  34479. }
  34480. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  34481. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  34482. scene.pushGeometry(box, true);
  34483. return box;
  34484. };
  34485. return Box;
  34486. })(_Primitive);
  34487. Primitives.Box = Box;
  34488. var Sphere = (function (_super) {
  34489. __extends(Sphere, _super);
  34490. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  34491. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34492. _super.call(this, id, scene, canBeRegenerated, mesh);
  34493. this.segments = segments;
  34494. this.diameter = diameter;
  34495. this.side = side;
  34496. }
  34497. Sphere.prototype._regenerateVertexData = function () {
  34498. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  34499. };
  34500. Sphere.prototype.copy = function (id) {
  34501. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  34502. };
  34503. Sphere.prototype.serialize = function () {
  34504. var serializationObject = _super.prototype.serialize.call(this);
  34505. serializationObject.segments = this.segments;
  34506. serializationObject.diameter = this.diameter;
  34507. return serializationObject;
  34508. };
  34509. Sphere.Parse = function (parsedSphere, scene) {
  34510. if (scene.getGeometryByID(parsedSphere.id)) {
  34511. return null; // null since geometry could be something else than a sphere...
  34512. }
  34513. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  34514. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  34515. scene.pushGeometry(sphere, true);
  34516. return sphere;
  34517. };
  34518. return Sphere;
  34519. })(_Primitive);
  34520. Primitives.Sphere = Sphere;
  34521. var Disc = (function (_super) {
  34522. __extends(Disc, _super);
  34523. // Members
  34524. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  34525. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34526. _super.call(this, id, scene, canBeRegenerated, mesh);
  34527. this.radius = radius;
  34528. this.tessellation = tessellation;
  34529. this.side = side;
  34530. }
  34531. Disc.prototype._regenerateVertexData = function () {
  34532. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  34533. };
  34534. Disc.prototype.copy = function (id) {
  34535. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  34536. };
  34537. return Disc;
  34538. })(_Primitive);
  34539. Primitives.Disc = Disc;
  34540. var Cylinder = (function (_super) {
  34541. __extends(Cylinder, _super);
  34542. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  34543. if (subdivisions === void 0) { subdivisions = 1; }
  34544. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34545. _super.call(this, id, scene, canBeRegenerated, mesh);
  34546. this.height = height;
  34547. this.diameterTop = diameterTop;
  34548. this.diameterBottom = diameterBottom;
  34549. this.tessellation = tessellation;
  34550. this.subdivisions = subdivisions;
  34551. this.side = side;
  34552. }
  34553. Cylinder.prototype._regenerateVertexData = function () {
  34554. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  34555. };
  34556. Cylinder.prototype.copy = function (id) {
  34557. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  34558. };
  34559. Cylinder.prototype.serialize = function () {
  34560. var serializationObject = _super.prototype.serialize.call(this);
  34561. serializationObject.height = this.height;
  34562. serializationObject.diameterTop = this.diameterTop;
  34563. serializationObject.diameterBottom = this.diameterBottom;
  34564. serializationObject.tessellation = this.tessellation;
  34565. return serializationObject;
  34566. };
  34567. Cylinder.Parse = function (parsedCylinder, scene) {
  34568. if (scene.getGeometryByID(parsedCylinder.id)) {
  34569. return null; // null since geometry could be something else than a cylinder...
  34570. }
  34571. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  34572. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  34573. scene.pushGeometry(cylinder, true);
  34574. return cylinder;
  34575. };
  34576. return Cylinder;
  34577. })(_Primitive);
  34578. Primitives.Cylinder = Cylinder;
  34579. var Torus = (function (_super) {
  34580. __extends(Torus, _super);
  34581. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  34582. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34583. _super.call(this, id, scene, canBeRegenerated, mesh);
  34584. this.diameter = diameter;
  34585. this.thickness = thickness;
  34586. this.tessellation = tessellation;
  34587. this.side = side;
  34588. }
  34589. Torus.prototype._regenerateVertexData = function () {
  34590. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  34591. };
  34592. Torus.prototype.copy = function (id) {
  34593. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  34594. };
  34595. Torus.prototype.serialize = function () {
  34596. var serializationObject = _super.prototype.serialize.call(this);
  34597. serializationObject.diameter = this.diameter;
  34598. serializationObject.thickness = this.thickness;
  34599. serializationObject.tessellation = this.tessellation;
  34600. return serializationObject;
  34601. };
  34602. Torus.Parse = function (parsedTorus, scene) {
  34603. if (scene.getGeometryByID(parsedTorus.id)) {
  34604. return null; // null since geometry could be something else than a torus...
  34605. }
  34606. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  34607. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  34608. scene.pushGeometry(torus, true);
  34609. return torus;
  34610. };
  34611. return Torus;
  34612. })(_Primitive);
  34613. Primitives.Torus = Torus;
  34614. var Ground = (function (_super) {
  34615. __extends(Ground, _super);
  34616. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  34617. _super.call(this, id, scene, canBeRegenerated, mesh);
  34618. this.width = width;
  34619. this.height = height;
  34620. this.subdivisions = subdivisions;
  34621. }
  34622. Ground.prototype._regenerateVertexData = function () {
  34623. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  34624. };
  34625. Ground.prototype.copy = function (id) {
  34626. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  34627. };
  34628. Ground.prototype.serialize = function () {
  34629. var serializationObject = _super.prototype.serialize.call(this);
  34630. serializationObject.width = this.width;
  34631. serializationObject.height = this.height;
  34632. serializationObject.subdivisions = this.subdivisions;
  34633. return serializationObject;
  34634. };
  34635. Ground.Parse = function (parsedGround, scene) {
  34636. if (scene.getGeometryByID(parsedGround.id)) {
  34637. return null; // null since geometry could be something else than a ground...
  34638. }
  34639. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  34640. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  34641. scene.pushGeometry(ground, true);
  34642. return ground;
  34643. };
  34644. return Ground;
  34645. })(_Primitive);
  34646. Primitives.Ground = Ground;
  34647. var TiledGround = (function (_super) {
  34648. __extends(TiledGround, _super);
  34649. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  34650. _super.call(this, id, scene, canBeRegenerated, mesh);
  34651. this.xmin = xmin;
  34652. this.zmin = zmin;
  34653. this.xmax = xmax;
  34654. this.zmax = zmax;
  34655. this.subdivisions = subdivisions;
  34656. this.precision = precision;
  34657. }
  34658. TiledGround.prototype._regenerateVertexData = function () {
  34659. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  34660. };
  34661. TiledGround.prototype.copy = function (id) {
  34662. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  34663. };
  34664. return TiledGround;
  34665. })(_Primitive);
  34666. Primitives.TiledGround = TiledGround;
  34667. var Plane = (function (_super) {
  34668. __extends(Plane, _super);
  34669. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  34670. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34671. _super.call(this, id, scene, canBeRegenerated, mesh);
  34672. this.size = size;
  34673. this.side = side;
  34674. }
  34675. Plane.prototype._regenerateVertexData = function () {
  34676. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  34677. };
  34678. Plane.prototype.copy = function (id) {
  34679. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  34680. };
  34681. Plane.prototype.serialize = function () {
  34682. var serializationObject = _super.prototype.serialize.call(this);
  34683. serializationObject.size = this.size;
  34684. return serializationObject;
  34685. };
  34686. Plane.Parse = function (parsedPlane, scene) {
  34687. if (scene.getGeometryByID(parsedPlane.id)) {
  34688. return null; // null since geometry could be something else than a ground...
  34689. }
  34690. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  34691. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  34692. scene.pushGeometry(plane, true);
  34693. return plane;
  34694. };
  34695. return Plane;
  34696. })(_Primitive);
  34697. Primitives.Plane = Plane;
  34698. var TorusKnot = (function (_super) {
  34699. __extends(TorusKnot, _super);
  34700. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  34701. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34702. _super.call(this, id, scene, canBeRegenerated, mesh);
  34703. this.radius = radius;
  34704. this.tube = tube;
  34705. this.radialSegments = radialSegments;
  34706. this.tubularSegments = tubularSegments;
  34707. this.p = p;
  34708. this.q = q;
  34709. this.side = side;
  34710. }
  34711. TorusKnot.prototype._regenerateVertexData = function () {
  34712. 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 });
  34713. };
  34714. TorusKnot.prototype.copy = function (id) {
  34715. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  34716. };
  34717. TorusKnot.prototype.serialize = function () {
  34718. var serializationObject = _super.prototype.serialize.call(this);
  34719. serializationObject.radius = this.radius;
  34720. serializationObject.tube = this.tube;
  34721. serializationObject.radialSegments = this.radialSegments;
  34722. serializationObject.tubularSegments = this.tubularSegments;
  34723. serializationObject.p = this.p;
  34724. serializationObject.q = this.q;
  34725. return serializationObject;
  34726. };
  34727. ;
  34728. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  34729. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  34730. return null; // null since geometry could be something else than a ground...
  34731. }
  34732. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  34733. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  34734. scene.pushGeometry(torusKnot, true);
  34735. return torusKnot;
  34736. };
  34737. return TorusKnot;
  34738. })(_Primitive);
  34739. Primitives.TorusKnot = TorusKnot;
  34740. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  34741. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  34742. })(BABYLON || (BABYLON = {}));
  34743. var BABYLON;
  34744. (function (BABYLON) {
  34745. var GroundMesh = (function (_super) {
  34746. __extends(GroundMesh, _super);
  34747. function GroundMesh(name, scene) {
  34748. _super.call(this, name, scene);
  34749. this.generateOctree = false;
  34750. this._worldInverse = new BABYLON.Matrix();
  34751. }
  34752. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  34753. get: function () {
  34754. return this._subdivisions;
  34755. },
  34756. enumerable: true,
  34757. configurable: true
  34758. });
  34759. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  34760. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  34761. this._subdivisions = chunksCount;
  34762. this.subdivide(this._subdivisions);
  34763. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  34764. };
  34765. /**
  34766. * Returns a height (y) value in the Worl system :
  34767. * the ground altitude at the coordinates (x, z) expressed in the World system.
  34768. * Returns the ground y position if (x, z) are outside the ground surface.
  34769. * Not pertinent if the ground is rotated.
  34770. */
  34771. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  34772. // express x and y in the ground local system
  34773. x -= this.position.x;
  34774. z -= this.position.z;
  34775. x /= this.scaling.x;
  34776. z /= this.scaling.z;
  34777. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  34778. return this.position.y;
  34779. }
  34780. if (!this._heightQuads || this._heightQuads.length == 0) {
  34781. this._initHeightQuads();
  34782. this._computeHeightQuads();
  34783. }
  34784. var facet = this._getFacetAt(x, z);
  34785. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  34786. // return y in the World system
  34787. return y * this.scaling.y + this.position.y;
  34788. };
  34789. /**
  34790. * Returns a normalized vector (Vector3) orthogonal to the ground
  34791. * at the ground coordinates (x, z) expressed in the World system.
  34792. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  34793. * Not pertinent if the ground is rotated.
  34794. */
  34795. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  34796. var normal = new BABYLON.Vector3(0, 1, 0);
  34797. this.getNormalAtCoordinatesToRef(x, z, normal);
  34798. return normal;
  34799. };
  34800. /**
  34801. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  34802. * at the ground coordinates (x, z) expressed in the World system.
  34803. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  34804. * Not pertinent if the ground is rotated.
  34805. */
  34806. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  34807. // express x and y in the ground local system
  34808. x -= this.position.x;
  34809. z -= this.position.z;
  34810. x /= this.scaling.x;
  34811. z /= this.scaling.z;
  34812. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  34813. return;
  34814. }
  34815. if (!this._heightQuads || this._heightQuads.length == 0) {
  34816. this._initHeightQuads();
  34817. this._computeHeightQuads();
  34818. }
  34819. var facet = this._getFacetAt(x, z);
  34820. ref.x = facet.x;
  34821. ref.y = facet.y;
  34822. ref.z = facet.z;
  34823. };
  34824. /**
  34825. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  34826. * if the ground has been updated.
  34827. * This can be used in the render loop
  34828. */
  34829. GroundMesh.prototype.updateCoordinateHeights = function () {
  34830. if (!this._heightQuads || this._heightQuads.length == 0) {
  34831. this._initHeightQuads();
  34832. }
  34833. this._computeHeightQuads();
  34834. };
  34835. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  34836. GroundMesh.prototype._getFacetAt = function (x, z) {
  34837. // retrieve col and row from x, z coordinates in the ground local system
  34838. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  34839. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  34840. var quad = this._heightQuads[row * this._subdivisions + col];
  34841. var facet;
  34842. if (z < quad.slope.x * x + quad.slope.y) {
  34843. facet = quad.facet1;
  34844. }
  34845. else {
  34846. facet = quad.facet2;
  34847. }
  34848. return facet;
  34849. };
  34850. // Creates and populates the heightMap array with "facet" elements :
  34851. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  34852. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34853. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34854. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34855. GroundMesh.prototype._initHeightQuads = function () {
  34856. this._heightQuads = new Array();
  34857. for (var row = 0; row < this._subdivisions; row++) {
  34858. for (var col = 0; col < this._subdivisions; col++) {
  34859. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  34860. this._heightQuads[row * this._subdivisions + col] = quad;
  34861. }
  34862. }
  34863. };
  34864. // Compute each quad element values and update the the heightMap array :
  34865. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34866. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34867. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34868. GroundMesh.prototype._computeHeightQuads = function () {
  34869. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34870. var v1 = BABYLON.Tmp.Vector3[3];
  34871. var v2 = BABYLON.Tmp.Vector3[2];
  34872. var v3 = BABYLON.Tmp.Vector3[1];
  34873. var v4 = BABYLON.Tmp.Vector3[0];
  34874. var v1v2 = BABYLON.Tmp.Vector3[4];
  34875. var v1v3 = BABYLON.Tmp.Vector3[5];
  34876. var v1v4 = BABYLON.Tmp.Vector3[6];
  34877. var norm1 = BABYLON.Tmp.Vector3[7];
  34878. var norm2 = BABYLON.Tmp.Vector3[8];
  34879. var i = 0;
  34880. var j = 0;
  34881. var k = 0;
  34882. var cd = 0; // 2D slope coefficient : z = cd * x + h
  34883. var h = 0;
  34884. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  34885. var d2 = 0;
  34886. for (var row = 0; row < this._subdivisions; row++) {
  34887. for (var col = 0; col < this._subdivisions; col++) {
  34888. i = col * 3;
  34889. j = row * (this._subdivisions + 1) * 3;
  34890. k = (row + 1) * (this._subdivisions + 1) * 3;
  34891. v1.x = positions[j + i];
  34892. v1.y = positions[j + i + 1];
  34893. v1.z = positions[j + i + 2];
  34894. v2.x = positions[j + i + 3];
  34895. v2.y = positions[j + i + 4];
  34896. v2.z = positions[j + i + 5];
  34897. v3.x = positions[k + i];
  34898. v3.y = positions[k + i + 1];
  34899. v3.z = positions[k + i + 2];
  34900. v4.x = positions[k + i + 3];
  34901. v4.y = positions[k + i + 4];
  34902. v4.z = positions[k + i + 5];
  34903. // 2D slope V1V4
  34904. cd = (v4.z - v1.z) / (v4.x - v1.x);
  34905. h = v1.z - cd * v1.x; // v1 belongs to the slope
  34906. // facet equations :
  34907. // we compute each facet normal vector
  34908. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  34909. // we compute the value d by applying the equation to v1 which belongs to the plane
  34910. // then we store the facet equation in a Vector4
  34911. v2.subtractToRef(v1, v1v2);
  34912. v3.subtractToRef(v1, v1v3);
  34913. v4.subtractToRef(v1, v1v4);
  34914. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  34915. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  34916. norm1.normalize();
  34917. norm2.normalize();
  34918. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  34919. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  34920. var quad = this._heightQuads[row * this._subdivisions + col];
  34921. quad.slope.copyFromFloats(cd, h);
  34922. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  34923. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  34924. }
  34925. }
  34926. };
  34927. return GroundMesh;
  34928. })(BABYLON.Mesh);
  34929. BABYLON.GroundMesh = GroundMesh;
  34930. })(BABYLON || (BABYLON = {}));
  34931. var BABYLON;
  34932. (function (BABYLON) {
  34933. var LinesMesh = (function (_super) {
  34934. __extends(LinesMesh, _super);
  34935. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  34936. if (parent === void 0) { parent = null; }
  34937. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  34938. this.color = new BABYLON.Color3(1, 1, 1);
  34939. this.alpha = 1;
  34940. this._positionBuffer = {};
  34941. if (source) {
  34942. this.color = source.color.clone();
  34943. this.alpha = source.alpha;
  34944. }
  34945. this._intersectionThreshold = 0.1;
  34946. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  34947. attributes: [BABYLON.VertexBuffer.PositionKind],
  34948. uniforms: ["worldViewProjection", "color"],
  34949. needAlphaBlending: true
  34950. });
  34951. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  34952. }
  34953. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  34954. /**
  34955. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  34956. * This margin is expressed in world space coordinates, so its value may vary.
  34957. * Default value is 0.1
  34958. * @returns the intersection Threshold value.
  34959. */
  34960. get: function () {
  34961. return this._intersectionThreshold;
  34962. },
  34963. /**
  34964. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  34965. * This margin is expressed in world space coordinates, so its value may vary.
  34966. * @param value the new threshold to apply
  34967. */
  34968. set: function (value) {
  34969. if (this._intersectionThreshold === value) {
  34970. return;
  34971. }
  34972. this._intersectionThreshold = value;
  34973. if (this.geometry) {
  34974. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  34975. }
  34976. },
  34977. enumerable: true,
  34978. configurable: true
  34979. });
  34980. Object.defineProperty(LinesMesh.prototype, "material", {
  34981. get: function () {
  34982. return this._colorShader;
  34983. },
  34984. enumerable: true,
  34985. configurable: true
  34986. });
  34987. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  34988. get: function () {
  34989. return false;
  34990. },
  34991. enumerable: true,
  34992. configurable: true
  34993. });
  34994. LinesMesh.prototype.createInstance = function (name) {
  34995. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  34996. return null;
  34997. };
  34998. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  34999. var engine = this.getScene().getEngine();
  35000. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  35001. // VBOs
  35002. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  35003. // Color
  35004. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  35005. };
  35006. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  35007. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  35008. return;
  35009. }
  35010. var engine = this.getScene().getEngine();
  35011. // Draw order
  35012. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  35013. };
  35014. LinesMesh.prototype.dispose = function (doNotRecurse) {
  35015. this._colorShader.dispose();
  35016. _super.prototype.dispose.call(this, doNotRecurse);
  35017. };
  35018. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  35019. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  35020. };
  35021. return LinesMesh;
  35022. })(BABYLON.Mesh);
  35023. BABYLON.LinesMesh = LinesMesh;
  35024. })(BABYLON || (BABYLON = {}));
  35025. var BABYLON;
  35026. (function (BABYLON) {
  35027. var DefaultLoadingScreen = (function () {
  35028. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  35029. var _this = this;
  35030. if (_loadingText === void 0) { _loadingText = ""; }
  35031. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  35032. this._renderingCanvas = _renderingCanvas;
  35033. this._loadingText = _loadingText;
  35034. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  35035. // Resize
  35036. this._resizeLoadingUI = function () {
  35037. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  35038. _this._loadingDiv.style.position = "absolute";
  35039. _this._loadingDiv.style.left = canvasRect.left + "px";
  35040. _this._loadingDiv.style.top = canvasRect.top + "px";
  35041. _this._loadingDiv.style.width = canvasRect.width + "px";
  35042. _this._loadingDiv.style.height = canvasRect.height + "px";
  35043. };
  35044. }
  35045. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  35046. var _this = this;
  35047. if (this._loadingDiv) {
  35048. // Do not add a loading screen if there is already one
  35049. return;
  35050. }
  35051. this._loadingDiv = document.createElement("div");
  35052. this._loadingDiv.id = "babylonjsLoadingDiv";
  35053. this._loadingDiv.style.opacity = "0";
  35054. this._loadingDiv.style.transition = "opacity 1.5s ease";
  35055. // Loading text
  35056. this._loadingTextDiv = document.createElement("div");
  35057. this._loadingTextDiv.style.position = "absolute";
  35058. this._loadingTextDiv.style.left = "0";
  35059. this._loadingTextDiv.style.top = "50%";
  35060. this._loadingTextDiv.style.marginTop = "80px";
  35061. this._loadingTextDiv.style.width = "100%";
  35062. this._loadingTextDiv.style.height = "20px";
  35063. this._loadingTextDiv.style.fontFamily = "Arial";
  35064. this._loadingTextDiv.style.fontSize = "14px";
  35065. this._loadingTextDiv.style.color = "white";
  35066. this._loadingTextDiv.style.textAlign = "center";
  35067. this._loadingTextDiv.innerHTML = "Loading";
  35068. this._loadingDiv.appendChild(this._loadingTextDiv);
  35069. //set the predefined text
  35070. this._loadingTextDiv.innerHTML = this._loadingText;
  35071. // Loading img
  35072. var imgBack = new Image();
  35073. 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==";
  35074. imgBack.style.position = "absolute";
  35075. imgBack.style.left = "50%";
  35076. imgBack.style.top = "50%";
  35077. imgBack.style.marginLeft = "-50px";
  35078. imgBack.style.marginTop = "-50px";
  35079. imgBack.style.transition = "transform 1.0s ease";
  35080. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  35081. var deg = 360;
  35082. var onTransitionEnd = function () {
  35083. deg += 360;
  35084. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  35085. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  35086. };
  35087. imgBack.addEventListener("transitionend", onTransitionEnd);
  35088. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  35089. this._loadingDiv.appendChild(imgBack);
  35090. // front image
  35091. var imgFront = new Image();
  35092. 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=";
  35093. imgFront.style.position = "absolute";
  35094. imgFront.style.left = "50%";
  35095. imgFront.style.top = "50%";
  35096. imgFront.style.marginLeft = "-50px";
  35097. imgFront.style.marginTop = "-50px";
  35098. this._loadingDiv.appendChild(imgFront);
  35099. this._resizeLoadingUI();
  35100. window.addEventListener("resize", this._resizeLoadingUI);
  35101. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  35102. document.body.appendChild(this._loadingDiv);
  35103. setTimeout(function () {
  35104. _this._loadingDiv.style.opacity = "1";
  35105. imgBack.style.transform = "rotateZ(360deg)";
  35106. imgBack.style.webkitTransform = "rotateZ(360deg)";
  35107. }, 0);
  35108. };
  35109. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  35110. var _this = this;
  35111. if (!this._loadingDiv) {
  35112. return;
  35113. }
  35114. var onTransitionEnd = function () {
  35115. if (!_this._loadingDiv) {
  35116. return;
  35117. }
  35118. document.body.removeChild(_this._loadingDiv);
  35119. window.removeEventListener("resize", _this._resizeLoadingUI);
  35120. _this._loadingDiv = null;
  35121. };
  35122. this._loadingDiv.style.opacity = "0";
  35123. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  35124. };
  35125. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  35126. set: function (text) {
  35127. this._loadingText = text;
  35128. if (this._loadingTextDiv) {
  35129. this._loadingTextDiv.innerHTML = this._loadingText;
  35130. }
  35131. },
  35132. enumerable: true,
  35133. configurable: true
  35134. });
  35135. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  35136. get: function () {
  35137. return this._loadingDivBackgroundColor;
  35138. },
  35139. set: function (color) {
  35140. this._loadingDivBackgroundColor = color;
  35141. if (!this._loadingDiv) {
  35142. return;
  35143. }
  35144. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  35145. },
  35146. enumerable: true,
  35147. configurable: true
  35148. });
  35149. return DefaultLoadingScreen;
  35150. })();
  35151. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  35152. })(BABYLON || (BABYLON = {}));
  35153. var BABYLON;
  35154. (function (BABYLON) {
  35155. var AudioEngine = (function () {
  35156. function AudioEngine() {
  35157. this._audioContext = null;
  35158. this._audioContextInitialized = false;
  35159. this.canUseWebAudio = false;
  35160. this.WarnedWebAudioUnsupported = false;
  35161. this.unlocked = false;
  35162. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  35163. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  35164. this.canUseWebAudio = true;
  35165. }
  35166. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  35167. this._unlockiOSaudio();
  35168. }
  35169. else {
  35170. this.unlocked = true;
  35171. }
  35172. }
  35173. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  35174. get: function () {
  35175. if (!this._audioContextInitialized) {
  35176. this._initializeAudioContext();
  35177. }
  35178. return this._audioContext;
  35179. },
  35180. enumerable: true,
  35181. configurable: true
  35182. });
  35183. AudioEngine.prototype._unlockiOSaudio = function () {
  35184. var _this = this;
  35185. var unlockaudio = function () {
  35186. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  35187. var source = _this.audioContext.createBufferSource();
  35188. source.buffer = buffer;
  35189. source.connect(_this.audioContext.destination);
  35190. source.start(0);
  35191. setTimeout(function () {
  35192. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  35193. _this.unlocked = true;
  35194. window.removeEventListener('touchend', unlockaudio, false);
  35195. if (_this.onAudioUnlocked) {
  35196. _this.onAudioUnlocked();
  35197. }
  35198. }
  35199. }, 0);
  35200. };
  35201. window.addEventListener('touchend', unlockaudio, false);
  35202. };
  35203. AudioEngine.prototype._initializeAudioContext = function () {
  35204. try {
  35205. if (this.canUseWebAudio) {
  35206. this._audioContext = new AudioContext();
  35207. // create a global volume gain node
  35208. this.masterGain = this._audioContext.createGain();
  35209. this.masterGain.gain.value = 1;
  35210. this.masterGain.connect(this._audioContext.destination);
  35211. this._audioContextInitialized = true;
  35212. }
  35213. }
  35214. catch (e) {
  35215. this.canUseWebAudio = false;
  35216. BABYLON.Tools.Error("Web Audio: " + e.message);
  35217. }
  35218. };
  35219. AudioEngine.prototype.dispose = function () {
  35220. if (this.canUseWebAudio && this._audioContextInitialized) {
  35221. if (this._connectedAnalyser) {
  35222. this._connectedAnalyser.stopDebugCanvas();
  35223. this._connectedAnalyser.dispose();
  35224. this.masterGain.disconnect();
  35225. this.masterGain.connect(this._audioContext.destination);
  35226. this._connectedAnalyser = null;
  35227. }
  35228. this.masterGain.gain.value = 1;
  35229. }
  35230. this.WarnedWebAudioUnsupported = false;
  35231. };
  35232. AudioEngine.prototype.getGlobalVolume = function () {
  35233. if (this.canUseWebAudio && this._audioContextInitialized) {
  35234. return this.masterGain.gain.value;
  35235. }
  35236. else {
  35237. return -1;
  35238. }
  35239. };
  35240. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  35241. if (this.canUseWebAudio && this._audioContextInitialized) {
  35242. this.masterGain.gain.value = newVolume;
  35243. }
  35244. };
  35245. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  35246. if (this._connectedAnalyser) {
  35247. this._connectedAnalyser.stopDebugCanvas();
  35248. }
  35249. if (this.canUseWebAudio && this._audioContextInitialized) {
  35250. this._connectedAnalyser = analyser;
  35251. this.masterGain.disconnect();
  35252. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  35253. }
  35254. };
  35255. return AudioEngine;
  35256. })();
  35257. BABYLON.AudioEngine = AudioEngine;
  35258. })(BABYLON || (BABYLON = {}));
  35259. var BABYLON;
  35260. (function (BABYLON) {
  35261. var Sound = (function () {
  35262. /**
  35263. * Create a sound and attach it to a scene
  35264. * @param name Name of your sound
  35265. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  35266. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  35267. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  35268. */
  35269. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  35270. var _this = this;
  35271. this.autoplay = false;
  35272. this.loop = false;
  35273. this.useCustomAttenuation = false;
  35274. this.spatialSound = false;
  35275. this.refDistance = 1;
  35276. this.rolloffFactor = 1;
  35277. this.maxDistance = 100;
  35278. this.distanceModel = "linear";
  35279. this._panningModel = "equalpower";
  35280. this._playbackRate = 1;
  35281. this._streaming = false;
  35282. this._startTime = 0;
  35283. this._startOffset = 0;
  35284. this._position = BABYLON.Vector3.Zero();
  35285. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  35286. this._volume = 1;
  35287. this._isLoaded = false;
  35288. this._isReadyToPlay = false;
  35289. this.isPlaying = false;
  35290. this.isPaused = false;
  35291. this._isDirectional = false;
  35292. // Used if you'd like to create a directional sound.
  35293. // If not set, the sound will be omnidirectional
  35294. this._coneInnerAngle = 360;
  35295. this._coneOuterAngle = 360;
  35296. this._coneOuterGain = 0;
  35297. this._isOutputConnected = false;
  35298. this.name = name;
  35299. this._scene = scene;
  35300. this._readyToPlayCallback = readyToPlayCallback;
  35301. // Default custom attenuation function is a linear attenuation
  35302. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  35303. if (currentDistance < maxDistance) {
  35304. return currentVolume * (1 - currentDistance / maxDistance);
  35305. }
  35306. else {
  35307. return 0;
  35308. }
  35309. };
  35310. if (options) {
  35311. this.autoplay = options.autoplay || false;
  35312. this.loop = options.loop || false;
  35313. // if volume === 0, we need another way to check this option
  35314. if (options.volume !== undefined) {
  35315. this._volume = options.volume;
  35316. }
  35317. this.spatialSound = options.spatialSound || false;
  35318. this.maxDistance = options.maxDistance || 100;
  35319. this.useCustomAttenuation = options.useCustomAttenuation || false;
  35320. this.rolloffFactor = options.rolloffFactor || 1;
  35321. this.refDistance = options.refDistance || 1;
  35322. this.distanceModel = options.distanceModel || "linear";
  35323. this._playbackRate = options.playbackRate || 1;
  35324. this._streaming = options.streaming || false;
  35325. }
  35326. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35327. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  35328. this._soundGain.gain.value = this._volume;
  35329. this._inputAudioNode = this._soundGain;
  35330. this._ouputAudioNode = this._soundGain;
  35331. if (this.spatialSound) {
  35332. this._createSpatialParameters();
  35333. }
  35334. this._scene.mainSoundTrack.AddSound(this);
  35335. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  35336. if (urlOrArrayBuffer) {
  35337. // If it's an URL
  35338. if (typeof (urlOrArrayBuffer) === "string") {
  35339. // Loading sound using XHR2
  35340. if (!this._streaming) {
  35341. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  35342. }
  35343. else {
  35344. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  35345. this._htmlAudioElement.controls = false;
  35346. this._htmlAudioElement.loop = this.loop;
  35347. this._htmlAudioElement.crossOrigin = "anonymous";
  35348. this._htmlAudioElement.preload = "auto";
  35349. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  35350. _this._isReadyToPlay = true;
  35351. if (_this.autoplay) {
  35352. _this.play();
  35353. }
  35354. if (_this._readyToPlayCallback) {
  35355. _this._readyToPlayCallback();
  35356. }
  35357. });
  35358. document.body.appendChild(this._htmlAudioElement);
  35359. }
  35360. }
  35361. else {
  35362. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  35363. if (urlOrArrayBuffer.byteLength > 0) {
  35364. this._soundLoaded(urlOrArrayBuffer);
  35365. }
  35366. }
  35367. else {
  35368. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  35369. }
  35370. }
  35371. }
  35372. }
  35373. else {
  35374. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  35375. this._scene.mainSoundTrack.AddSound(this);
  35376. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  35377. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  35378. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  35379. }
  35380. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  35381. if (this._readyToPlayCallback) {
  35382. window.setTimeout(function () {
  35383. _this._readyToPlayCallback();
  35384. }, 1000);
  35385. }
  35386. }
  35387. }
  35388. Sound.prototype.dispose = function () {
  35389. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  35390. if (this.isPlaying) {
  35391. this.stop();
  35392. }
  35393. this._isReadyToPlay = false;
  35394. if (this.soundTrackId === -1) {
  35395. this._scene.mainSoundTrack.RemoveSound(this);
  35396. }
  35397. else {
  35398. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  35399. }
  35400. if (this._soundGain) {
  35401. this._soundGain.disconnect();
  35402. this._soundGain = null;
  35403. }
  35404. if (this._soundPanner) {
  35405. this._soundPanner.disconnect();
  35406. this._soundPanner = null;
  35407. }
  35408. if (this._soundSource) {
  35409. this._soundSource.disconnect();
  35410. this._soundSource = null;
  35411. }
  35412. this._audioBuffer = null;
  35413. if (this._htmlAudioElement) {
  35414. this._htmlAudioElement.pause();
  35415. this._htmlAudioElement.src = "";
  35416. document.body.removeChild(this._htmlAudioElement);
  35417. }
  35418. if (this._connectedMesh) {
  35419. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35420. this._connectedMesh = null;
  35421. }
  35422. }
  35423. };
  35424. Sound.prototype._soundLoaded = function (audioData) {
  35425. var _this = this;
  35426. this._isLoaded = true;
  35427. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  35428. _this._audioBuffer = buffer;
  35429. _this._isReadyToPlay = true;
  35430. if (_this.autoplay) {
  35431. _this.play();
  35432. }
  35433. if (_this._readyToPlayCallback) {
  35434. _this._readyToPlayCallback();
  35435. }
  35436. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  35437. };
  35438. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  35439. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35440. this._audioBuffer = audioBuffer;
  35441. this._isReadyToPlay = true;
  35442. }
  35443. };
  35444. Sound.prototype.updateOptions = function (options) {
  35445. if (options) {
  35446. this.loop = options.loop || this.loop;
  35447. this.maxDistance = options.maxDistance || this.maxDistance;
  35448. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  35449. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  35450. this.refDistance = options.refDistance || this.refDistance;
  35451. this.distanceModel = options.distanceModel || this.distanceModel;
  35452. this._playbackRate = options.playbackRate || this._playbackRate;
  35453. this._updateSpatialParameters();
  35454. if (this.isPlaying) {
  35455. if (this._streaming) {
  35456. this._htmlAudioElement.playbackRate = this._playbackRate;
  35457. }
  35458. else {
  35459. this._soundSource.playbackRate.value = this._playbackRate;
  35460. }
  35461. }
  35462. }
  35463. };
  35464. Sound.prototype._createSpatialParameters = function () {
  35465. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35466. if (this._scene.headphone) {
  35467. this._panningModel = "HRTF";
  35468. }
  35469. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  35470. this._updateSpatialParameters();
  35471. this._soundPanner.connect(this._ouputAudioNode);
  35472. this._inputAudioNode = this._soundPanner;
  35473. }
  35474. };
  35475. Sound.prototype._updateSpatialParameters = function () {
  35476. if (this.spatialSound) {
  35477. if (this.useCustomAttenuation) {
  35478. // Tricks to disable in a way embedded Web Audio attenuation
  35479. this._soundPanner.distanceModel = "linear";
  35480. this._soundPanner.maxDistance = Number.MAX_VALUE;
  35481. this._soundPanner.refDistance = 1;
  35482. this._soundPanner.rolloffFactor = 1;
  35483. this._soundPanner.panningModel = this._panningModel;
  35484. }
  35485. else {
  35486. this._soundPanner.distanceModel = this.distanceModel;
  35487. this._soundPanner.maxDistance = this.maxDistance;
  35488. this._soundPanner.refDistance = this.refDistance;
  35489. this._soundPanner.rolloffFactor = this.rolloffFactor;
  35490. this._soundPanner.panningModel = this._panningModel;
  35491. }
  35492. }
  35493. };
  35494. Sound.prototype.switchPanningModelToHRTF = function () {
  35495. this._panningModel = "HRTF";
  35496. this._switchPanningModel();
  35497. };
  35498. Sound.prototype.switchPanningModelToEqualPower = function () {
  35499. this._panningModel = "equalpower";
  35500. this._switchPanningModel();
  35501. };
  35502. Sound.prototype._switchPanningModel = function () {
  35503. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  35504. this._soundPanner.panningModel = this._panningModel;
  35505. }
  35506. };
  35507. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  35508. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35509. if (this._isOutputConnected) {
  35510. this._ouputAudioNode.disconnect();
  35511. }
  35512. this._ouputAudioNode.connect(soundTrackAudioNode);
  35513. this._isOutputConnected = true;
  35514. }
  35515. };
  35516. /**
  35517. * Transform this sound into a directional source
  35518. * @param coneInnerAngle Size of the inner cone in degree
  35519. * @param coneOuterAngle Size of the outer cone in degree
  35520. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  35521. */
  35522. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  35523. if (coneOuterAngle < coneInnerAngle) {
  35524. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  35525. return;
  35526. }
  35527. this._coneInnerAngle = coneInnerAngle;
  35528. this._coneOuterAngle = coneOuterAngle;
  35529. this._coneOuterGain = coneOuterGain;
  35530. this._isDirectional = true;
  35531. if (this.isPlaying && this.loop) {
  35532. this.stop();
  35533. this.play();
  35534. }
  35535. };
  35536. Sound.prototype.setPosition = function (newPosition) {
  35537. this._position = newPosition;
  35538. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  35539. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35540. }
  35541. };
  35542. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  35543. this._localDirection = newLocalDirection;
  35544. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  35545. this._updateDirection();
  35546. }
  35547. };
  35548. Sound.prototype._updateDirection = function () {
  35549. var mat = this._connectedMesh.getWorldMatrix();
  35550. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  35551. direction.normalize();
  35552. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  35553. };
  35554. Sound.prototype.updateDistanceFromListener = function () {
  35555. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  35556. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  35557. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  35558. }
  35559. };
  35560. Sound.prototype.setAttenuationFunction = function (callback) {
  35561. this._customAttenuationFunction = callback;
  35562. };
  35563. /**
  35564. * Play the sound
  35565. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  35566. * @param offset (optional) Start the sound setting it at a specific time
  35567. */
  35568. Sound.prototype.play = function (time, offset) {
  35569. var _this = this;
  35570. if (this._isReadyToPlay && this._scene.audioEnabled) {
  35571. try {
  35572. if (this._startOffset < 0) {
  35573. time = -this._startOffset;
  35574. this._startOffset = 0;
  35575. }
  35576. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35577. if (!this._soundSource || !this._streamingSource) {
  35578. if (this.spatialSound) {
  35579. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35580. if (this._isDirectional) {
  35581. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  35582. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  35583. this._soundPanner.coneOuterGain = this._coneOuterGain;
  35584. if (this._connectedMesh) {
  35585. this._updateDirection();
  35586. }
  35587. else {
  35588. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  35589. }
  35590. }
  35591. }
  35592. }
  35593. if (this._streaming) {
  35594. if (!this._streamingSource) {
  35595. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  35596. this._htmlAudioElement.onended = function () { _this._onended(); };
  35597. this._htmlAudioElement.playbackRate = this._playbackRate;
  35598. }
  35599. this._streamingSource.disconnect();
  35600. this._streamingSource.connect(this._inputAudioNode);
  35601. this._htmlAudioElement.play();
  35602. }
  35603. else {
  35604. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  35605. this._soundSource.buffer = this._audioBuffer;
  35606. this._soundSource.connect(this._inputAudioNode);
  35607. this._soundSource.loop = this.loop;
  35608. this._soundSource.playbackRate.value = this._playbackRate;
  35609. this._soundSource.onended = function () { _this._onended(); };
  35610. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  35611. }
  35612. this._startTime = startTime;
  35613. this.isPlaying = true;
  35614. this.isPaused = false;
  35615. }
  35616. catch (ex) {
  35617. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  35618. }
  35619. }
  35620. };
  35621. Sound.prototype._onended = function () {
  35622. this.isPlaying = false;
  35623. if (this.onended) {
  35624. this.onended();
  35625. }
  35626. };
  35627. /**
  35628. * Stop the sound
  35629. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  35630. */
  35631. Sound.prototype.stop = function (time) {
  35632. if (this.isPlaying) {
  35633. if (this._streaming) {
  35634. this._htmlAudioElement.pause();
  35635. // Test needed for Firefox or it will generate an Invalid State Error
  35636. if (this._htmlAudioElement.currentTime > 0) {
  35637. this._htmlAudioElement.currentTime = 0;
  35638. }
  35639. }
  35640. else {
  35641. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35642. this._soundSource.stop(stopTime);
  35643. this._soundSource.onended = null;
  35644. if (!this.isPaused) {
  35645. this._startOffset = 0;
  35646. }
  35647. }
  35648. this.isPlaying = false;
  35649. }
  35650. };
  35651. Sound.prototype.pause = function () {
  35652. if (this.isPlaying) {
  35653. this.isPaused = true;
  35654. if (this._streaming) {
  35655. this._htmlAudioElement.pause();
  35656. }
  35657. else {
  35658. this.stop(0);
  35659. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  35660. }
  35661. }
  35662. };
  35663. Sound.prototype.setVolume = function (newVolume, time) {
  35664. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35665. if (time) {
  35666. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  35667. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  35668. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  35669. }
  35670. else {
  35671. this._soundGain.gain.value = newVolume;
  35672. }
  35673. }
  35674. this._volume = newVolume;
  35675. };
  35676. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  35677. this._playbackRate = newPlaybackRate;
  35678. if (this.isPlaying) {
  35679. if (this._streaming) {
  35680. this._htmlAudioElement.playbackRate = this._playbackRate;
  35681. }
  35682. else {
  35683. this._soundSource.playbackRate.value = this._playbackRate;
  35684. }
  35685. }
  35686. };
  35687. Sound.prototype.getVolume = function () {
  35688. return this._volume;
  35689. };
  35690. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  35691. var _this = this;
  35692. if (this._connectedMesh) {
  35693. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35694. this._registerFunc = null;
  35695. }
  35696. this._connectedMesh = meshToConnectTo;
  35697. if (!this.spatialSound) {
  35698. this.spatialSound = true;
  35699. this._createSpatialParameters();
  35700. if (this.isPlaying && this.loop) {
  35701. this.stop();
  35702. this.play();
  35703. }
  35704. }
  35705. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  35706. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  35707. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  35708. };
  35709. Sound.prototype.detachFromMesh = function () {
  35710. if (this._connectedMesh) {
  35711. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35712. this._registerFunc = null;
  35713. this._connectedMesh = null;
  35714. }
  35715. };
  35716. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  35717. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  35718. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  35719. this._updateDirection();
  35720. }
  35721. };
  35722. Sound.prototype.clone = function () {
  35723. var _this = this;
  35724. if (!this._streaming) {
  35725. var setBufferAndRun = function () {
  35726. if (_this._isReadyToPlay) {
  35727. clonedSound._audioBuffer = _this.getAudioBuffer();
  35728. clonedSound._isReadyToPlay = true;
  35729. if (clonedSound.autoplay) {
  35730. clonedSound.play();
  35731. }
  35732. }
  35733. else {
  35734. window.setTimeout(setBufferAndRun, 300);
  35735. }
  35736. };
  35737. var currentOptions = {
  35738. autoplay: this.autoplay, loop: this.loop,
  35739. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  35740. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  35741. refDistance: this.refDistance, distanceModel: this.distanceModel
  35742. };
  35743. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  35744. if (this.useCustomAttenuation) {
  35745. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  35746. }
  35747. clonedSound.setPosition(this._position);
  35748. clonedSound.setPlaybackRate(this._playbackRate);
  35749. setBufferAndRun();
  35750. return clonedSound;
  35751. }
  35752. else {
  35753. return null;
  35754. }
  35755. };
  35756. Sound.prototype.getAudioBuffer = function () {
  35757. return this._audioBuffer;
  35758. };
  35759. Sound.prototype.serialize = function () {
  35760. var serializationObject = {
  35761. name: this.name,
  35762. url: this.name,
  35763. autoplay: this.autoplay,
  35764. loop: this.loop,
  35765. volume: this._volume,
  35766. spatialSound: this.spatialSound,
  35767. maxDistance: this.maxDistance,
  35768. rolloffFactor: this.rolloffFactor,
  35769. refDistance: this.refDistance,
  35770. distanceModel: this.distanceModel,
  35771. playbackRate: this._playbackRate,
  35772. panningModel: this._panningModel,
  35773. soundTrackId: this.soundTrackId
  35774. };
  35775. if (this.spatialSound) {
  35776. if (this._connectedMesh)
  35777. serializationObject.connectedMeshId = this._connectedMesh.id;
  35778. serializationObject.position = this._position.asArray();
  35779. serializationObject.refDistance = this.refDistance;
  35780. serializationObject.distanceModel = this.distanceModel;
  35781. serializationObject.isDirectional = this._isDirectional;
  35782. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  35783. serializationObject.coneInnerAngle = this._coneInnerAngle;
  35784. serializationObject.coneOuterAngle = this._coneOuterAngle;
  35785. serializationObject.coneOuterGain = this._coneOuterGain;
  35786. }
  35787. return serializationObject;
  35788. };
  35789. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  35790. var soundName = parsedSound.name;
  35791. var soundUrl;
  35792. if (parsedSound.url) {
  35793. soundUrl = rootUrl + parsedSound.url;
  35794. }
  35795. else {
  35796. soundUrl = rootUrl + soundName;
  35797. }
  35798. var options = {
  35799. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  35800. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  35801. rolloffFactor: parsedSound.rolloffFactor,
  35802. refDistance: parsedSound.refDistance,
  35803. distanceModel: parsedSound.distanceModel,
  35804. playbackRate: parsedSound.playbackRate
  35805. };
  35806. var newSound;
  35807. if (!sourceSound) {
  35808. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  35809. scene._addPendingData(newSound);
  35810. }
  35811. else {
  35812. var setBufferAndRun = function () {
  35813. if (sourceSound._isReadyToPlay) {
  35814. newSound._audioBuffer = sourceSound.getAudioBuffer();
  35815. newSound._isReadyToPlay = true;
  35816. if (newSound.autoplay) {
  35817. newSound.play();
  35818. }
  35819. }
  35820. else {
  35821. window.setTimeout(setBufferAndRun, 300);
  35822. }
  35823. };
  35824. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  35825. setBufferAndRun();
  35826. }
  35827. if (parsedSound.position) {
  35828. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  35829. newSound.setPosition(soundPosition);
  35830. }
  35831. if (parsedSound.isDirectional) {
  35832. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  35833. if (parsedSound.localDirectionToMesh) {
  35834. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  35835. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  35836. }
  35837. }
  35838. if (parsedSound.connectedMeshId) {
  35839. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  35840. if (connectedMesh) {
  35841. newSound.attachToMesh(connectedMesh);
  35842. }
  35843. }
  35844. return newSound;
  35845. };
  35846. return Sound;
  35847. })();
  35848. BABYLON.Sound = Sound;
  35849. })(BABYLON || (BABYLON = {}));
  35850. var BABYLON;
  35851. (function (BABYLON) {
  35852. var SoundTrack = (function () {
  35853. function SoundTrack(scene, options) {
  35854. this.id = -1;
  35855. this._isMainTrack = false;
  35856. this._isInitialized = false;
  35857. this._scene = scene;
  35858. this.soundCollection = new Array();
  35859. this._options = options;
  35860. if (!this._isMainTrack) {
  35861. this._scene.soundTracks.push(this);
  35862. this.id = this._scene.soundTracks.length - 1;
  35863. }
  35864. }
  35865. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  35866. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35867. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  35868. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  35869. if (this._options) {
  35870. if (this._options.volume) {
  35871. this._outputAudioNode.gain.value = this._options.volume;
  35872. }
  35873. if (this._options.mainTrack) {
  35874. this._isMainTrack = this._options.mainTrack;
  35875. }
  35876. }
  35877. this._isInitialized = true;
  35878. }
  35879. };
  35880. SoundTrack.prototype.dispose = function () {
  35881. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35882. if (this._connectedAnalyser) {
  35883. this._connectedAnalyser.stopDebugCanvas();
  35884. }
  35885. while (this.soundCollection.length) {
  35886. this.soundCollection[0].dispose();
  35887. }
  35888. if (this._outputAudioNode) {
  35889. this._outputAudioNode.disconnect();
  35890. }
  35891. this._outputAudioNode = null;
  35892. }
  35893. };
  35894. SoundTrack.prototype.AddSound = function (sound) {
  35895. if (!this._isInitialized) {
  35896. this._initializeSoundTrackAudioGraph();
  35897. }
  35898. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35899. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  35900. }
  35901. if (sound.soundTrackId) {
  35902. if (sound.soundTrackId === -1) {
  35903. this._scene.mainSoundTrack.RemoveSound(sound);
  35904. }
  35905. else {
  35906. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  35907. }
  35908. }
  35909. this.soundCollection.push(sound);
  35910. sound.soundTrackId = this.id;
  35911. };
  35912. SoundTrack.prototype.RemoveSound = function (sound) {
  35913. var index = this.soundCollection.indexOf(sound);
  35914. if (index !== -1) {
  35915. this.soundCollection.splice(index, 1);
  35916. }
  35917. };
  35918. SoundTrack.prototype.setVolume = function (newVolume) {
  35919. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35920. this._outputAudioNode.gain.value = newVolume;
  35921. }
  35922. };
  35923. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  35924. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35925. for (var i = 0; i < this.soundCollection.length; i++) {
  35926. this.soundCollection[i].switchPanningModelToHRTF();
  35927. }
  35928. }
  35929. };
  35930. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  35931. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35932. for (var i = 0; i < this.soundCollection.length; i++) {
  35933. this.soundCollection[i].switchPanningModelToEqualPower();
  35934. }
  35935. }
  35936. };
  35937. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  35938. if (this._connectedAnalyser) {
  35939. this._connectedAnalyser.stopDebugCanvas();
  35940. }
  35941. this._connectedAnalyser = analyser;
  35942. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35943. this._outputAudioNode.disconnect();
  35944. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  35945. }
  35946. };
  35947. return SoundTrack;
  35948. })();
  35949. BABYLON.SoundTrack = SoundTrack;
  35950. })(BABYLON || (BABYLON = {}));
  35951. var BABYLON;
  35952. (function (BABYLON) {
  35953. var DebugLayer = (function () {
  35954. function DebugLayer(scene) {
  35955. var _this = this;
  35956. this._transformationMatrix = BABYLON.Matrix.Identity();
  35957. this._enabled = false;
  35958. this._labelsEnabled = false;
  35959. this._displayStatistics = true;
  35960. this._displayTree = false;
  35961. this._displayLogs = false;
  35962. this._skeletonViewers = new Array();
  35963. this._identityMatrix = BABYLON.Matrix.Identity();
  35964. this.axisRatio = 0.02;
  35965. this.accentColor = "orange";
  35966. this._scene = scene;
  35967. this._syncPositions = function () {
  35968. var engine = _this._scene.getEngine();
  35969. var canvasRect = engine.getRenderingCanvasClientRect();
  35970. if (_this._showUI) {
  35971. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  35972. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  35973. _this._statsDiv.style.width = "400px";
  35974. _this._statsDiv.style.height = "auto";
  35975. _this._statsSubsetDiv.style.maxHeight = "240px";
  35976. _this._optionsDiv.style.left = "0px";
  35977. _this._optionsDiv.style.top = "10px";
  35978. _this._optionsDiv.style.width = "200px";
  35979. _this._optionsDiv.style.height = "auto";
  35980. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  35981. _this._logDiv.style.left = "0px";
  35982. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  35983. _this._logDiv.style.width = "600px";
  35984. _this._logDiv.style.height = "160px";
  35985. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  35986. _this._treeDiv.style.top = "10px";
  35987. _this._treeDiv.style.width = "300px";
  35988. _this._treeDiv.style.height = "auto";
  35989. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  35990. }
  35991. _this._globalDiv.style.left = canvasRect.left + "px";
  35992. _this._globalDiv.style.top = canvasRect.top + "px";
  35993. _this._drawingCanvas.style.left = "0px";
  35994. _this._drawingCanvas.style.top = "0px";
  35995. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  35996. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  35997. var devicePixelRatio = window.devicePixelRatio || 1;
  35998. var context = _this._drawingContext;
  35999. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  36000. context.mozBackingStorePixelRatio ||
  36001. context.msBackingStorePixelRatio ||
  36002. context.oBackingStorePixelRatio ||
  36003. context.backingStorePixelRatio || 1;
  36004. _this._ratio = devicePixelRatio / backingStoreRatio;
  36005. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  36006. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  36007. };
  36008. this._onCanvasClick = function (evt) {
  36009. _this._clickPosition = {
  36010. x: evt.clientX * _this._ratio,
  36011. y: evt.clientY * _this._ratio
  36012. };
  36013. };
  36014. this._syncUI = function () {
  36015. if (_this._showUI) {
  36016. if (_this._displayStatistics) {
  36017. _this._displayStats();
  36018. _this._statsDiv.style.display = "";
  36019. }
  36020. else {
  36021. _this._statsDiv.style.display = "none";
  36022. }
  36023. if (_this._displayLogs) {
  36024. _this._logDiv.style.display = "";
  36025. }
  36026. else {
  36027. _this._logDiv.style.display = "none";
  36028. }
  36029. if (_this._displayTree) {
  36030. _this._treeDiv.style.display = "";
  36031. if (_this._needToRefreshMeshesTree) {
  36032. _this._needToRefreshMeshesTree = false;
  36033. _this._refreshMeshesTreeContent();
  36034. }
  36035. }
  36036. else {
  36037. _this._treeDiv.style.display = "none";
  36038. }
  36039. }
  36040. };
  36041. this._syncData = function () {
  36042. if (_this._labelsEnabled || !_this._showUI) {
  36043. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  36044. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  36045. var engine = _this._scene.getEngine();
  36046. var viewport = _this._camera.viewport;
  36047. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  36048. // Meshes
  36049. var meshes = _this._camera.getActiveMeshes();
  36050. var index;
  36051. var projectedPosition;
  36052. for (index = 0; index < meshes.length; index++) {
  36053. var mesh = meshes.data[index];
  36054. var position = mesh.getBoundingInfo().boundingSphere.center;
  36055. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  36056. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  36057. _this._renderAxis(projectedPosition, mesh, globalViewport);
  36058. }
  36059. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  36060. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  36061. }
  36062. }
  36063. // Cameras
  36064. var cameras = _this._scene.cameras;
  36065. for (index = 0; index < cameras.length; index++) {
  36066. var camera = cameras[index];
  36067. if (camera === _this._camera) {
  36068. continue;
  36069. }
  36070. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  36071. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  36072. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  36073. _this._camera.detachControl(engine.getRenderingCanvas());
  36074. _this._camera = camera;
  36075. _this._camera.attachControl(engine.getRenderingCanvas());
  36076. }, function () { return "purple"; });
  36077. }
  36078. }
  36079. // Lights
  36080. var lights = _this._scene.lights;
  36081. for (index = 0; index < lights.length; index++) {
  36082. var light = lights[index];
  36083. if (light.position) {
  36084. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  36085. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  36086. _this._renderLabel(light.name, projectedPosition, -20, function () {
  36087. light.setEnabled(!light.isEnabled());
  36088. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  36089. }
  36090. }
  36091. }
  36092. }
  36093. _this._clickPosition = undefined;
  36094. };
  36095. }
  36096. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  36097. while (this._treeSubsetDiv.hasChildNodes()) {
  36098. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  36099. }
  36100. // Add meshes
  36101. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  36102. sortedArray.sort(function (a, b) {
  36103. if (a.name === b.name) {
  36104. return 0;
  36105. }
  36106. return (a.name > b.name) ? 1 : -1;
  36107. });
  36108. for (var index = 0; index < sortedArray.length; index++) {
  36109. var mesh = sortedArray[index];
  36110. if (!mesh.isEnabled()) {
  36111. continue;
  36112. }
  36113. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  36114. m.isVisible = element.checked;
  36115. }, mesh);
  36116. }
  36117. };
  36118. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  36119. this._drawingContext.beginPath();
  36120. this._drawingContext.moveTo(zero.x, zero.y);
  36121. this._drawingContext.lineTo(unit.x, unit.y);
  36122. this._drawingContext.strokeStyle = color;
  36123. this._drawingContext.lineWidth = 4;
  36124. this._drawingContext.stroke();
  36125. this._drawingContext.font = "normal 14px Segoe UI";
  36126. this._drawingContext.fillStyle = color;
  36127. this._drawingContext.fillText(label, unitText.x, unitText.y);
  36128. };
  36129. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  36130. var position = mesh.getBoundingInfo().boundingSphere.center;
  36131. var worldMatrix = mesh.getWorldMatrix();
  36132. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  36133. var unit = (unprojectedVector.subtract(position)).length();
  36134. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36135. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36136. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  36137. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36138. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36139. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  36140. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  36141. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  36142. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  36143. };
  36144. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  36145. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  36146. this._drawingContext.font = "normal 12px Segoe UI";
  36147. var textMetrics = this._drawingContext.measureText(text);
  36148. var centerX = projectedPosition.x - textMetrics.width / 2;
  36149. var centerY = projectedPosition.y;
  36150. var clientRect = this._drawingCanvas.getBoundingClientRect();
  36151. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  36152. onClick();
  36153. }
  36154. this._drawingContext.beginPath();
  36155. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  36156. this._drawingContext.fillStyle = getFillStyle();
  36157. this._drawingContext.globalAlpha = 0.5;
  36158. this._drawingContext.fill();
  36159. this._drawingContext.globalAlpha = 1.0;
  36160. this._drawingContext.strokeStyle = '#FFFFFF';
  36161. this._drawingContext.lineWidth = 1;
  36162. this._drawingContext.stroke();
  36163. this._drawingContext.fillStyle = "#FFFFFF";
  36164. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  36165. this._drawingContext.beginPath();
  36166. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  36167. this._drawingContext.fill();
  36168. }
  36169. };
  36170. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  36171. if (!this._clickPosition) {
  36172. return false;
  36173. }
  36174. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  36175. return false;
  36176. }
  36177. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  36178. return false;
  36179. }
  36180. return true;
  36181. };
  36182. DebugLayer.prototype.isVisible = function () {
  36183. return this._enabled;
  36184. };
  36185. DebugLayer.prototype.hide = function () {
  36186. if (!this._enabled) {
  36187. return;
  36188. }
  36189. this._enabled = false;
  36190. var engine = this._scene.getEngine();
  36191. this._scene.unregisterBeforeRender(this._syncData);
  36192. this._scene.unregisterAfterRender(this._syncUI);
  36193. this._rootElement.removeChild(this._globalDiv);
  36194. this._scene.forceShowBoundingBoxes = false;
  36195. this._scene.forceWireframe = false;
  36196. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  36197. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  36198. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  36199. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  36200. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  36201. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  36202. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  36203. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  36204. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  36205. BABYLON.StandardMaterial.ColorGradingTextureEnabled = true;
  36206. this._scene.shadowsEnabled = true;
  36207. this._scene.particlesEnabled = true;
  36208. this._scene.postProcessesEnabled = true;
  36209. this._scene.collisionsEnabled = true;
  36210. this._scene.lightsEnabled = true;
  36211. this._scene.texturesEnabled = true;
  36212. this._scene.lensFlaresEnabled = true;
  36213. this._scene.proceduralTexturesEnabled = true;
  36214. this._scene.renderTargetsEnabled = true;
  36215. this._scene.probesEnabled = true;
  36216. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  36217. this._clearSkeletonViewers();
  36218. };
  36219. DebugLayer.prototype._clearSkeletonViewers = function () {
  36220. for (var index = 0; index < this._skeletonViewers.length; index++) {
  36221. this._skeletonViewers[index].dispose();
  36222. }
  36223. this._skeletonViewers = [];
  36224. };
  36225. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  36226. if (showUI === void 0) { showUI = true; }
  36227. if (camera === void 0) { camera = null; }
  36228. if (rootElement === void 0) { rootElement = null; }
  36229. if (this._enabled) {
  36230. return;
  36231. }
  36232. this._enabled = true;
  36233. if (camera) {
  36234. this._camera = camera;
  36235. }
  36236. else {
  36237. this._camera = this._scene.activeCamera;
  36238. }
  36239. this._showUI = showUI;
  36240. var engine = this._scene.getEngine();
  36241. this._globalDiv = document.createElement("div");
  36242. this._rootElement = rootElement || document.body;
  36243. this._rootElement.appendChild(this._globalDiv);
  36244. this._generateDOMelements();
  36245. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  36246. this._syncPositions();
  36247. this._scene.registerBeforeRender(this._syncData);
  36248. this._scene.registerAfterRender(this._syncUI);
  36249. };
  36250. DebugLayer.prototype._clearLabels = function () {
  36251. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  36252. for (var index = 0; index < this._scene.meshes.length; index++) {
  36253. var mesh = this._scene.meshes[index];
  36254. mesh.renderOverlay = false;
  36255. }
  36256. };
  36257. DebugLayer.prototype._generateheader = function (root, text) {
  36258. var header = document.createElement("div");
  36259. header.innerHTML = text + "&nbsp;";
  36260. header.style.textAlign = "right";
  36261. header.style.width = "100%";
  36262. header.style.color = "white";
  36263. header.style.backgroundColor = "Black";
  36264. header.style.padding = "5px 5px 4px 0px";
  36265. header.style.marginLeft = "-5px";
  36266. header.style.fontWeight = "bold";
  36267. root.appendChild(header);
  36268. };
  36269. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  36270. var label = document.createElement("label");
  36271. label.style.display = "inline";
  36272. label.innerHTML = title;
  36273. label.style.color = color;
  36274. root.appendChild(label);
  36275. root.appendChild(document.createElement("br"));
  36276. };
  36277. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  36278. if (tag === void 0) { tag = null; }
  36279. var label = document.createElement("label");
  36280. label.style.display = "inline";
  36281. var boundingBoxesCheckbox = document.createElement("input");
  36282. boundingBoxesCheckbox.type = "checkbox";
  36283. boundingBoxesCheckbox.checked = initialState;
  36284. boundingBoxesCheckbox.style.display = "inline";
  36285. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  36286. boundingBoxesCheckbox.style.verticalAlign = "sub";
  36287. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  36288. task(evt.target, tag);
  36289. });
  36290. label.appendChild(boundingBoxesCheckbox);
  36291. var container = document.createElement("span");
  36292. var leftPart = document.createElement("span");
  36293. var rightPart = document.createElement("span");
  36294. rightPart.style.cssFloat = "right";
  36295. leftPart.innerHTML = leftTitle;
  36296. rightPart.innerHTML = rightTitle;
  36297. rightPart.style.fontSize = "12px";
  36298. rightPart.style.maxWidth = "200px";
  36299. container.appendChild(leftPart);
  36300. container.appendChild(rightPart);
  36301. label.appendChild(container);
  36302. root.appendChild(label);
  36303. root.appendChild(document.createElement("br"));
  36304. };
  36305. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  36306. if (tag === void 0) { tag = null; }
  36307. var label = document.createElement("label");
  36308. label.style.display = "inline";
  36309. var checkBox = document.createElement("input");
  36310. checkBox.type = "checkbox";
  36311. checkBox.checked = initialState;
  36312. checkBox.style.display = "inline";
  36313. checkBox.style.margin = "0px 5px 0px 0px";
  36314. checkBox.style.verticalAlign = "sub";
  36315. checkBox.addEventListener("change", function (evt) {
  36316. task(evt.target, tag);
  36317. });
  36318. label.appendChild(checkBox);
  36319. label.appendChild(document.createTextNode(title));
  36320. root.appendChild(label);
  36321. root.appendChild(document.createElement("br"));
  36322. };
  36323. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  36324. if (tag === void 0) { tag = null; }
  36325. var button = document.createElement("button");
  36326. button.innerHTML = title;
  36327. button.style.height = "24px";
  36328. button.style.width = "150px";
  36329. button.style.marginBottom = "5px";
  36330. button.style.color = "#444444";
  36331. button.style.border = "1px solid white";
  36332. button.className = "debugLayerButton";
  36333. button.addEventListener("click", function (evt) {
  36334. task(evt.target, tag);
  36335. });
  36336. root.appendChild(button);
  36337. root.appendChild(document.createElement("br"));
  36338. };
  36339. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  36340. if (tag === void 0) { tag = null; }
  36341. var label = document.createElement("label");
  36342. label.style.display = "inline";
  36343. var boundingBoxesRadio = document.createElement("input");
  36344. boundingBoxesRadio.type = "radio";
  36345. boundingBoxesRadio.name = name;
  36346. boundingBoxesRadio.checked = initialState;
  36347. boundingBoxesRadio.style.display = "inline";
  36348. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  36349. boundingBoxesRadio.style.verticalAlign = "sub";
  36350. boundingBoxesRadio.addEventListener("change", function (evt) {
  36351. task(evt.target, tag);
  36352. });
  36353. label.appendChild(boundingBoxesRadio);
  36354. label.appendChild(document.createTextNode(title));
  36355. root.appendChild(label);
  36356. root.appendChild(document.createElement("br"));
  36357. };
  36358. DebugLayer.prototype._generateDOMelements = function () {
  36359. var _this = this;
  36360. this._globalDiv.id = "DebugLayer";
  36361. this._globalDiv.style.position = "absolute";
  36362. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  36363. this._globalDiv.style.fontSize = "14px";
  36364. this._globalDiv.style.color = "white";
  36365. // Drawing canvas
  36366. this._drawingCanvas = document.createElement("canvas");
  36367. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  36368. this._drawingCanvas.style.position = "absolute";
  36369. this._drawingCanvas.style.pointerEvents = "none";
  36370. this._drawingCanvas.style.backgroundColor = "transparent";
  36371. this._drawingContext = this._drawingCanvas.getContext("2d");
  36372. this._globalDiv.appendChild(this._drawingCanvas);
  36373. if (this._showUI) {
  36374. var background = "rgba(128, 128, 128, 0.4)";
  36375. var border = "rgb(180, 180, 180) solid 1px";
  36376. // Stats
  36377. this._statsDiv = document.createElement("div");
  36378. this._statsDiv.id = "DebugLayerStats";
  36379. this._statsDiv.style.border = border;
  36380. this._statsDiv.style.position = "absolute";
  36381. this._statsDiv.style.background = background;
  36382. this._statsDiv.style.padding = "0px 0px 0px 5px";
  36383. this._generateheader(this._statsDiv, "STATISTICS");
  36384. this._statsSubsetDiv = document.createElement("div");
  36385. this._statsSubsetDiv.style.paddingTop = "5px";
  36386. this._statsSubsetDiv.style.paddingBottom = "5px";
  36387. this._statsSubsetDiv.style.overflowY = "auto";
  36388. this._statsDiv.appendChild(this._statsSubsetDiv);
  36389. // Tree
  36390. this._treeDiv = document.createElement("div");
  36391. this._treeDiv.id = "DebugLayerTree";
  36392. this._treeDiv.style.border = border;
  36393. this._treeDiv.style.position = "absolute";
  36394. this._treeDiv.style.background = background;
  36395. this._treeDiv.style.padding = "0px 0px 0px 5px";
  36396. this._treeDiv.style.display = "none";
  36397. this._generateheader(this._treeDiv, "MESHES TREE");
  36398. this._treeSubsetDiv = document.createElement("div");
  36399. this._treeSubsetDiv.style.paddingTop = "5px";
  36400. this._treeSubsetDiv.style.paddingRight = "5px";
  36401. this._treeSubsetDiv.style.overflowY = "auto";
  36402. this._treeSubsetDiv.style.maxHeight = "300px";
  36403. this._treeDiv.appendChild(this._treeSubsetDiv);
  36404. this._needToRefreshMeshesTree = true;
  36405. // Logs
  36406. this._logDiv = document.createElement("div");
  36407. this._logDiv.style.border = border;
  36408. this._logDiv.id = "DebugLayerLogs";
  36409. this._logDiv.style.position = "absolute";
  36410. this._logDiv.style.background = background;
  36411. this._logDiv.style.padding = "0px 0px 0px 5px";
  36412. this._logDiv.style.display = "none";
  36413. this._generateheader(this._logDiv, "LOGS");
  36414. this._logSubsetDiv = document.createElement("div");
  36415. this._logSubsetDiv.style.height = "127px";
  36416. this._logSubsetDiv.style.paddingTop = "5px";
  36417. this._logSubsetDiv.style.overflowY = "auto";
  36418. this._logSubsetDiv.style.fontSize = "12px";
  36419. this._logSubsetDiv.style.fontFamily = "consolas";
  36420. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  36421. this._logDiv.appendChild(this._logSubsetDiv);
  36422. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  36423. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  36424. };
  36425. // Options
  36426. this._optionsDiv = document.createElement("div");
  36427. this._optionsDiv.id = "DebugLayerOptions";
  36428. this._optionsDiv.style.border = border;
  36429. this._optionsDiv.style.position = "absolute";
  36430. this._optionsDiv.style.background = background;
  36431. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  36432. this._optionsDiv.style.overflowY = "auto";
  36433. this._generateheader(this._optionsDiv, "OPTIONS");
  36434. this._optionsSubsetDiv = document.createElement("div");
  36435. this._optionsSubsetDiv.style.paddingTop = "5px";
  36436. this._optionsSubsetDiv.style.paddingBottom = "5px";
  36437. this._optionsSubsetDiv.style.overflowY = "auto";
  36438. this._optionsSubsetDiv.style.maxHeight = "200px";
  36439. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  36440. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  36441. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  36442. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  36443. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  36444. _this._displayTree = element.checked;
  36445. _this._needToRefreshMeshesTree = true;
  36446. });
  36447. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36448. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  36449. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  36450. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  36451. _this._labelsEnabled = element.checked;
  36452. if (!_this._labelsEnabled) {
  36453. _this._clearLabels();
  36454. }
  36455. });
  36456. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  36457. if (element.checked) {
  36458. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  36459. }
  36460. else {
  36461. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  36462. }
  36463. });
  36464. ;
  36465. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36466. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  36467. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  36468. if (element.checked) {
  36469. _this._scene.forceWireframe = false;
  36470. _this._scene.forcePointsCloud = false;
  36471. }
  36472. });
  36473. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  36474. if (element.checked) {
  36475. _this._scene.forceWireframe = true;
  36476. _this._scene.forcePointsCloud = false;
  36477. }
  36478. });
  36479. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  36480. if (element.checked) {
  36481. _this._scene.forceWireframe = false;
  36482. _this._scene.forcePointsCloud = true;
  36483. }
  36484. });
  36485. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36486. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  36487. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  36488. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  36489. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  36490. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  36491. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  36492. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  36493. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  36494. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  36495. this._generateCheckBox(this._optionsSubsetDiv, "ColorGrading", BABYLON.StandardMaterial.ColorGradingTextureEnabled, function (element) { BABYLON.StandardMaterial.ColorGradingTextureEnabled = element.checked; });
  36496. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  36497. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  36498. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36499. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  36500. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  36501. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  36502. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  36503. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  36504. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  36505. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  36506. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  36507. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  36508. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  36509. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  36510. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  36511. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  36512. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  36513. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  36514. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  36515. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36516. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  36517. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  36518. if (element.checked) {
  36519. _this._scene.headphone = true;
  36520. }
  36521. });
  36522. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  36523. if (element.checked) {
  36524. _this._scene.headphone = false;
  36525. }
  36526. });
  36527. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  36528. _this._scene.audioEnabled = !element.checked;
  36529. });
  36530. }
  36531. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36532. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  36533. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  36534. if (!element.checked) {
  36535. _this._clearSkeletonViewers();
  36536. return;
  36537. }
  36538. for (var index = 0; index < _this._scene.meshes.length; index++) {
  36539. var mesh = _this._scene.meshes[index];
  36540. if (mesh.skeleton) {
  36541. var found = false;
  36542. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  36543. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  36544. found = true;
  36545. break;
  36546. }
  36547. }
  36548. if (found) {
  36549. continue;
  36550. }
  36551. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  36552. viewer.isEnabled = true;
  36553. _this._skeletonViewers.push(viewer);
  36554. }
  36555. }
  36556. });
  36557. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36558. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  36559. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  36560. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  36561. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  36562. if (_this._camera) {
  36563. console.log(_this._camera);
  36564. }
  36565. else {
  36566. console.warn("No camera defined, or debug layer created before camera creation!");
  36567. }
  36568. });
  36569. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36570. this._globalDiv.appendChild(this._statsDiv);
  36571. this._globalDiv.appendChild(this._logDiv);
  36572. this._globalDiv.appendChild(this._optionsDiv);
  36573. this._globalDiv.appendChild(this._treeDiv);
  36574. }
  36575. };
  36576. DebugLayer.prototype._displayStats = function () {
  36577. var scene = this._scene;
  36578. var engine = scene.getEngine();
  36579. var glInfo = engine.getGlInfo();
  36580. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  36581. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  36582. + "<b>Count</b><br>"
  36583. + "Total meshes: " + scene.meshes.length + "<br>"
  36584. + "Total lights: " + scene.lights.length + "<br>"
  36585. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  36586. + "Total materials: " + scene.materials.length + "<br>"
  36587. + "Total textures: " + scene.textures.length + "<br>"
  36588. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  36589. + "Active indices: " + scene.getActiveIndices() + "<br>"
  36590. + "Active bones: " + scene.getActiveBones() + "<br>"
  36591. + "Active particles: " + scene.getActiveParticles() + "<br>"
  36592. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  36593. + "<b>Duration</b><br>"
  36594. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  36595. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  36596. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  36597. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  36598. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  36599. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  36600. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  36601. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  36602. + "</div>"
  36603. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  36604. + "<b>Extensions</b><br>"
  36605. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  36606. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  36607. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  36608. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  36609. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  36610. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  36611. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  36612. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  36613. + "</div><br>"
  36614. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  36615. + "<b>Caps.</b><br>"
  36616. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  36617. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  36618. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  36619. + "<b>Info</b><br>"
  36620. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  36621. + glInfo.version + "<br>"
  36622. + "</div><br>"
  36623. + glInfo.renderer + "<br>";
  36624. if (this.customStatsFunction) {
  36625. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  36626. }
  36627. };
  36628. return DebugLayer;
  36629. })();
  36630. BABYLON.DebugLayer = DebugLayer;
  36631. })(BABYLON || (BABYLON = {}));
  36632. var BABYLON;
  36633. (function (BABYLON) {
  36634. var SIMDVector3 = (function () {
  36635. function SIMDVector3() {
  36636. }
  36637. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  36638. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  36639. var m0 = SIMD.float32x4.load(transformation.m, 0);
  36640. var m1 = SIMD.float32x4.load(transformation.m, 4);
  36641. var m2 = SIMD.float32x4.load(transformation.m, 8);
  36642. var m3 = SIMD.float32x4.load(transformation.m, 12);
  36643. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  36644. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  36645. SIMD.float32x4.storeXYZ(result._data, 0, r);
  36646. };
  36647. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  36648. var v0 = SIMD.float32x4.splat(x);
  36649. var v1 = SIMD.float32x4.splat(y);
  36650. var v2 = SIMD.float32x4.splat(z);
  36651. var m0 = SIMD.float32x4.load(transformation.m, 0);
  36652. var m1 = SIMD.float32x4.load(transformation.m, 4);
  36653. var m2 = SIMD.float32x4.load(transformation.m, 8);
  36654. var m3 = SIMD.float32x4.load(transformation.m, 12);
  36655. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  36656. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  36657. SIMD.float32x4.storeXYZ(result._data, 0, r);
  36658. };
  36659. return SIMDVector3;
  36660. })();
  36661. BABYLON.SIMDVector3 = SIMDVector3;
  36662. var SIMDMatrix = (function () {
  36663. function SIMDMatrix() {
  36664. }
  36665. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  36666. if (offset === void 0) { offset = 0; }
  36667. var tm = this.m;
  36668. var om = other.m;
  36669. var om0 = SIMD.float32x4.load(om, 0);
  36670. var om1 = SIMD.float32x4.load(om, 4);
  36671. var om2 = SIMD.float32x4.load(om, 8);
  36672. var om3 = SIMD.float32x4.load(om, 12);
  36673. var tm0 = SIMD.float32x4.load(tm, 0);
  36674. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  36675. var tm1 = SIMD.float32x4.load(tm, 4);
  36676. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  36677. var tm2 = SIMD.float32x4.load(tm, 8);
  36678. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  36679. var tm3 = SIMD.float32x4.load(tm, 12);
  36680. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  36681. };
  36682. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  36683. var src = this.m;
  36684. var dest = other.m;
  36685. var row0, row1, row2, row3;
  36686. var tmp1;
  36687. var minor0, minor1, minor2, minor3;
  36688. var det;
  36689. // Load the 4 rows
  36690. var src0 = SIMD.float32x4.load(src, 0);
  36691. var src1 = SIMD.float32x4.load(src, 4);
  36692. var src2 = SIMD.float32x4.load(src, 8);
  36693. var src3 = SIMD.float32x4.load(src, 12);
  36694. // Transpose the source matrix. Sort of. Not a true transpose operation
  36695. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  36696. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  36697. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  36698. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  36699. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  36700. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  36701. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  36702. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  36703. // This is a true transposition, but it will lead to an incorrect result
  36704. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  36705. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  36706. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  36707. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  36708. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  36709. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  36710. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  36711. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  36712. // ----
  36713. tmp1 = SIMD.float32x4.mul(row2, row3);
  36714. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36715. minor0 = SIMD.float32x4.mul(row1, tmp1);
  36716. minor1 = SIMD.float32x4.mul(row0, tmp1);
  36717. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36718. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  36719. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  36720. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  36721. // ----
  36722. tmp1 = SIMD.float32x4.mul(row1, row2);
  36723. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36724. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  36725. minor3 = SIMD.float32x4.mul(row0, tmp1);
  36726. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36727. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  36728. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  36729. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  36730. // ----
  36731. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  36732. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36733. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  36734. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  36735. minor2 = SIMD.float32x4.mul(row0, tmp1);
  36736. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36737. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  36738. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  36739. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  36740. // ----
  36741. tmp1 = SIMD.float32x4.mul(row0, row1);
  36742. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36743. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  36744. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  36745. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36746. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  36747. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  36748. // ----
  36749. tmp1 = SIMD.float32x4.mul(row0, row3);
  36750. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36751. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  36752. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  36753. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36754. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  36755. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  36756. // ----
  36757. tmp1 = SIMD.float32x4.mul(row0, row2);
  36758. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36759. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  36760. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  36761. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36762. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  36763. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  36764. // Compute determinant
  36765. det = SIMD.float32x4.mul(row0, minor0);
  36766. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  36767. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  36768. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  36769. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  36770. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  36771. // These shuffles aren't necessary if the faulty transposition is done
  36772. // up at the top of this function.
  36773. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  36774. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  36775. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  36776. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  36777. // Compute final values by multiplying with 1/det
  36778. minor0 = SIMD.float32x4.mul(det, minor0);
  36779. minor1 = SIMD.float32x4.mul(det, minor1);
  36780. minor2 = SIMD.float32x4.mul(det, minor2);
  36781. minor3 = SIMD.float32x4.mul(det, minor3);
  36782. SIMD.float32x4.store(dest, 0, minor0);
  36783. SIMD.float32x4.store(dest, 4, minor1);
  36784. SIMD.float32x4.store(dest, 8, minor2);
  36785. SIMD.float32x4.store(dest, 12, minor3);
  36786. return this;
  36787. };
  36788. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  36789. var out = result.m;
  36790. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  36791. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  36792. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  36793. // cc.kmVec3Subtract(f, pCenter, pEye);
  36794. var f = SIMD.float32x4.sub(center, eye);
  36795. // cc.kmVec3Normalize(f, f);
  36796. var tmp = SIMD.float32x4.mul(f, f);
  36797. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  36798. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  36799. // cc.kmVec3Assign(up, pUp);
  36800. // cc.kmVec3Normalize(up, up);
  36801. tmp = SIMD.float32x4.mul(up, up);
  36802. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  36803. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  36804. // cc.kmVec3Cross(s, f, up);
  36805. 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)));
  36806. // cc.kmVec3Normalize(s, s);
  36807. tmp = SIMD.float32x4.mul(s, s);
  36808. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  36809. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  36810. // cc.kmVec3Cross(u, s, f);
  36811. 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)));
  36812. // cc.kmVec3Normalize(s, s);
  36813. tmp = SIMD.float32x4.mul(s, s);
  36814. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  36815. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  36816. var zero = SIMD.float32x4.splat(0.0);
  36817. s = SIMD.float32x4.neg(s);
  36818. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  36819. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  36820. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  36821. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  36822. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  36823. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  36824. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  36825. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  36826. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  36827. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  36828. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  36829. var b3 = SIMD.float32x4.neg(eye);
  36830. b3 = SIMD.float32x4.withW(b3, 1.0);
  36831. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  36832. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  36833. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  36834. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  36835. };
  36836. return SIMDMatrix;
  36837. })();
  36838. BABYLON.SIMDMatrix = SIMDMatrix;
  36839. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  36840. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  36841. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  36842. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  36843. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  36844. var SIMDHelper = (function () {
  36845. function SIMDHelper() {
  36846. }
  36847. Object.defineProperty(SIMDHelper, "IsEnabled", {
  36848. get: function () {
  36849. return SIMDHelper._isEnabled;
  36850. },
  36851. enumerable: true,
  36852. configurable: true
  36853. });
  36854. SIMDHelper.DisableSIMD = function () {
  36855. // Replace functions
  36856. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  36857. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  36858. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  36859. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  36860. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  36861. SIMDHelper._isEnabled = false;
  36862. };
  36863. SIMDHelper.EnableSIMD = function () {
  36864. if (window.SIMD === undefined) {
  36865. return;
  36866. }
  36867. // Replace functions
  36868. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  36869. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  36870. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  36871. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  36872. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  36873. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  36874. get: function () { return this._data[0]; },
  36875. set: function (value) {
  36876. if (!this._data) {
  36877. this._data = new Float32Array(3);
  36878. }
  36879. this._data[0] = value;
  36880. }
  36881. });
  36882. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  36883. get: function () { return this._data[1]; },
  36884. set: function (value) {
  36885. this._data[1] = value;
  36886. }
  36887. });
  36888. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  36889. get: function () { return this._data[2]; },
  36890. set: function (value) {
  36891. this._data[2] = value;
  36892. }
  36893. });
  36894. SIMDHelper._isEnabled = true;
  36895. };
  36896. SIMDHelper._isEnabled = false;
  36897. return SIMDHelper;
  36898. })();
  36899. BABYLON.SIMDHelper = SIMDHelper;
  36900. })(BABYLON || (BABYLON = {}));
  36901. var BABYLON;
  36902. (function (BABYLON) {
  36903. /**
  36904. * This class describe a rectangle that were added to the map.
  36905. * You have access to its coordinates either in pixel or normalized (UV)
  36906. */
  36907. var PackedRect = (function () {
  36908. function PackedRect(root, parent, pos, size) {
  36909. this._pos = pos;
  36910. this._size = size;
  36911. this._root = root;
  36912. this._parent = parent;
  36913. }
  36914. Object.defineProperty(PackedRect.prototype, "pos", {
  36915. /**
  36916. * @returns the position of this node into the map
  36917. */
  36918. get: function () {
  36919. return this._pos;
  36920. },
  36921. enumerable: true,
  36922. configurable: true
  36923. });
  36924. Object.defineProperty(PackedRect.prototype, "contentSize", {
  36925. /**
  36926. * @returns the size of the rectangle this node handles
  36927. */
  36928. get: function () {
  36929. return this._contentSize;
  36930. },
  36931. enumerable: true,
  36932. configurable: true
  36933. });
  36934. Object.defineProperty(PackedRect.prototype, "UVs", {
  36935. /**
  36936. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  36937. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  36938. */
  36939. get: function () {
  36940. return this.getUVsForCustomSize(this._root._size);
  36941. },
  36942. enumerable: true,
  36943. configurable: true
  36944. });
  36945. /**
  36946. * 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.
  36947. * This method will return the UVs for this part by given the custom size of what you really use
  36948. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  36949. */
  36950. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  36951. var mainWidth = this._root._size.width;
  36952. var mainHeight = this._root._size.height;
  36953. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  36954. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  36955. var uvs = new Array();
  36956. uvs.push(topLeft);
  36957. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  36958. uvs.push(rightBottom);
  36959. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  36960. return uvs;
  36961. };
  36962. /**
  36963. * Free this rectangle from the map.
  36964. * Call this method when you no longer need the rectangle to be in the map.
  36965. */
  36966. PackedRect.prototype.freeContent = function () {
  36967. if (!this.contentSize) {
  36968. return;
  36969. }
  36970. this._contentSize = null;
  36971. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  36972. this.attemptDefrag();
  36973. };
  36974. Object.defineProperty(PackedRect.prototype, "isUsed", {
  36975. get: function () {
  36976. return this._contentSize != null || this._leftNode != null;
  36977. },
  36978. enumerable: true,
  36979. configurable: true
  36980. });
  36981. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  36982. var node = this.findNode(contentSize);
  36983. // Not enough space...
  36984. if (!node) {
  36985. return null;
  36986. }
  36987. node.splitNode(contentSize);
  36988. return node;
  36989. };
  36990. PackedRect.prototype.findNode = function (size) {
  36991. var resNode = null;
  36992. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  36993. if (this.isUsed) {
  36994. if (this._leftNode) {
  36995. resNode = this._leftNode.findNode(size);
  36996. }
  36997. if (!resNode && this._rightNode) {
  36998. resNode = this._rightNode.findNode(size);
  36999. }
  37000. if (!resNode && this._bottomNode) {
  37001. resNode = this._bottomNode.findNode(size);
  37002. }
  37003. }
  37004. else if (this._initialSize && (size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  37005. resNode = this;
  37006. }
  37007. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  37008. resNode = this;
  37009. }
  37010. return resNode;
  37011. };
  37012. PackedRect.prototype.splitNode = function (contentSize) {
  37013. // 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)
  37014. if (!this._contentSize && this._initialSize) {
  37015. 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));
  37016. return this._leftNode.splitNode(contentSize);
  37017. }
  37018. else {
  37019. this._contentSize = contentSize.clone();
  37020. this._initialSize = contentSize.clone();
  37021. if (contentSize.width !== this._size.width) {
  37022. 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));
  37023. }
  37024. if (contentSize.height !== this._size.height) {
  37025. 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));
  37026. }
  37027. return this;
  37028. }
  37029. };
  37030. PackedRect.prototype.attemptDefrag = function () {
  37031. if (!this.isUsed && this.isRecursiveFree) {
  37032. this.clearNode();
  37033. if (this._parent) {
  37034. this._parent.attemptDefrag();
  37035. }
  37036. }
  37037. };
  37038. PackedRect.prototype.clearNode = function () {
  37039. this._initialSize = null;
  37040. this._rightNode = null;
  37041. this._bottomNode = null;
  37042. };
  37043. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  37044. get: function () {
  37045. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  37046. },
  37047. enumerable: true,
  37048. configurable: true
  37049. });
  37050. PackedRect.prototype.evalFreeSize = function (size) {
  37051. var levelSize = 0;
  37052. if (!this.isUsed) {
  37053. if (this._initialSize) {
  37054. levelSize = this._initialSize.surface;
  37055. }
  37056. else {
  37057. levelSize = this._size.surface;
  37058. }
  37059. }
  37060. if (this._rightNode) {
  37061. levelSize += this._rightNode.evalFreeSize(0);
  37062. }
  37063. if (this._bottomNode) {
  37064. levelSize += this._bottomNode.evalFreeSize(0);
  37065. }
  37066. return levelSize + size;
  37067. };
  37068. return PackedRect;
  37069. })();
  37070. BABYLON.PackedRect = PackedRect;
  37071. /**
  37072. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  37073. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  37074. * 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.
  37075. */
  37076. var RectPackingMap = (function (_super) {
  37077. __extends(RectPackingMap, _super);
  37078. /**
  37079. * Create an instance of the object with a dimension using the given size
  37080. * @param size The dimension of the rectangle that will contain all the sub ones.
  37081. */
  37082. function RectPackingMap(size) {
  37083. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  37084. this._root = this;
  37085. }
  37086. /**
  37087. * Add a rectangle, finding the best location to store it into the map
  37088. * @param size the dimension of the rectangle to store
  37089. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  37090. */
  37091. RectPackingMap.prototype.addRect = function (size) {
  37092. var node = this.findAndSplitNode(size);
  37093. return node;
  37094. };
  37095. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  37096. /**
  37097. * Return the current space free normalized between [0;1]
  37098. * @returns {}
  37099. */
  37100. get: function () {
  37101. var freeSize = 0;
  37102. freeSize = this.evalFreeSize(freeSize);
  37103. return freeSize / (this._size.width * this._size.height);
  37104. },
  37105. enumerable: true,
  37106. configurable: true
  37107. });
  37108. return RectPackingMap;
  37109. })(PackedRect);
  37110. BABYLON.RectPackingMap = RectPackingMap;
  37111. })(BABYLON || (BABYLON = {}));
  37112. var BABYLON;
  37113. (function (BABYLON) {
  37114. var DynamicFloatArrayElementInfo = (function () {
  37115. function DynamicFloatArrayElementInfo() {
  37116. }
  37117. return DynamicFloatArrayElementInfo;
  37118. })();
  37119. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  37120. /**
  37121. * 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.
  37122. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  37123. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  37124. * 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.
  37125. * 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.
  37126. * 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".
  37127. */
  37128. var DynamicFloatArray = (function () {
  37129. /**
  37130. * Construct an instance of the dynamic float array
  37131. * @param stride size of one element in float (i.e. not bytes!)
  37132. * @param initialElementCount the number of available entries at construction
  37133. */
  37134. function DynamicFloatArray(stride, initialElementCount) {
  37135. this.compareValueOffset = null;
  37136. this.sortingAscending = true;
  37137. this._stride = stride;
  37138. this.buffer = new Float32Array(stride * initialElementCount);
  37139. this._lastUsed = 0;
  37140. this._firstFree = 0;
  37141. this._allEntries = new Array(initialElementCount);
  37142. this._freeEntries = new Array(initialElementCount);
  37143. for (var i = 0; i < initialElementCount; i++) {
  37144. var element = new DynamicFloatArrayElementInfo();
  37145. element.offset = i * stride;
  37146. this._allEntries[i] = element;
  37147. this._freeEntries[initialElementCount - i - 1] = element;
  37148. }
  37149. }
  37150. /**
  37151. * Allocate an element in the array.
  37152. * @return the element info instance that contains the offset into the main buffer of the element's location.
  37153. * Beware, this offset may change when you call pack()
  37154. */
  37155. DynamicFloatArray.prototype.allocElement = function () {
  37156. if (this._freeEntries.length === 0) {
  37157. this._growBuffer();
  37158. }
  37159. var el = this._freeEntries.pop();
  37160. this._lastUsed = Math.max(el.offset, this._lastUsed);
  37161. if (el.offset === this._firstFree) {
  37162. if (this._freeEntries.length > 0) {
  37163. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  37164. }
  37165. else {
  37166. this._firstFree += this._stride;
  37167. }
  37168. }
  37169. return el;
  37170. };
  37171. /**
  37172. * Free the element corresponding to the given element info
  37173. * @param elInfo the element that describe the allocated element
  37174. */
  37175. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  37176. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  37177. this._freeEntries.push(elInfo);
  37178. };
  37179. /**
  37180. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  37181. * 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().
  37182. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  37183. */
  37184. DynamicFloatArray.prototype.pack = function () {
  37185. // no free slot? no need to pack
  37186. if (this._freeEntries.length === 0) {
  37187. return this.buffer;
  37188. }
  37189. // If the buffer is already packed the last used will always be lower than the first free
  37190. // 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.
  37191. if (this._lastUsed < this._firstFree) {
  37192. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  37193. return elementsBuffer_1;
  37194. }
  37195. var s = this._stride;
  37196. // 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
  37197. var lastFree = new DynamicFloatArrayElementInfo();
  37198. lastFree.offset = this.totalElementCount * s;
  37199. this._freeEntries.push(lastFree);
  37200. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  37201. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  37202. var firstFreeSlotOffset = sortedFree[0].offset;
  37203. var freeZoneSize = 1;
  37204. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  37205. var prevOffset = sortedFree[0].offset;
  37206. for (var i = 1; i < sortedFree.length; i++) {
  37207. // 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
  37208. if (firstFreeSlotOffset >= occupiedZoneSize) {
  37209. break;
  37210. }
  37211. var curFree = sortedFree[i];
  37212. var curOffset = curFree.offset;
  37213. // Compute the distance between this offset and the previous
  37214. var distance = curOffset - prevOffset;
  37215. // If the distance is the stride size, they are adjacent, it good, move to the next
  37216. if (distance === s) {
  37217. // Free zone is one element bigger
  37218. ++freeZoneSize;
  37219. // as we're about to iterate to the next, the cur becomes the previous...
  37220. prevOffset = curOffset;
  37221. continue;
  37222. }
  37223. // Distance is bigger, which means there's x element between the previous free and this one
  37224. var usedRange = (distance / s) - 1;
  37225. // Two cases the free zone is smaller than the data to move or bigger
  37226. // Copy what can fit in the free zone
  37227. var curMoveOffset = curOffset - s;
  37228. var copyCount = Math.min(freeZoneSize, usedRange);
  37229. for (var j = 0; j < copyCount; j++) {
  37230. var freeI = firstFreeSlotOffset / s;
  37231. var curI = curMoveOffset / s;
  37232. var moveEl = sortedAll[curI];
  37233. this._moveElement(moveEl, firstFreeSlotOffset);
  37234. var replacedEl = sortedAll[freeI];
  37235. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  37236. replacedEl.offset = curMoveOffset;
  37237. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  37238. sortedAll[freeI] = moveEl;
  37239. sortedAll[curI] = replacedEl;
  37240. curMoveOffset -= s;
  37241. firstFreeSlotOffset += s;
  37242. }
  37243. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  37244. if (freeZoneSize <= usedRange) {
  37245. firstFreeSlotOffset = curMoveOffset + s;
  37246. freeZoneSize = 1 + copyCount;
  37247. }
  37248. else {
  37249. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  37250. }
  37251. // as we're about to iterate to the next, the cur becomes the previous...
  37252. prevOffset = curOffset;
  37253. }
  37254. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  37255. this._lastUsed = firstFreeSlotOffset - s;
  37256. this._firstFree = firstFreeSlotOffset;
  37257. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  37258. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  37259. this._allEntries = sortedAll;
  37260. return elementsBuffer;
  37261. };
  37262. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  37263. for (var i = 0; i < this._stride; i++) {
  37264. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  37265. }
  37266. element.offset = destOffset;
  37267. };
  37268. DynamicFloatArray.prototype._growBuffer = function () {
  37269. // Allocate the new buffer with 50% more entries, copy the content of the current one
  37270. var newElCount = Math.floor(this.totalElementCount * 1.5);
  37271. var newBuffer = new Float32Array(newElCount * this._stride);
  37272. newBuffer.set(this.buffer);
  37273. var curCount = this.totalElementCount;
  37274. var addedCount = newElCount - this.totalElementCount;
  37275. for (var i = 0; i < addedCount; i++) {
  37276. var element = new DynamicFloatArrayElementInfo();
  37277. element.offset = (curCount + i) * this.stride;
  37278. this._allEntries.push(element);
  37279. this._freeEntries[addedCount - i - 1] = element;
  37280. }
  37281. this._firstFree = curCount * this.stride;
  37282. this.buffer = newBuffer;
  37283. };
  37284. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  37285. /**
  37286. * Get the total count of entries that can fit in the current buffer
  37287. * @returns the elements count
  37288. */
  37289. get: function () {
  37290. return this._allEntries.length;
  37291. },
  37292. enumerable: true,
  37293. configurable: true
  37294. });
  37295. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  37296. /**
  37297. * Get the count of free entries that can still be allocated without resizing the buffer
  37298. * @returns the free elements count
  37299. */
  37300. get: function () {
  37301. return this._freeEntries.length;
  37302. },
  37303. enumerable: true,
  37304. configurable: true
  37305. });
  37306. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  37307. /**
  37308. * Get the count of allocated elements
  37309. * @returns the allocated elements count
  37310. */
  37311. get: function () {
  37312. return this._allEntries.length - this._freeEntries.length;
  37313. },
  37314. enumerable: true,
  37315. configurable: true
  37316. });
  37317. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  37318. /**
  37319. * Return the size of one element in float
  37320. * @returns the size in float
  37321. */
  37322. get: function () {
  37323. return this._stride;
  37324. },
  37325. enumerable: true,
  37326. configurable: true
  37327. });
  37328. DynamicFloatArray.prototype.sort = function () {
  37329. var _this = this;
  37330. if (!this.compareValueOffset) {
  37331. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  37332. }
  37333. var count = this.usedElementCount;
  37334. // Do we have to (re)create the sort table?
  37335. if (!this._sortTable || this._sortTable.length < count) {
  37336. // 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...
  37337. var newCount = Math.min(this.totalElementCount, count * 2);
  37338. this._sortTable = new Array(newCount);
  37339. }
  37340. if (!this._sortedTable || this._sortedTable.length !== count) {
  37341. this._sortedTable = new Array(count);
  37342. }
  37343. // Because, you know...
  37344. this.pack();
  37345. //let stride = this.stride;
  37346. //for (let i = 0; i < count; i++) {
  37347. // let si = this._sortTable[i];
  37348. // if (!si) {
  37349. // si = new SortInfo();
  37350. // this._sortTable[i] = si;
  37351. // }
  37352. // si.entry = this._allEntries[i];
  37353. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  37354. // si.swapedOffset = null;
  37355. // this._sortedTable[i] = si;
  37356. //}
  37357. var curOffset = 0;
  37358. var stride = this.stride;
  37359. for (var i = 0; i < count; i++, curOffset += stride) {
  37360. var si = this._sortTable[i];
  37361. if (!si) {
  37362. si = new SortInfo();
  37363. this._sortTable[i] = si;
  37364. }
  37365. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  37366. si.offset = curOffset;
  37367. si.swapedOffset = null;
  37368. this._sortedTable[i] = si;
  37369. }
  37370. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  37371. if (this.sortingAscending) {
  37372. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  37373. }
  37374. else {
  37375. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  37376. }
  37377. var swapElements = function (src, dst) {
  37378. for (var i = 0; i < stride; i++) {
  37379. var tps = _this.buffer[dst + i];
  37380. _this.buffer[dst + i] = _this.buffer[src + i];
  37381. _this.buffer[src + i] = tps;
  37382. }
  37383. };
  37384. // 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:
  37385. // 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),
  37386. // and I still want something with a good algorithm complexity.
  37387. // 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,
  37388. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  37389. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  37390. // 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
  37391. // until we find a SortInfo object without a swapedOffset which means we got the right location
  37392. // 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
  37393. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  37394. for (var i = 0; i < count; i++) {
  37395. // Get the element to move
  37396. var sourceSI = this._sortedTable[i];
  37397. var destSI = this._sortTable[i];
  37398. var sourceOff = sourceSI.offset;
  37399. // If the source changed location, find the new one
  37400. if (sourceSI.swapedOffset) {
  37401. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  37402. var curSI = sourceSI;
  37403. while (curSI.swapedOffset) {
  37404. curSI = this._sortTable[curSI.swapedOffset / stride];
  37405. }
  37406. // Finally get the right location
  37407. sourceOff = curSI.offset;
  37408. }
  37409. // Tag the element being replaced with its new location
  37410. destSI.swapedOffset = sourceOff;
  37411. // Swap elements (only if needed)
  37412. if (sourceOff !== destSI.offset) {
  37413. swapElements(sourceOff, destSI.offset);
  37414. }
  37415. // Update the offset in the corresponding DFAE
  37416. //sourceSI.entry.offset = destSI.entry.offset;
  37417. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  37418. }
  37419. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  37420. return true;
  37421. };
  37422. return DynamicFloatArray;
  37423. })();
  37424. BABYLON.DynamicFloatArray = DynamicFloatArray;
  37425. var SortInfo = (function () {
  37426. function SortInfo() {
  37427. this.compareData = this.offset = this.swapedOffset = null;
  37428. }
  37429. return SortInfo;
  37430. })();
  37431. })(BABYLON || (BABYLON = {}));
  37432. var BABYLON;
  37433. (function (BABYLON) {
  37434. /**
  37435. * This class given information about a given character.
  37436. */
  37437. var CharInfo = (function () {
  37438. function CharInfo() {
  37439. }
  37440. return CharInfo;
  37441. })();
  37442. BABYLON.CharInfo = CharInfo;
  37443. var FontTexture = (function (_super) {
  37444. __extends(FontTexture, _super);
  37445. /**
  37446. * Create a new instance of the FontTexture class
  37447. * @param name the name of the texture
  37448. * @param font the font to use, use the W3C CSS notation
  37449. * @param scene the scene that owns the texture
  37450. * @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
  37451. * @param samplingMode the texture sampling mode
  37452. * @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.
  37453. */
  37454. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample) {
  37455. if (maxCharCount === void 0) { maxCharCount = 200; }
  37456. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37457. if (superSample === void 0) { superSample = false; }
  37458. _super.call(this, null, scene, true, false, samplingMode);
  37459. this._charInfos = {};
  37460. this._curCharCount = 0;
  37461. this._lastUpdateCharCount = -1;
  37462. this._usedCounter = 1;
  37463. this.name = name;
  37464. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37465. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37466. this._superSample = false;
  37467. if (superSample) {
  37468. var sfont = this.getSuperSampleFont(font);
  37469. if (sfont) {
  37470. this._superSample = true;
  37471. font = sfont;
  37472. }
  37473. }
  37474. // First canvas creation to determine the size of the texture to create
  37475. this._canvas = document.createElement("canvas");
  37476. this._context = this._canvas.getContext("2d");
  37477. this._context.font = font;
  37478. this._context.fillStyle = "white";
  37479. this._cachedFontId = null;
  37480. var res = this.getFontHeight(font);
  37481. this._lineHeightSuper = res.height;
  37482. this._lineHeight = this._superSample ? (this._lineHeightSuper / 2) : this._lineHeightSuper;
  37483. this._offset = res.offset - 1;
  37484. var maxCharWidth = this._context.measureText("W").width;
  37485. this._spaceWidthSuper = this._context.measureText(" ").width;
  37486. this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
  37487. // This is an approximate size, but should always be able to fit at least the maxCharCount
  37488. var totalEstSurface = this._lineHeightSuper * maxCharWidth * maxCharCount;
  37489. var edge = Math.sqrt(totalEstSurface);
  37490. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  37491. // Create the texture that will store the font characters
  37492. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  37493. var textureSize = this.getSize();
  37494. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  37495. this._canvas = document.createElement("canvas");
  37496. this._canvas.width = textureSize.width;
  37497. this._canvas.height = textureSize.height;
  37498. this._context = this._canvas.getContext("2d");
  37499. this._context.textBaseline = "top";
  37500. this._context.font = font;
  37501. this._context.fillStyle = "white";
  37502. this._context.imageSmoothingEnabled = false;
  37503. this._currentFreePosition = BABYLON.Vector2.Zero();
  37504. // Add the basic ASCII based characters
  37505. for (var i = 0x20; i < 0x7F; i++) {
  37506. var c = String.fromCharCode(i);
  37507. this.getChar(c);
  37508. }
  37509. this.update();
  37510. }
  37511. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  37512. get: function () {
  37513. return this._superSample;
  37514. },
  37515. enumerable: true,
  37516. configurable: true
  37517. });
  37518. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  37519. get: function () {
  37520. return this._spaceWidth;
  37521. },
  37522. enumerable: true,
  37523. configurable: true
  37524. });
  37525. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  37526. get: function () {
  37527. return this._lineHeight;
  37528. },
  37529. enumerable: true,
  37530. configurable: true
  37531. });
  37532. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample) {
  37533. if (supersample === void 0) { supersample = false; }
  37534. var s = scene;
  37535. if (!s.__fontTextureCache__) {
  37536. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  37537. }
  37538. var dic = s.__fontTextureCache__;
  37539. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  37540. var ft = dic.get(lfn);
  37541. if (ft) {
  37542. ++ft._usedCounter;
  37543. return ft;
  37544. }
  37545. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample);
  37546. ft._cachedFontId = lfn;
  37547. dic.add(lfn, ft);
  37548. return ft;
  37549. };
  37550. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample) {
  37551. if (supersample === void 0) { supersample = false; }
  37552. var s = scene;
  37553. var dic = s.__fontTextureCache__;
  37554. if (!dic) {
  37555. return;
  37556. }
  37557. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  37558. var font = dic.get(lfn);
  37559. if (--font._usedCounter === 0) {
  37560. dic.remove(lfn);
  37561. font.dispose();
  37562. }
  37563. };
  37564. /**
  37565. * Make sure the given char is present in the font map.
  37566. * @param char the character to get or add
  37567. * @return the CharInfo instance corresponding to the given character
  37568. */
  37569. FontTexture.prototype.getChar = function (char) {
  37570. if (char.length !== 1) {
  37571. return null;
  37572. }
  37573. var info = this._charInfos[char];
  37574. if (info) {
  37575. return info;
  37576. }
  37577. info = new CharInfo();
  37578. var measure = this._context.measureText(char);
  37579. var textureSize = this.getSize();
  37580. // we reached the end of the current line?
  37581. var width = Math.round(measure.width);
  37582. var xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  37583. var yMargin = xMargin;
  37584. if (this._currentFreePosition.x + width + xMargin > textureSize.width) {
  37585. this._currentFreePosition.x = 0;
  37586. this._currentFreePosition.y += this._lineHeightSuper + yMargin;
  37587. // No more room?
  37588. if (this._currentFreePosition.y > textureSize.height) {
  37589. return this.getChar("!");
  37590. }
  37591. }
  37592. // Draw the character in the texture
  37593. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  37594. // Fill the CharInfo object
  37595. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  37596. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  37597. info.charWidth = this._superSample ? (width / 2) : width;
  37598. // Add the info structure
  37599. this._charInfos[char] = info;
  37600. this._curCharCount++;
  37601. // Set the next position
  37602. this._currentFreePosition.x += width + xMargin;
  37603. return info;
  37604. };
  37605. FontTexture.prototype.measureText = function (text, tabulationSize) {
  37606. if (tabulationSize === void 0) { tabulationSize = 4; }
  37607. var maxWidth = 0;
  37608. var curWidth = 0;
  37609. var lineCount = 1;
  37610. var charxpos = 0;
  37611. // Parse each char of the string
  37612. for (var _i = 0; _i < text.length; _i++) {
  37613. var char = text[_i];
  37614. // Next line feed?
  37615. if (char === "\n") {
  37616. maxWidth = Math.max(maxWidth, curWidth);
  37617. charxpos = 0;
  37618. curWidth = 0;
  37619. ++lineCount;
  37620. continue;
  37621. }
  37622. // Tabulation ?
  37623. if (char === "\t") {
  37624. var nextPos = charxpos + tabulationSize;
  37625. nextPos = nextPos - (nextPos % tabulationSize);
  37626. curWidth += (nextPos - charxpos) * this.spaceWidth;
  37627. charxpos = nextPos;
  37628. continue;
  37629. }
  37630. if (char < " ") {
  37631. continue;
  37632. }
  37633. curWidth += this.getChar(char).charWidth;
  37634. ++charxpos;
  37635. }
  37636. maxWidth = Math.max(maxWidth, curWidth);
  37637. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  37638. };
  37639. FontTexture.prototype.getSuperSampleFont = function (font) {
  37640. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  37641. 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*$/;
  37642. var res = font.toLocaleLowerCase().match(regex);
  37643. if (res == null) {
  37644. return null;
  37645. }
  37646. var size = parseInt(res[4]);
  37647. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  37648. var newFont = "";
  37649. for (var j = 1; j < res.length; j++) {
  37650. if (res[j] != null) {
  37651. newFont += res[j] + " ";
  37652. }
  37653. }
  37654. return newFont;
  37655. };
  37656. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  37657. FontTexture.prototype.getFontHeight = function (font) {
  37658. var fontDraw = document.createElement("canvas");
  37659. var ctx = fontDraw.getContext('2d');
  37660. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  37661. ctx.textBaseline = 'top';
  37662. ctx.fillStyle = 'white';
  37663. ctx.font = font;
  37664. ctx.fillText('jH|', 0, 0);
  37665. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  37666. var start = -1;
  37667. var end = -1;
  37668. for (var row = 0; row < fontDraw.height; row++) {
  37669. for (var column = 0; column < fontDraw.width; column++) {
  37670. var index = (row * fontDraw.width + column) * 4;
  37671. if (pixels[index] === 0) {
  37672. if (column === fontDraw.width - 1 && start !== -1) {
  37673. end = row;
  37674. row = fontDraw.height;
  37675. break;
  37676. }
  37677. continue;
  37678. }
  37679. else {
  37680. if (start === -1) {
  37681. start = row;
  37682. }
  37683. break;
  37684. }
  37685. }
  37686. }
  37687. return { height: (end - start) + 1, offset: start - 1 };
  37688. };
  37689. Object.defineProperty(FontTexture.prototype, "canRescale", {
  37690. get: function () {
  37691. return false;
  37692. },
  37693. enumerable: true,
  37694. configurable: true
  37695. });
  37696. FontTexture.prototype.getContext = function () {
  37697. return this._context;
  37698. };
  37699. /**
  37700. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  37701. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  37702. */
  37703. FontTexture.prototype.update = function () {
  37704. // Update only if there's new char added since the previous update
  37705. if (this._lastUpdateCharCount < this._curCharCount) {
  37706. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  37707. this._lastUpdateCharCount = this._curCharCount;
  37708. }
  37709. };
  37710. // cloning should be prohibited, there's no point to duplicate this texture at all
  37711. FontTexture.prototype.clone = function () {
  37712. return null;
  37713. };
  37714. /**
  37715. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  37716. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  37717. */
  37718. FontTexture.prototype.incCachedFontTextureCounter = function () {
  37719. ++this._usedCounter;
  37720. };
  37721. /**
  37722. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  37723. */
  37724. FontTexture.prototype.decCachedFontTextureCounter = function () {
  37725. var s = this.getScene();
  37726. var dic = s.__fontTextureCache__;
  37727. if (!dic) {
  37728. return;
  37729. }
  37730. if (--this._usedCounter === 0) {
  37731. dic.remove(this._cachedFontId);
  37732. this.dispose();
  37733. }
  37734. };
  37735. return FontTexture;
  37736. })(BABYLON.Texture);
  37737. BABYLON.FontTexture = FontTexture;
  37738. })(BABYLON || (BABYLON = {}));
  37739. var BABYLON;
  37740. (function (BABYLON) {
  37741. var MapTexture = (function (_super) {
  37742. __extends(MapTexture, _super);
  37743. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  37744. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37745. if (useMipMap === void 0) { useMipMap = false; }
  37746. _super.call(this, null, scene, !useMipMap, false, samplingMode);
  37747. this.name = name;
  37748. this._size = size;
  37749. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37750. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37751. // Create the rectPackMap that will allocate portion of the texture
  37752. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  37753. // Create the texture that will store the content
  37754. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  37755. }
  37756. /**
  37757. * Allocate a rectangle of a given size in the texture map
  37758. * @param size the size of the rectangle to allocation
  37759. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  37760. */
  37761. MapTexture.prototype.allocateRect = function (size) {
  37762. return this._rectPackingMap.addRect(size);
  37763. };
  37764. /**
  37765. * Free a given rectangle from the texture map
  37766. * @param rectInfo the instance corresponding to the rect to free.
  37767. */
  37768. MapTexture.prototype.freeRect = function (rectInfo) {
  37769. if (rectInfo) {
  37770. rectInfo.freeContent();
  37771. }
  37772. };
  37773. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  37774. /**
  37775. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  37776. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  37777. * @returns {}
  37778. */
  37779. get: function () {
  37780. return this._rectPackingMap.freeSpace;
  37781. },
  37782. enumerable: true,
  37783. configurable: true
  37784. });
  37785. /**
  37786. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  37787. * 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.
  37788. * Don't forget to call unbindTexture when you're done rendering
  37789. * @param rect the zone to render to
  37790. * @param clear true to clear the portion's color/depth data
  37791. */
  37792. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  37793. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  37794. };
  37795. /**
  37796. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  37797. * 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.
  37798. * Don't forget to call unbindTexture when you're done rendering
  37799. * @param pos the position into the texture
  37800. * @param size the portion to fit the clip space to
  37801. * @param clear true to clear the portion's color/depth data
  37802. */
  37803. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  37804. var engine = this.getScene().getEngine();
  37805. engine.bindFramebuffer(this._texture);
  37806. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  37807. if (clear) {
  37808. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  37809. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  37810. }
  37811. };
  37812. /**
  37813. * Unbind the texture map from the rendering engine.
  37814. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  37815. * @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.
  37816. */
  37817. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  37818. // Dump ?
  37819. if (dumpForDebug) {
  37820. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  37821. }
  37822. var engine = this.getScene().getEngine();
  37823. if (this._replacedViewport) {
  37824. engine.setViewport(this._replacedViewport);
  37825. this._replacedViewport = null;
  37826. }
  37827. engine.unBindFramebuffer(this._texture);
  37828. };
  37829. Object.defineProperty(MapTexture.prototype, "canRescale", {
  37830. get: function () {
  37831. return false;
  37832. },
  37833. enumerable: true,
  37834. configurable: true
  37835. });
  37836. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  37837. // Anyway, there's not much point to use this method for this kind of texture I guess
  37838. MapTexture.prototype.clone = function () {
  37839. return null;
  37840. };
  37841. return MapTexture;
  37842. })(BABYLON.Texture);
  37843. BABYLON.MapTexture = MapTexture;
  37844. })(BABYLON || (BABYLON = {}));
  37845. var BABYLON;
  37846. (function (BABYLON) {
  37847. /**
  37848. * Stores 2D Bounding Information.
  37849. * This class handles a circle area and a bounding rectangle one.
  37850. */
  37851. var BoundingInfo2D = (function () {
  37852. function BoundingInfo2D() {
  37853. this.radius = 0;
  37854. this.center = BABYLON.Vector2.Zero();
  37855. this.extent = BABYLON.Vector2.Zero();
  37856. }
  37857. /**
  37858. * Create a BoundingInfo2D object from a given size
  37859. * @param size the size that will be used to set the extend, radius will be computed from it.
  37860. */
  37861. BoundingInfo2D.CreateFromSize = function (size) {
  37862. var r = new BoundingInfo2D();
  37863. BoundingInfo2D.CreateFromSizeToRef(size, r);
  37864. return r;
  37865. };
  37866. /**
  37867. * Create a BoundingInfo2D object from a given radius
  37868. * @param radius the radius to use, the extent will be computed from it.
  37869. */
  37870. BoundingInfo2D.CreateFromRadius = function (radius) {
  37871. var r = new BoundingInfo2D();
  37872. BoundingInfo2D.CreateFromRadiusToRef(radius, r);
  37873. return r;
  37874. };
  37875. /**
  37876. * Create a BoundingInfo2D object from a list of points.
  37877. * The resulted object will be the smallest bounding area that includes all the given points.
  37878. * @param points an array of points to compute the bounding object from.
  37879. */
  37880. BoundingInfo2D.CreateFromPoints = function (points) {
  37881. var r = new BoundingInfo2D();
  37882. BoundingInfo2D.CreateFromPointsToRef(points, r);
  37883. return r;
  37884. };
  37885. /**
  37886. * Update a BoundingInfo2D object using the given Size as input
  37887. * @param size the bounding data will be computed from this size.
  37888. * @param b must be a valid/allocated object, it will contain the result of the operation
  37889. */
  37890. BoundingInfo2D.CreateFromSizeToRef = function (size, b) {
  37891. if (!size) {
  37892. size = BABYLON.Size.Zero();
  37893. }
  37894. b.center.x = +size.width / 2;
  37895. b.center.y = +size.height / 2;
  37896. b.extent.x = b.center.x;
  37897. b.extent.y = b.center.y;
  37898. b.radius = b.extent.length();
  37899. };
  37900. /**
  37901. * Update a BoundingInfo2D object using the given radius as input
  37902. * @param radius the bounding data will be computed from this radius
  37903. * @param b must be a valid/allocated object, it will contain the result of the operation
  37904. */
  37905. BoundingInfo2D.CreateFromRadiusToRef = function (radius, b) {
  37906. b.center.x = b.center.y = 0;
  37907. var r = +radius;
  37908. b.extent.x = r;
  37909. b.extent.y = r;
  37910. b.radius = r;
  37911. };
  37912. /**
  37913. * Update a BoundingInfo2D object using the given points array as input
  37914. * @param points the point array to use to update the bounding data
  37915. * @param b must be a valid/allocated object, it will contain the result of the operation
  37916. */
  37917. BoundingInfo2D.CreateFromPointsToRef = function (points, b) {
  37918. var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
  37919. for (var _i = 0; _i < points.length; _i++) {
  37920. var p = points[_i];
  37921. xmin = Math.min(p.x, xmin);
  37922. xmax = Math.max(p.x, xmax);
  37923. ymin = Math.min(p.y, ymin);
  37924. ymax = Math.max(p.y, ymax);
  37925. }
  37926. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b);
  37927. };
  37928. /**
  37929. * Update a BoundingInfo2D object using the given min/max values as input
  37930. * @param xmin the smallest x coordinate
  37931. * @param xmax the biggest x coordinate
  37932. * @param ymin the smallest y coordinate
  37933. * @param ymax the buggest y coordinate
  37934. * @param b must be a valid/allocated object, it will contain the result of the operation
  37935. */
  37936. BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b) {
  37937. var w = xmax - xmin;
  37938. var h = ymax - ymin;
  37939. b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
  37940. b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
  37941. b.radius = b.extent.length();
  37942. };
  37943. /**
  37944. * Duplicate this instance and return a new one
  37945. * @return the duplicated instance
  37946. */
  37947. BoundingInfo2D.prototype.clone = function () {
  37948. var r = new BoundingInfo2D();
  37949. r.center = this.center.clone();
  37950. r.radius = this.radius;
  37951. r.extent = this.extent.clone();
  37952. return r;
  37953. };
  37954. BoundingInfo2D.prototype.clear = function () {
  37955. this.center.copyFromFloats(0, 0);
  37956. this.radius = 0;
  37957. this.extent.copyFromFloats(0, 0);
  37958. };
  37959. BoundingInfo2D.prototype.copyFrom = function (src) {
  37960. this.center.copyFrom(src.center);
  37961. this.radius = src.radius;
  37962. this.extent.copyFrom(src.extent);
  37963. };
  37964. /**
  37965. * return the max extend of the bounding info
  37966. */
  37967. BoundingInfo2D.prototype.max = function () {
  37968. var r = BABYLON.Vector2.Zero();
  37969. this.maxToRef(r);
  37970. return r;
  37971. };
  37972. /**
  37973. * Update a vector2 with the max extend of the bounding info
  37974. * @param result must be a valid/allocated vector2 that will contain the result of the operation
  37975. */
  37976. BoundingInfo2D.prototype.maxToRef = function (result) {
  37977. result.x = this.center.x + this.extent.x;
  37978. result.y = this.center.y + this.extent.y;
  37979. };
  37980. /**
  37981. * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
  37982. * @param matrix the transformation matrix to apply
  37983. * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
  37984. */
  37985. BoundingInfo2D.prototype.transform = function (matrix) {
  37986. var r = new BoundingInfo2D();
  37987. this.transformToRef(matrix, r);
  37988. return r;
  37989. };
  37990. /**
  37991. * Compute the union of this BoundingInfo2D with a given one, returns a new BoundingInfo2D as a result
  37992. * @param other the second BoundingInfo2D to compute the union with this one
  37993. * @return a new instance containing the result of the union
  37994. */
  37995. BoundingInfo2D.prototype.union = function (other) {
  37996. var r = new BoundingInfo2D();
  37997. this.unionToRef(other, r);
  37998. return r;
  37999. };
  38000. /**
  38001. * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
  38002. * 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.
  38003. * @param matrix The matrix to use to compute the transformation
  38004. * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
  38005. */
  38006. BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
  38007. // Construct a bounding box based on the extent values
  38008. var p = BoundingInfo2D._transform;
  38009. p[0].x = this.center.x + this.extent.x;
  38010. p[0].y = this.center.y + this.extent.y;
  38011. p[1].x = this.center.x + this.extent.x;
  38012. p[1].y = this.center.y - this.extent.y;
  38013. p[2].x = this.center.x - this.extent.x;
  38014. p[2].y = this.center.y - this.extent.y;
  38015. p[3].x = this.center.x - this.extent.x;
  38016. p[3].y = this.center.y + this.extent.y;
  38017. // Transform the four points of the bounding box with the matrix
  38018. for (var i = 0; i < 4; i++) {
  38019. BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
  38020. }
  38021. BoundingInfo2D.CreateFromPointsToRef(p, result);
  38022. };
  38023. /**
  38024. * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
  38025. * 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.
  38026. * @param other the second object used to compute the union
  38027. * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
  38028. */
  38029. BoundingInfo2D.prototype.unionToRef = function (other, result) {
  38030. var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
  38031. var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
  38032. var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
  38033. var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
  38034. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
  38035. };
  38036. /**
  38037. * Check if the given point is inside the BoundingInfo.
  38038. * The test is first made on the radius, then inside the rectangle described by the extent
  38039. * @param pickPosition the position to test
  38040. * @return true if the point is inside, false otherwise
  38041. */
  38042. BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
  38043. // is it inside the radius?
  38044. var pickLocal = pickPosition.subtract(this.center);
  38045. if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
  38046. // is it inside the rectangle?
  38047. return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
  38048. }
  38049. return false;
  38050. };
  38051. BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
  38052. return BoundingInfo2D;
  38053. })();
  38054. BABYLON.BoundingInfo2D = BoundingInfo2D;
  38055. })(BABYLON || (BABYLON = {}));
  38056. var BABYLON;
  38057. (function (BABYLON) {
  38058. /**
  38059. * Base class implementing the ILocable interface.
  38060. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  38061. */
  38062. var LockableBase = (function () {
  38063. function LockableBase() {
  38064. }
  38065. LockableBase.prototype.isLocked = function () {
  38066. return this._isLocked;
  38067. };
  38068. LockableBase.prototype.lock = function () {
  38069. if (this._isLocked) {
  38070. return true;
  38071. }
  38072. this.onLock();
  38073. this._isLocked = true;
  38074. return false;
  38075. };
  38076. /**
  38077. * Protected handler that will be called when the instance is about to be locked.
  38078. */
  38079. LockableBase.prototype.onLock = function () {
  38080. };
  38081. return LockableBase;
  38082. })();
  38083. BABYLON.LockableBase = LockableBase;
  38084. var SolidColorBrush2D = (function (_super) {
  38085. __extends(SolidColorBrush2D, _super);
  38086. function SolidColorBrush2D(color, lock) {
  38087. if (lock === void 0) { lock = false; }
  38088. _super.call(this);
  38089. this._color = color;
  38090. if (lock) {
  38091. {
  38092. this.lock();
  38093. }
  38094. }
  38095. }
  38096. /**
  38097. * Return true if the brush is transparent, false if it's totally opaque
  38098. */
  38099. SolidColorBrush2D.prototype.isTransparent = function () {
  38100. return this._color && this._color.a < 1.0;
  38101. };
  38102. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  38103. /**
  38104. * The color used by this instance to render
  38105. * @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.
  38106. */
  38107. get: function () {
  38108. return this._color;
  38109. },
  38110. set: function (value) {
  38111. if (this.isLocked()) {
  38112. return;
  38113. }
  38114. this._color = value;
  38115. },
  38116. enumerable: true,
  38117. configurable: true
  38118. });
  38119. /**
  38120. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  38121. */
  38122. SolidColorBrush2D.prototype.toString = function () {
  38123. return this._color.toHexString();
  38124. };
  38125. SolidColorBrush2D = __decorate([
  38126. BABYLON.className("SolidColorBrush2D")
  38127. ], SolidColorBrush2D);
  38128. return SolidColorBrush2D;
  38129. })(LockableBase);
  38130. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  38131. var GradientColorBrush2D = (function (_super) {
  38132. __extends(GradientColorBrush2D, _super);
  38133. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  38134. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  38135. if (rotation === void 0) { rotation = 0; }
  38136. if (scale === void 0) { scale = 1; }
  38137. if (lock === void 0) { lock = false; }
  38138. _super.call(this);
  38139. this._color1 = color1;
  38140. this._color2 = color2;
  38141. this._translation = translation;
  38142. this._rotation = rotation;
  38143. this._scale = scale;
  38144. if (lock) {
  38145. this.lock();
  38146. }
  38147. }
  38148. /**
  38149. * Return true if the brush is transparent, false if it's totally opaque
  38150. */
  38151. GradientColorBrush2D.prototype.isTransparent = function () {
  38152. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  38153. };
  38154. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  38155. /**
  38156. * First color, the blend will start from this color
  38157. */
  38158. get: function () {
  38159. return this._color1;
  38160. },
  38161. set: function (value) {
  38162. if (this.isLocked()) {
  38163. return;
  38164. }
  38165. this._color1 = value;
  38166. },
  38167. enumerable: true,
  38168. configurable: true
  38169. });
  38170. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  38171. /**
  38172. * Second color, the blend will end to this color
  38173. */
  38174. get: function () {
  38175. return this._color2;
  38176. },
  38177. set: function (value) {
  38178. if (this.isLocked()) {
  38179. return;
  38180. }
  38181. this._color2 = value;
  38182. },
  38183. enumerable: true,
  38184. configurable: true
  38185. });
  38186. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  38187. /**
  38188. * Translation vector to apply on the blend
  38189. * Default is [0;0]
  38190. */
  38191. get: function () {
  38192. return this._translation;
  38193. },
  38194. set: function (value) {
  38195. if (this.isLocked()) {
  38196. return;
  38197. }
  38198. this._translation = value;
  38199. },
  38200. enumerable: true,
  38201. configurable: true
  38202. });
  38203. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  38204. /**
  38205. * Rotation in radian to apply to the brush
  38206. * Default direction of the brush is vertical, you can change this using this property.
  38207. * Default is 0.
  38208. */
  38209. get: function () {
  38210. return this._rotation;
  38211. },
  38212. set: function (value) {
  38213. if (this.isLocked()) {
  38214. return;
  38215. }
  38216. this._rotation = value;
  38217. },
  38218. enumerable: true,
  38219. configurable: true
  38220. });
  38221. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  38222. /**
  38223. * Scale factor to apply to the gradient.
  38224. * Default is 1: no scale.
  38225. */
  38226. get: function () {
  38227. return this._scale;
  38228. },
  38229. set: function (value) {
  38230. if (this.isLocked()) {
  38231. return;
  38232. }
  38233. this._scale = value;
  38234. },
  38235. enumerable: true,
  38236. configurable: true
  38237. });
  38238. /**
  38239. * Return a string describing the brush
  38240. */
  38241. GradientColorBrush2D.prototype.toString = function () {
  38242. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  38243. };
  38244. /**
  38245. * Build a unique key string for the given parameters
  38246. */
  38247. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  38248. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  38249. };
  38250. GradientColorBrush2D = __decorate([
  38251. BABYLON.className("GradientColorBrush2D")
  38252. ], GradientColorBrush2D);
  38253. return GradientColorBrush2D;
  38254. })(LockableBase);
  38255. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  38256. })(BABYLON || (BABYLON = {}));
  38257. var BABYLON;
  38258. (function (BABYLON) {
  38259. var Prim2DClassInfo = (function () {
  38260. function Prim2DClassInfo() {
  38261. }
  38262. return Prim2DClassInfo;
  38263. })();
  38264. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  38265. var Prim2DPropInfo = (function () {
  38266. function Prim2DPropInfo() {
  38267. }
  38268. Prim2DPropInfo.PROPKIND_MODEL = 1;
  38269. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  38270. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  38271. return Prim2DPropInfo;
  38272. })();
  38273. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  38274. /**
  38275. * Custom type of the propertyChanged observable
  38276. */
  38277. var PropertyChangedInfo = (function () {
  38278. function PropertyChangedInfo() {
  38279. }
  38280. return PropertyChangedInfo;
  38281. })();
  38282. BABYLON.PropertyChangedInfo = PropertyChangedInfo;
  38283. var ClassTreeInfo = (function () {
  38284. function ClassTreeInfo(baseClass, type, classContentFactory) {
  38285. this._baseClass = baseClass;
  38286. this._type = type;
  38287. this._subClasses = new Array();
  38288. this._levelContent = new BABYLON.StringDictionary();
  38289. this._classContentFactory = classContentFactory;
  38290. }
  38291. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  38292. get: function () {
  38293. if (!this._classContent) {
  38294. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  38295. }
  38296. return this._classContent;
  38297. },
  38298. enumerable: true,
  38299. configurable: true
  38300. });
  38301. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  38302. get: function () {
  38303. return this._type;
  38304. },
  38305. enumerable: true,
  38306. configurable: true
  38307. });
  38308. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  38309. get: function () {
  38310. return this._levelContent;
  38311. },
  38312. enumerable: true,
  38313. configurable: true
  38314. });
  38315. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  38316. get: function () {
  38317. if (!this._fullContent) {
  38318. var dic = new BABYLON.StringDictionary();
  38319. var curLevel = this;
  38320. while (curLevel) {
  38321. curLevel.levelContent.forEach(function (k, v) { return dic.add(k, v); });
  38322. curLevel = curLevel._baseClass;
  38323. }
  38324. this._fullContent = dic;
  38325. }
  38326. return this._fullContent;
  38327. },
  38328. enumerable: true,
  38329. configurable: true
  38330. });
  38331. ClassTreeInfo.prototype.getLevelOf = function (type) {
  38332. // Are we already there?
  38333. if (type === this._type) {
  38334. return this;
  38335. }
  38336. var baseProto = Object.getPrototypeOf(type);
  38337. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  38338. if (!curProtoContent) {
  38339. this.getLevelOf(baseProto);
  38340. }
  38341. return this.getOrAddType(baseProto, type);
  38342. };
  38343. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  38344. // Are we at the level corresponding to the baseType?
  38345. // If so, get or add the level we're looking for
  38346. if (baseType === this._type) {
  38347. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  38348. var subType = _a[_i];
  38349. if (subType.type === type) {
  38350. return subType.node;
  38351. }
  38352. }
  38353. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  38354. var info = { type: type, node: node };
  38355. this._subClasses.push(info);
  38356. return info.node;
  38357. }
  38358. // Recurse down to keep looking for the node corresponding to the baseTypeName
  38359. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  38360. var subType = _c[_b];
  38361. var info = subType.node.getOrAddType(baseType, type);
  38362. if (info) {
  38363. return info;
  38364. }
  38365. }
  38366. return null;
  38367. };
  38368. ClassTreeInfo.get = function (type) {
  38369. var dic = type["__classTreeInfo"];
  38370. if (!dic) {
  38371. return null;
  38372. }
  38373. return dic.getLevelOf(type);
  38374. };
  38375. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  38376. var dic = type["__classTreeInfo"];
  38377. if (!dic) {
  38378. dic = new ClassTreeInfo(null, type, classContentFactory);
  38379. type["__classTreeInfo"] = dic;
  38380. }
  38381. return dic;
  38382. };
  38383. return ClassTreeInfo;
  38384. })();
  38385. BABYLON.ClassTreeInfo = ClassTreeInfo;
  38386. var SmartPropertyPrim = (function () {
  38387. function SmartPropertyPrim() {
  38388. this._flags = 0;
  38389. this._modelKey = null;
  38390. this._instanceDirtyFlags = 0;
  38391. this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  38392. this.animations = new Array();
  38393. }
  38394. Object.defineProperty(SmartPropertyPrim.prototype, "isDisposed", {
  38395. /**
  38396. * Check if the object is disposed or not.
  38397. * @returns true if the object is dispose, false otherwise.
  38398. */
  38399. get: function () {
  38400. return this._isFlagSet(SmartPropertyPrim.flagIsDisposed);
  38401. },
  38402. enumerable: true,
  38403. configurable: true
  38404. });
  38405. /**
  38406. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  38407. * @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.
  38408. */
  38409. SmartPropertyPrim.prototype.dispose = function () {
  38410. if (this.isDisposed) {
  38411. return false;
  38412. }
  38413. // Don't set to null, it may upset somebody...
  38414. this.animations.splice(0);
  38415. this._setFlags(SmartPropertyPrim.flagIsDisposed);
  38416. return true;
  38417. };
  38418. /**
  38419. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  38420. * Look at Sprite2D for more information
  38421. */
  38422. SmartPropertyPrim.prototype.getAnimatables = function () {
  38423. return new Array();
  38424. };
  38425. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  38426. /**
  38427. * Property giving the Model Key associated to the property.
  38428. * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
  38429. * @returns the model key string.
  38430. */
  38431. get: function () {
  38432. var _this = this;
  38433. // No need to compute it?
  38434. if (!this._isFlagSet(SmartPropertyPrim.flagModelDirty) && this._modelKey) {
  38435. return this._modelKey;
  38436. }
  38437. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  38438. var propDic = this.propDic;
  38439. propDic.forEach(function (k, v) {
  38440. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  38441. var propVal = _this[v.name];
  38442. // 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
  38443. if (propVal && propVal.constructor === Array) {
  38444. var firstVal = propVal[0];
  38445. if (!firstVal) {
  38446. propVal = 0;
  38447. }
  38448. else {
  38449. propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
  38450. }
  38451. }
  38452. modelKey += v.name + ":" + ((propVal != null) ? ((v.typeLevelCompare) ? BABYLON.Tools.getClassName(propVal) : propVal.toString()) : "[null]") + ";";
  38453. }
  38454. });
  38455. this._clearFlags(SmartPropertyPrim.flagModelDirty);
  38456. this._modelKey = modelKey;
  38457. return modelKey;
  38458. },
  38459. enumerable: true,
  38460. configurable: true
  38461. });
  38462. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  38463. /**
  38464. * States if the Primitive is dirty and should be rendered again next time.
  38465. * @returns true is dirty, false otherwise
  38466. */
  38467. get: function () {
  38468. return (this._instanceDirtyFlags !== 0) || this._areSomeFlagsSet(SmartPropertyPrim.flagModelDirty | SmartPropertyPrim.flagPositioningDirty | SmartPropertyPrim.flagLayoutDirty);
  38469. },
  38470. enumerable: true,
  38471. configurable: true
  38472. });
  38473. Object.defineProperty(SmartPropertyPrim.prototype, "propDic", {
  38474. /**
  38475. * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
  38476. * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
  38477. */
  38478. get: function () {
  38479. if (!this._propInfo) {
  38480. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  38481. if (!cti) {
  38482. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  38483. }
  38484. this._propInfo = cti.fullContent;
  38485. }
  38486. return this._propInfo;
  38487. },
  38488. enumerable: true,
  38489. configurable: true
  38490. });
  38491. SmartPropertyPrim._createPropInfo = function (target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind) {
  38492. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  38493. var node = dic.getLevelOf(target);
  38494. var propInfo = node.levelContent.get(propId.toString());
  38495. if (propInfo) {
  38496. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  38497. }
  38498. // Create, setup and add the PropInfo object to our prop dictionary
  38499. propInfo = new Prim2DPropInfo();
  38500. propInfo.id = propId;
  38501. propInfo.flagId = Math.pow(2, propId);
  38502. propInfo.kind = kind;
  38503. propInfo.name = propName;
  38504. propInfo.dirtyBoundingInfo = dirtyBoundingInfo;
  38505. propInfo.dirtyParentBoundingInfo = dirtyParentBoundingBox;
  38506. propInfo.typeLevelCompare = typeLevelCompare;
  38507. node.levelContent.add(propName, propInfo);
  38508. return propInfo;
  38509. };
  38510. SmartPropertyPrim._checkUnchanged = function (curValue, newValue) {
  38511. // Nothing to nothing: nothing to do!
  38512. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  38513. return true;
  38514. }
  38515. // Check value unchanged
  38516. if ((curValue != null) && (newValue != null)) {
  38517. if (typeof (curValue.equals) == "function") {
  38518. if (curValue.equals(newValue)) {
  38519. return true;
  38520. }
  38521. }
  38522. else {
  38523. if (curValue === newValue) {
  38524. return true;
  38525. }
  38526. }
  38527. }
  38528. return false;
  38529. };
  38530. SmartPropertyPrim.prototype.markAsDirty = function (propertyName) {
  38531. if (this.isDisposed) {
  38532. return;
  38533. }
  38534. var i = propertyName.indexOf(".");
  38535. if (i !== -1) {
  38536. propertyName = propertyName.substr(0, i);
  38537. }
  38538. var propInfo = this.propDic.get(propertyName);
  38539. if (!propInfo) {
  38540. return;
  38541. }
  38542. var newValue = this[propertyName];
  38543. this._handlePropChanged(undefined, newValue, propertyName, propInfo, propInfo.typeLevelCompare);
  38544. };
  38545. SmartPropertyPrim.prototype._boundingBoxDirty = function () {
  38546. this._setFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  38547. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  38548. if (this instanceof BABYLON.Prim2DBase) {
  38549. var curprim = this;
  38550. while (curprim) {
  38551. curprim._setFlags(SmartPropertyPrim.flagBoundingInfoDirty);
  38552. if (curprim.isSizeAuto) {
  38553. curprim.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  38554. curprim._setFlags(SmartPropertyPrim.flagPositioningDirty);
  38555. }
  38556. if (curprim instanceof BABYLON.Group2D) {
  38557. if (curprim.isRenderableGroup) {
  38558. break;
  38559. }
  38560. }
  38561. curprim = curprim.parent;
  38562. }
  38563. }
  38564. };
  38565. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  38566. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  38567. if (propInfo.dirtyBoundingInfo) {
  38568. this._boundingBoxDirty();
  38569. }
  38570. else if (propInfo.dirtyParentBoundingInfo) {
  38571. var p = this._parent;
  38572. if (p != null) {
  38573. p._boundingBoxDirty();
  38574. }
  38575. }
  38576. // Trigger property changed
  38577. var info = SmartPropertyPrim.propChangedInfo;
  38578. info.oldValue = curValue;
  38579. info.newValue = newValue;
  38580. info.propertyName = propName;
  38581. var propMask = propInfo.flagId;
  38582. this.propertyChanged.notifyObservers(info, propMask);
  38583. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  38584. if (this instanceof BABYLON.Group2D) {
  38585. this.handleGroupChanged(propInfo);
  38586. }
  38587. // Check for parent layout dirty
  38588. if (this instanceof BABYLON.Prim2DBase) {
  38589. var p = this._parent;
  38590. if (p != null && p.layoutEngine && (p.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  38591. p._setLayoutDirty();
  38592. }
  38593. }
  38594. // For type level compare, if there's a change of type it's a change of model, otherwise we issue an instance change
  38595. var instanceDirty = false;
  38596. if (typeLevelCompare && curValue != null && newValue != null) {
  38597. var cvProto = curValue.__proto__;
  38598. var nvProto = newValue.__proto__;
  38599. instanceDirty = (cvProto === nvProto);
  38600. }
  38601. // Set the dirty flags
  38602. if (!instanceDirty && (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL)) {
  38603. if (!this.isDirty) {
  38604. this._setFlags(SmartPropertyPrim.flagModelDirty);
  38605. }
  38606. }
  38607. else if (instanceDirty || (propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  38608. this.onPrimitivePropertyDirty(propMask);
  38609. }
  38610. };
  38611. SmartPropertyPrim.prototype.onPrimitivePropertyDirty = function (propFlagId) {
  38612. this.onPrimBecomesDirty();
  38613. this._instanceDirtyFlags |= propFlagId;
  38614. };
  38615. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  38616. };
  38617. /**
  38618. * Check if a given set of properties are dirty or not.
  38619. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  38620. * @return true if at least one property is dirty, false if none of them are.
  38621. */
  38622. SmartPropertyPrim.prototype.checkPropertiesDirty = function (flags) {
  38623. return (this._instanceDirtyFlags & flags) !== 0;
  38624. };
  38625. /**
  38626. * Clear a given set of properties.
  38627. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  38628. * @return the new set of property still marked as dirty
  38629. */
  38630. SmartPropertyPrim.prototype.clearPropertiesDirty = function (flags) {
  38631. this._instanceDirtyFlags &= ~flags;
  38632. return this._instanceDirtyFlags;
  38633. };
  38634. SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
  38635. this._instanceDirtyFlags = 0;
  38636. this._clearFlags(SmartPropertyPrim.flagPrimInDirtyList);
  38637. };
  38638. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  38639. /**
  38640. * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
  38641. */
  38642. get: function () {
  38643. if (this._isFlagSet(SmartPropertyPrim.flagLevelBoundingInfoDirty)) {
  38644. this.updateLevelBoundingInfo();
  38645. this._clearFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  38646. }
  38647. return this._levelBoundingInfo;
  38648. },
  38649. enumerable: true,
  38650. configurable: true
  38651. });
  38652. /**
  38653. * This method must be overridden by a given Primitive implementation to compute its boundingInfo
  38654. */
  38655. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  38656. };
  38657. /**
  38658. * Property method called when the Primitive becomes dirty
  38659. */
  38660. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  38661. };
  38662. SmartPropertyPrim._hookProperty = function (propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, kind) {
  38663. return function (target, propName, descriptor) {
  38664. var propInfo = SmartPropertyPrim._createPropInfo(target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind);
  38665. if (piStore) {
  38666. piStore(propInfo);
  38667. }
  38668. var getter = descriptor.get, setter = descriptor.set;
  38669. // Overload the property setter implementation to add our own logic
  38670. descriptor.set = function (val) {
  38671. // check for disposed first, do nothing
  38672. if (this.isDisposed) {
  38673. return;
  38674. }
  38675. var curVal = getter.call(this);
  38676. if (SmartPropertyPrim._checkUnchanged(curVal, val)) {
  38677. return;
  38678. }
  38679. // Cast the object we're working one
  38680. var prim = this;
  38681. // Change the value
  38682. setter.call(this, val);
  38683. // Notify change, dirty flags update
  38684. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  38685. };
  38686. };
  38687. };
  38688. /**
  38689. * Add an externally attached data from its key.
  38690. * This method call will fail and return false, if such key already exists.
  38691. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  38692. * @param key the unique key that identifies the data
  38693. * @param data the data object to associate to the key for this Engine instance
  38694. * @return true if no such key were already present and the data was added successfully, false otherwise
  38695. */
  38696. SmartPropertyPrim.prototype.addExternalData = function (key, data) {
  38697. if (!this._externalData) {
  38698. this._externalData = new BABYLON.StringDictionary();
  38699. }
  38700. return this._externalData.add(key, data);
  38701. };
  38702. /**
  38703. * Get an externally attached data from its key
  38704. * @param key the unique key that identifies the data
  38705. * @return the associated data, if present (can be null), or undefined if not present
  38706. */
  38707. SmartPropertyPrim.prototype.getExternalData = function (key) {
  38708. if (!this._externalData) {
  38709. return null;
  38710. }
  38711. return this._externalData.get(key);
  38712. };
  38713. /**
  38714. * Get an externally attached data from its key, create it using a factory if it's not already present
  38715. * @param key the unique key that identifies the data
  38716. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  38717. * @return the associated data, can be null if the factory returned null.
  38718. */
  38719. SmartPropertyPrim.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  38720. if (!this._externalData) {
  38721. this._externalData = new BABYLON.StringDictionary();
  38722. }
  38723. return this._externalData.getOrAddWithFactory(key, factory);
  38724. };
  38725. /**
  38726. * Remove an externally attached data from the Engine instance
  38727. * @param key the unique key that identifies the data
  38728. * @return true if the data was successfully removed, false if it doesn't exist
  38729. */
  38730. SmartPropertyPrim.prototype.removeExternalData = function (key) {
  38731. if (!this._externalData) {
  38732. return false;
  38733. }
  38734. return this._externalData.remove(key);
  38735. };
  38736. /**
  38737. * Check if a given flag is set
  38738. * @param flag the flag value
  38739. * @return true if set, false otherwise
  38740. */
  38741. SmartPropertyPrim.prototype._isFlagSet = function (flag) {
  38742. return (this._flags & flag) !== 0;
  38743. };
  38744. /**
  38745. * Check if all given flags are set
  38746. * @param flags the flags ORed
  38747. * @return true if all the flags are set, false otherwise
  38748. */
  38749. SmartPropertyPrim.prototype._areAllFlagsSet = function (flags) {
  38750. return (this._flags & flags) === flags;
  38751. };
  38752. /**
  38753. * Check if at least one flag of the given flags is set
  38754. * @param flags the flags ORed
  38755. * @return true if at least one flag is set, false otherwise
  38756. */
  38757. SmartPropertyPrim.prototype._areSomeFlagsSet = function (flags) {
  38758. return (this._flags & flags) !== 0;
  38759. };
  38760. /**
  38761. * Clear the given flags
  38762. * @param flags the flags to clear
  38763. */
  38764. SmartPropertyPrim.prototype._clearFlags = function (flags) {
  38765. this._flags &= ~flags;
  38766. };
  38767. /**
  38768. * Set the given flags to true state
  38769. * @param flags the flags ORed to set
  38770. * @return the flags state before this call
  38771. */
  38772. SmartPropertyPrim.prototype._setFlags = function (flags) {
  38773. var cur = this._flags;
  38774. this._flags |= flags;
  38775. return cur;
  38776. };
  38777. /**
  38778. * Change the state of the given flags
  38779. * @param flags the flags ORed to change
  38780. * @param state true to set them, false to clear them
  38781. */
  38782. SmartPropertyPrim.prototype._changeFlags = function (flags, state) {
  38783. if (state) {
  38784. this._flags |= flags;
  38785. }
  38786. else {
  38787. this._flags &= ~flags;
  38788. }
  38789. };
  38790. SmartPropertyPrim.propChangedInfo = new PropertyChangedInfo();
  38791. SmartPropertyPrim.flagIsDisposed = 0x0000001; // set if the object is already disposed
  38792. SmartPropertyPrim.flagLevelBoundingInfoDirty = 0x0000002; // set if the primitive's level bounding box (not including children) is dirty
  38793. SmartPropertyPrim.flagModelDirty = 0x0000004; // set if the model must be changed
  38794. SmartPropertyPrim.flagLayoutDirty = 0x0000008; // set if the layout must be computed
  38795. SmartPropertyPrim.flagLevelVisible = 0x0000010; // set if the primitive is set as visible for its level only
  38796. SmartPropertyPrim.flagBoundingInfoDirty = 0x0000020; // set if the primitive's overall bounding box (including children) is dirty
  38797. SmartPropertyPrim.flagIsPickable = 0x0000040; // set if the primitive can be picked during interaction
  38798. SmartPropertyPrim.flagIsVisible = 0x0000080; // set if the primitive is concretely visible (use the levelVisible of parents)
  38799. SmartPropertyPrim.flagVisibilityChanged = 0x0000100; // set if there was a transition between visible/hidden status
  38800. SmartPropertyPrim.flagPositioningDirty = 0x0000200; // set if the primitive positioning must be computed
  38801. SmartPropertyPrim.flagTrackedGroup = 0x0000400; // set if the group2D is tracking a scene node
  38802. SmartPropertyPrim.flagWorldCacheChanged = 0x0000800; // set if the cached bitmap of a world space canvas changed
  38803. SmartPropertyPrim.flagChildrenFlatZOrder = 0x0001000; // set if all the children (direct and indirect) will share the same Z-Order
  38804. SmartPropertyPrim.flagZOrderDirty = 0x0002000; // set if the Z-Order for this prim and its children must be recomputed
  38805. SmartPropertyPrim.flagActualOpacityDirty = 0x0004000; // set if the actualOpactity should be recomputed
  38806. SmartPropertyPrim.flagPrimInDirtyList = 0x0008000; // set if the primitive is in the primDirtyList
  38807. SmartPropertyPrim = __decorate([
  38808. BABYLON.className("SmartPropertyPrim")
  38809. ], SmartPropertyPrim);
  38810. return SmartPropertyPrim;
  38811. })();
  38812. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  38813. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  38814. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  38815. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  38816. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  38817. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_MODEL);
  38818. }
  38819. BABYLON.modelLevelProperty = modelLevelProperty;
  38820. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  38821. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  38822. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  38823. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  38824. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_INSTANCE);
  38825. }
  38826. BABYLON.instanceLevelProperty = instanceLevelProperty;
  38827. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  38828. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  38829. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  38830. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  38831. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_DYNAMIC);
  38832. }
  38833. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  38834. })(BABYLON || (BABYLON = {}));
  38835. var BABYLON;
  38836. (function (BABYLON) {
  38837. var PrepareRender2DContext = (function () {
  38838. function PrepareRender2DContext() {
  38839. this.forceRefreshPrimitive = false;
  38840. }
  38841. return PrepareRender2DContext;
  38842. })();
  38843. BABYLON.PrepareRender2DContext = PrepareRender2DContext;
  38844. var Render2DContext = (function () {
  38845. function Render2DContext(renderMode) {
  38846. this._renderMode = renderMode;
  38847. this.useInstancing = false;
  38848. this.groupInfoPartData = null;
  38849. this.partDataStartIndex = this.partDataEndIndex = null;
  38850. this.instancedBuffers = null;
  38851. }
  38852. Object.defineProperty(Render2DContext.prototype, "renderMode", {
  38853. /**
  38854. * Define which render Mode should be used to render the primitive: one of Render2DContext.RenderModeXxxx property
  38855. */
  38856. get: function () {
  38857. return this._renderMode;
  38858. },
  38859. enumerable: true,
  38860. configurable: true
  38861. });
  38862. Object.defineProperty(Render2DContext, "RenderModeOpaque", {
  38863. /**
  38864. * The set of primitives to render is opaque.
  38865. * This is the first rendering pass. All Opaque primitives are rendered. Depth Compare and Write are both enabled.
  38866. */
  38867. get: function () {
  38868. return Render2DContext._renderModeOpaque;
  38869. },
  38870. enumerable: true,
  38871. configurable: true
  38872. });
  38873. Object.defineProperty(Render2DContext, "RenderModeAlphaTest", {
  38874. /**
  38875. * The set of primitives to render is using Alpha Test (aka masking).
  38876. * 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.
  38877. */
  38878. get: function () {
  38879. return Render2DContext._renderModeAlphaTest;
  38880. },
  38881. enumerable: true,
  38882. configurable: true
  38883. });
  38884. Object.defineProperty(Render2DContext, "RenderModeTransparent", {
  38885. /**
  38886. * The set of primitives to render is transparent.
  38887. * 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.
  38888. */
  38889. get: function () {
  38890. return Render2DContext._renderModeTransparent;
  38891. },
  38892. enumerable: true,
  38893. configurable: true
  38894. });
  38895. Render2DContext._renderModeOpaque = 1;
  38896. Render2DContext._renderModeAlphaTest = 2;
  38897. Render2DContext._renderModeTransparent = 3;
  38898. return Render2DContext;
  38899. })();
  38900. BABYLON.Render2DContext = Render2DContext;
  38901. /**
  38902. * This class store information for the pointerEventObservable Observable.
  38903. * 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.
  38904. */
  38905. var PrimitivePointerInfo = (function () {
  38906. function PrimitivePointerInfo() {
  38907. this.primitivePointerPos = BABYLON.Vector2.Zero();
  38908. this.tilt = BABYLON.Vector2.Zero();
  38909. this.cancelBubble = false;
  38910. }
  38911. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  38912. // 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.
  38913. /**
  38914. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  38915. * Bubbles: yes
  38916. */
  38917. get: function () {
  38918. return PrimitivePointerInfo._pointerOver;
  38919. },
  38920. enumerable: true,
  38921. configurable: true
  38922. });
  38923. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  38924. /**
  38925. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  38926. * Bubbles: no
  38927. */
  38928. get: function () {
  38929. return PrimitivePointerInfo._pointerEnter;
  38930. },
  38931. enumerable: true,
  38932. configurable: true
  38933. });
  38934. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  38935. /**
  38936. * 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.
  38937. * Bubbles: yes
  38938. */
  38939. get: function () {
  38940. return PrimitivePointerInfo._pointerDown;
  38941. },
  38942. enumerable: true,
  38943. configurable: true
  38944. });
  38945. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  38946. /**
  38947. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  38948. * Bubbles: yes
  38949. */
  38950. get: function () {
  38951. return PrimitivePointerInfo._pointerMouseWheel;
  38952. },
  38953. enumerable: true,
  38954. configurable: true
  38955. });
  38956. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  38957. /**
  38958. * 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.
  38959. * Bubbles: yes
  38960. */
  38961. get: function () {
  38962. return PrimitivePointerInfo._pointerMove;
  38963. },
  38964. enumerable: true,
  38965. configurable: true
  38966. });
  38967. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  38968. /**
  38969. * 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.
  38970. * Bubbles: yes
  38971. */
  38972. get: function () {
  38973. return PrimitivePointerInfo._pointerUp;
  38974. },
  38975. enumerable: true,
  38976. configurable: true
  38977. });
  38978. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  38979. /**
  38980. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  38981. * Bubbles: yes
  38982. */
  38983. get: function () {
  38984. return PrimitivePointerInfo._pointerOut;
  38985. },
  38986. enumerable: true,
  38987. configurable: true
  38988. });
  38989. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  38990. /**
  38991. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  38992. * Bubbles: no
  38993. */
  38994. get: function () {
  38995. return PrimitivePointerInfo._pointerLeave;
  38996. },
  38997. enumerable: true,
  38998. configurable: true
  38999. });
  39000. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  39001. /**
  39002. * 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.
  39003. * Bubbles: yes
  39004. */
  39005. get: function () {
  39006. return PrimitivePointerInfo._pointerGotCapture;
  39007. },
  39008. enumerable: true,
  39009. configurable: true
  39010. });
  39011. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  39012. /**
  39013. * This event type is raised after pointer capture is released for a pointer.
  39014. * Bubbles: yes
  39015. */
  39016. get: function () {
  39017. return PrimitivePointerInfo._pointerLostCapture;
  39018. },
  39019. enumerable: true,
  39020. configurable: true
  39021. });
  39022. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  39023. get: function () {
  39024. return PrimitivePointerInfo._mouseWheelPrecision;
  39025. },
  39026. enumerable: true,
  39027. configurable: true
  39028. });
  39029. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  39030. this.relatedTarget = prim;
  39031. this.relatedTargetPointerPos = primPointerPos;
  39032. };
  39033. PrimitivePointerInfo.getEventTypeName = function (mask) {
  39034. switch (mask) {
  39035. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  39036. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  39037. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  39038. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  39039. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  39040. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  39041. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  39042. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  39043. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  39044. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  39045. }
  39046. };
  39047. PrimitivePointerInfo._pointerOver = 0x0001;
  39048. PrimitivePointerInfo._pointerEnter = 0x0002;
  39049. PrimitivePointerInfo._pointerDown = 0x0004;
  39050. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  39051. PrimitivePointerInfo._pointerMove = 0x0010;
  39052. PrimitivePointerInfo._pointerUp = 0x0020;
  39053. PrimitivePointerInfo._pointerOut = 0x0040;
  39054. PrimitivePointerInfo._pointerLeave = 0x0080;
  39055. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  39056. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  39057. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  39058. return PrimitivePointerInfo;
  39059. })();
  39060. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  39061. /**
  39062. * Defines the horizontal and vertical alignment information for a Primitive.
  39063. */
  39064. var PrimitiveAlignment = (function () {
  39065. function PrimitiveAlignment(changeCallback) {
  39066. this._changedCallback = changeCallback;
  39067. this._horizontal = PrimitiveAlignment.AlignLeft;
  39068. this._vertical = PrimitiveAlignment.AlignBottom;
  39069. }
  39070. Object.defineProperty(PrimitiveAlignment, "AlignLeft", {
  39071. /**
  39072. * Alignment is made relative to the left edge of the Primitive. Valid for horizontal alignment only.
  39073. */
  39074. get: function () { return PrimitiveAlignment._AlignLeft; },
  39075. enumerable: true,
  39076. configurable: true
  39077. });
  39078. Object.defineProperty(PrimitiveAlignment, "AlignTop", {
  39079. /**
  39080. * Alignment is made relative to the top edge of the Primitive. Valid for vertical alignment only.
  39081. */
  39082. get: function () { return PrimitiveAlignment._AlignTop; },
  39083. enumerable: true,
  39084. configurable: true
  39085. });
  39086. Object.defineProperty(PrimitiveAlignment, "AlignRight", {
  39087. /**
  39088. * Alignment is made relative to the right edge of the Primitive. Valid for horizontal alignment only.
  39089. */
  39090. get: function () { return PrimitiveAlignment._AlignRight; },
  39091. enumerable: true,
  39092. configurable: true
  39093. });
  39094. Object.defineProperty(PrimitiveAlignment, "AlignBottom", {
  39095. /**
  39096. * Alignment is made relative to the bottom edge of the Primitive. Valid for vertical alignment only.
  39097. */
  39098. get: function () { return PrimitiveAlignment._AlignBottom; },
  39099. enumerable: true,
  39100. configurable: true
  39101. });
  39102. Object.defineProperty(PrimitiveAlignment, "AlignCenter", {
  39103. /**
  39104. * Alignment is made to center the content from equal distance to the opposite edges of the Primitive
  39105. */
  39106. get: function () { return PrimitiveAlignment._AlignCenter; },
  39107. enumerable: true,
  39108. configurable: true
  39109. });
  39110. Object.defineProperty(PrimitiveAlignment, "AlignStretch", {
  39111. /**
  39112. * The content is stretched toward the opposite edges of the Primitive
  39113. */
  39114. get: function () { return PrimitiveAlignment._AlignStretch; },
  39115. enumerable: true,
  39116. configurable: true
  39117. });
  39118. Object.defineProperty(PrimitiveAlignment.prototype, "horizontal", {
  39119. /**
  39120. * Get/set the horizontal alignment. Use one of the AlignXXX static properties of this class
  39121. */
  39122. get: function () {
  39123. return this._horizontal;
  39124. },
  39125. set: function (value) {
  39126. if (this._horizontal === value) {
  39127. return;
  39128. }
  39129. this._horizontal = value;
  39130. this._changedCallback();
  39131. },
  39132. enumerable: true,
  39133. configurable: true
  39134. });
  39135. Object.defineProperty(PrimitiveAlignment.prototype, "vertical", {
  39136. /**
  39137. * Get/set the vertical alignment. Use one of the AlignXXX static properties of this class
  39138. */
  39139. get: function () {
  39140. return this._vertical;
  39141. },
  39142. set: function (value) {
  39143. if (this._vertical === value) {
  39144. return;
  39145. }
  39146. this._vertical = value;
  39147. this._changedCallback();
  39148. },
  39149. enumerable: true,
  39150. configurable: true
  39151. });
  39152. /**
  39153. * Set the horizontal alignment from a string value.
  39154. * @param text can be either: 'left','right','center','stretch'
  39155. */
  39156. PrimitiveAlignment.prototype.setHorizontal = function (text) {
  39157. var v = text.trim().toLocaleLowerCase();
  39158. switch (v) {
  39159. case "left":
  39160. this.horizontal = PrimitiveAlignment.AlignLeft;
  39161. return;
  39162. case "right":
  39163. this.horizontal = PrimitiveAlignment.AlignRight;
  39164. return;
  39165. case "center":
  39166. this.horizontal = PrimitiveAlignment.AlignCenter;
  39167. return;
  39168. case "stretch":
  39169. this.horizontal = PrimitiveAlignment.AlignStretch;
  39170. return;
  39171. }
  39172. };
  39173. /**
  39174. * Set the vertical alignment from a string value.
  39175. * @param text can be either: 'top','bottom','center','stretch'
  39176. */
  39177. PrimitiveAlignment.prototype.setVertical = function (text) {
  39178. var v = text.trim().toLocaleLowerCase();
  39179. switch (v) {
  39180. case "top":
  39181. this.vertical = PrimitiveAlignment.AlignTop;
  39182. return;
  39183. case "bottom":
  39184. this.vertical = PrimitiveAlignment.AlignBottom;
  39185. return;
  39186. case "center":
  39187. this.vertical = PrimitiveAlignment.AlignCenter;
  39188. return;
  39189. case "stretch":
  39190. this.vertical = PrimitiveAlignment.AlignStretch;
  39191. return;
  39192. }
  39193. };
  39194. /**
  39195. * Set the horizontal and or vertical alignments from a string value.
  39196. * @param text can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
  39197. */
  39198. PrimitiveAlignment.prototype.fromString = function (value) {
  39199. var m = value.trim().split(",");
  39200. for (var _i = 0; _i < m.length; _i++) {
  39201. var v = m[_i];
  39202. v = v.toLocaleLowerCase().trim();
  39203. // Horizontal
  39204. var i = v.indexOf("h:");
  39205. if (i === -1) {
  39206. i = v.indexOf("horizontal:");
  39207. }
  39208. if (i !== -1) {
  39209. v = v.substr(v.indexOf(":") + 1);
  39210. this.setHorizontal(v);
  39211. continue;
  39212. }
  39213. // Vertical
  39214. i = v.indexOf("v:");
  39215. if (i === -1) {
  39216. i = v.indexOf("vertical:");
  39217. }
  39218. if (i !== -1) {
  39219. v = v.substr(v.indexOf(":") + 1);
  39220. this.setVertical(v);
  39221. continue;
  39222. }
  39223. }
  39224. };
  39225. PrimitiveAlignment._AlignLeft = 1;
  39226. PrimitiveAlignment._AlignTop = 1; // Same as left
  39227. PrimitiveAlignment._AlignRight = 2;
  39228. PrimitiveAlignment._AlignBottom = 2; // Same as right
  39229. PrimitiveAlignment._AlignCenter = 3;
  39230. PrimitiveAlignment._AlignStretch = 4;
  39231. return PrimitiveAlignment;
  39232. })();
  39233. BABYLON.PrimitiveAlignment = PrimitiveAlignment;
  39234. /**
  39235. * Stores information about a Primitive that was intersected
  39236. */
  39237. var PrimitiveIntersectedInfo = (function () {
  39238. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  39239. this.prim = prim;
  39240. this.intersectionLocation = intersectionLocation;
  39241. }
  39242. return PrimitiveIntersectedInfo;
  39243. })();
  39244. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  39245. /**
  39246. * Define a thickness toward every edges of a Primitive to allow margin and padding.
  39247. * The thickness can be expressed as pixels, percentages, inherit the value of the parent primitive or be auto.
  39248. */
  39249. var PrimitiveThickness = (function () {
  39250. function PrimitiveThickness(parentAccess, changedCallback) {
  39251. this._parentAccess = parentAccess;
  39252. this._changedCallback = changedCallback;
  39253. this._pixels = new Array(4);
  39254. this._percentages = new Array(4);
  39255. this._setType(0, PrimitiveThickness.Auto);
  39256. this._setType(1, PrimitiveThickness.Auto);
  39257. this._setType(2, PrimitiveThickness.Auto);
  39258. this._setType(3, PrimitiveThickness.Auto);
  39259. this._pixels[0] = 0;
  39260. this._pixels[1] = 0;
  39261. this._pixels[2] = 0;
  39262. this._pixels[3] = 0;
  39263. }
  39264. /**
  39265. * Set the thickness from a string value
  39266. * @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.
  39267. * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39268. */
  39269. PrimitiveThickness.prototype.fromString = function (thickness) {
  39270. this._clear();
  39271. var m = thickness.trim().split(",");
  39272. // Special case, one value to apply to all edges
  39273. if (m.length === 1 && thickness.indexOf(":") === -1) {
  39274. this._setStringValue(m[0], 0, false);
  39275. this._setStringValue(m[0], 1, false);
  39276. this._setStringValue(m[0], 2, false);
  39277. this._setStringValue(m[0], 3, false);
  39278. this._changedCallback();
  39279. return;
  39280. }
  39281. var res = false;
  39282. for (var _i = 0; _i < m.length; _i++) {
  39283. var cm = m[_i];
  39284. res = this._extractString(cm, false) || res;
  39285. }
  39286. if (!res) {
  39287. throw new Error("Can't parse the string to create a PrimitiveMargin object, format must be: 'top: <value>, left:<value>, right:<value>, bottom:<value>");
  39288. }
  39289. // Check the margin that weren't set and set them in auto
  39290. if ((this._flags & 0x000F) === 0)
  39291. this._flags |= PrimitiveThickness.Pixel << 0;
  39292. if ((this._flags & 0x00F0) === 0)
  39293. this._flags |= PrimitiveThickness.Pixel << 4;
  39294. if ((this._flags & 0x0F00) === 0)
  39295. this._flags |= PrimitiveThickness.Pixel << 8;
  39296. if ((this._flags & 0xF000) === 0)
  39297. this._flags |= PrimitiveThickness.Pixel << 12;
  39298. this._changedCallback();
  39299. };
  39300. /**
  39301. * Set the thickness from multiple string
  39302. * Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39303. * @param top the top thickness to set
  39304. * @param left the left thickness to set
  39305. * @param right the right thickness to set
  39306. * @param bottom the bottom thickness to set
  39307. */
  39308. PrimitiveThickness.prototype.fromStrings = function (top, left, right, bottom) {
  39309. this._clear();
  39310. this._setStringValue(top, 0, false);
  39311. this._setStringValue(left, 1, false);
  39312. this._setStringValue(right, 2, false);
  39313. this._setStringValue(bottom, 3, false);
  39314. this._changedCallback();
  39315. return this;
  39316. };
  39317. /**
  39318. * Set the thickness from pixel values
  39319. * @param top the top thickness in pixels to set
  39320. * @param left the left thickness in pixels to set
  39321. * @param right the right thickness in pixels to set
  39322. * @param bottom the bottom thickness in pixels to set
  39323. */
  39324. PrimitiveThickness.prototype.fromPixels = function (top, left, right, bottom) {
  39325. this._clear();
  39326. this._pixels[0] = top;
  39327. this._pixels[1] = left;
  39328. this._pixels[2] = right;
  39329. this._pixels[3] = bottom;
  39330. this._changedCallback();
  39331. return this;
  39332. };
  39333. /**
  39334. * Apply the same pixel value to all edges
  39335. * @param margin the value to set, in pixels.
  39336. */
  39337. PrimitiveThickness.prototype.fromUniformPixels = function (margin) {
  39338. this._clear();
  39339. this._pixels[0] = margin;
  39340. this._pixels[1] = margin;
  39341. this._pixels[2] = margin;
  39342. this._pixels[3] = margin;
  39343. this._changedCallback();
  39344. return this;
  39345. };
  39346. /**
  39347. * Set all edges in auto
  39348. */
  39349. PrimitiveThickness.prototype.auto = function () {
  39350. this._clear();
  39351. this._flags = (PrimitiveThickness.Auto << 0) | (PrimitiveThickness.Auto << 4) | (PrimitiveThickness.Auto << 8) | (PrimitiveThickness.Auto << 12);
  39352. this._pixels[0] = 0;
  39353. this._pixels[1] = 0;
  39354. this._pixels[2] = 0;
  39355. this._pixels[3] = 0;
  39356. this._changedCallback();
  39357. return this;
  39358. };
  39359. PrimitiveThickness.prototype._clear = function () {
  39360. this._flags = 0;
  39361. this._pixels[0] = 0;
  39362. this._pixels[1] = 0;
  39363. this._pixels[2] = 0;
  39364. this._pixels[3] = 0;
  39365. this._percentages[0] = null;
  39366. this._percentages[1] = null;
  39367. this._percentages[2] = null;
  39368. this._percentages[3] = null;
  39369. };
  39370. PrimitiveThickness.prototype._extractString = function (value, emitChanged) {
  39371. var v = value.trim().toLocaleLowerCase();
  39372. if (v.indexOf("top:") === 0) {
  39373. v = v.substr(4).trim();
  39374. return this._setStringValue(v, 0, emitChanged);
  39375. }
  39376. if (v.indexOf("left:") === 0) {
  39377. v = v.substr(5).trim();
  39378. return this._setStringValue(v, 1, emitChanged);
  39379. }
  39380. if (v.indexOf("right:") === 0) {
  39381. v = v.substr(6).trim();
  39382. return this._setStringValue(v, 2, emitChanged);
  39383. }
  39384. if (v.indexOf("bottom:") === 0) {
  39385. v = v.substr(7).trim();
  39386. return this._setStringValue(v, 3, emitChanged);
  39387. }
  39388. return false;
  39389. };
  39390. PrimitiveThickness.prototype._setStringValue = function (value, index, emitChanged) {
  39391. // Check for auto
  39392. var v = value.trim().toLocaleLowerCase();
  39393. if (v === "auto") {
  39394. if (this._isType(index, PrimitiveThickness.Auto)) {
  39395. return true;
  39396. }
  39397. this._setType(index, PrimitiveThickness.Auto);
  39398. this._pixels[index] = 0;
  39399. if (emitChanged) {
  39400. this._changedCallback();
  39401. }
  39402. }
  39403. else if (v === "inherit") {
  39404. if (this._isType(index, PrimitiveThickness.Inherit)) {
  39405. return true;
  39406. }
  39407. this._setType(index, PrimitiveThickness.Inherit);
  39408. this._pixels[index] = null;
  39409. if (emitChanged) {
  39410. this._changedCallback();
  39411. }
  39412. }
  39413. else {
  39414. var pI = v.indexOf("%");
  39415. // Check for percentage
  39416. if (pI !== -1) {
  39417. var n_1 = v.substr(0, pI);
  39418. var number_1 = Math.round(Number(n_1)) / 100; // Normalize the percentage to [0;1] with a 0.01 precision
  39419. if (this._isType(index, PrimitiveThickness.Percentage) && (this._percentages[index] === number_1)) {
  39420. return true;
  39421. }
  39422. this._setType(index, PrimitiveThickness.Percentage);
  39423. if (isNaN(number_1)) {
  39424. return false;
  39425. }
  39426. this._percentages[index] = number_1;
  39427. if (emitChanged) {
  39428. this._changedCallback();
  39429. }
  39430. return true;
  39431. }
  39432. // Check for pixel
  39433. var n;
  39434. pI = v.indexOf("px");
  39435. if (pI !== -1) {
  39436. n = v.substr(0, pI).trim();
  39437. }
  39438. else {
  39439. n = v;
  39440. }
  39441. var number = Number(n);
  39442. if (this._isType(index, PrimitiveThickness.Pixel) && (this._pixels[index] === number)) {
  39443. return true;
  39444. }
  39445. if (isNaN(number)) {
  39446. return false;
  39447. }
  39448. this._pixels[index] = number;
  39449. this._setType(index, PrimitiveThickness.Pixel);
  39450. if (emitChanged) {
  39451. this._changedCallback();
  39452. }
  39453. return true;
  39454. }
  39455. };
  39456. PrimitiveThickness.prototype._setPixels = function (value, index, emitChanged) {
  39457. // 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
  39458. value = Math.round(value);
  39459. if (this._isType(index, PrimitiveThickness.Pixel) && this._pixels[index] === value) {
  39460. return;
  39461. }
  39462. this._setType(index, PrimitiveThickness.Pixel);
  39463. this._pixels[index] = value;
  39464. if (emitChanged) {
  39465. this._changedCallback();
  39466. }
  39467. };
  39468. PrimitiveThickness.prototype._setPercentage = function (value, index, emitChanged) {
  39469. // Clip Value to bounds
  39470. value = Math.min(1, value);
  39471. value = Math.max(0, value);
  39472. value = Math.round(value * 100) / 100; // 0.01 precision
  39473. if (this._isType(index, PrimitiveThickness.Percentage) && this._percentages[index] === value) {
  39474. return;
  39475. }
  39476. this._setType(index, PrimitiveThickness.Percentage);
  39477. this._percentages[index] = value;
  39478. if (emitChanged) {
  39479. this._changedCallback();
  39480. }
  39481. };
  39482. PrimitiveThickness.prototype._getStringValue = function (index) {
  39483. var f = (this._flags >> (index * 4)) & 0xF;
  39484. switch (f) {
  39485. case PrimitiveThickness.Auto:
  39486. return "auto";
  39487. case PrimitiveThickness.Pixel:
  39488. return this._pixels[index] + "px";
  39489. case PrimitiveThickness.Percentage:
  39490. return this._percentages[index] * 100 + "%";
  39491. case PrimitiveThickness.Inherit:
  39492. return "inherit";
  39493. }
  39494. return "";
  39495. };
  39496. PrimitiveThickness.prototype._isType = function (index, type) {
  39497. var f = (this._flags >> (index * 4)) & 0xF;
  39498. return f === type;
  39499. };
  39500. PrimitiveThickness.prototype._getType = function (index, processInherit) {
  39501. var t = (this._flags >> (index * 4)) & 0xF;
  39502. if (processInherit && (t === PrimitiveThickness.Inherit)) {
  39503. var p = this._parentAccess();
  39504. if (p) {
  39505. return p._getType(index, true);
  39506. }
  39507. return PrimitiveThickness.Auto;
  39508. }
  39509. return t;
  39510. };
  39511. PrimitiveThickness.prototype._setType = function (index, type) {
  39512. this._flags &= ~(0xF << (index * 4));
  39513. this._flags |= type << (index * 4);
  39514. };
  39515. PrimitiveThickness.prototype.setTop = function (value) {
  39516. if (typeof value === "string") {
  39517. this._setStringValue(value, 0, true);
  39518. }
  39519. else {
  39520. this.topPixels = value;
  39521. }
  39522. };
  39523. PrimitiveThickness.prototype.setLeft = function (value) {
  39524. if (typeof value === "string") {
  39525. this._setStringValue(value, 1, true);
  39526. }
  39527. else {
  39528. this.leftPixels = value;
  39529. }
  39530. };
  39531. PrimitiveThickness.prototype.setRight = function (value) {
  39532. if (typeof value === "string") {
  39533. this._setStringValue(value, 2, true);
  39534. }
  39535. else {
  39536. this.rightPixels = value;
  39537. }
  39538. };
  39539. PrimitiveThickness.prototype.setBottom = function (value) {
  39540. if (typeof value === "string") {
  39541. this._setStringValue(value, 3, true);
  39542. }
  39543. else {
  39544. this.bottomPixels = value;
  39545. }
  39546. };
  39547. Object.defineProperty(PrimitiveThickness.prototype, "top", {
  39548. /**
  39549. * Get/set the top thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39550. */
  39551. get: function () {
  39552. return this._getStringValue(0);
  39553. },
  39554. set: function (value) {
  39555. this._setStringValue(value, 0, true);
  39556. },
  39557. enumerable: true,
  39558. configurable: true
  39559. });
  39560. Object.defineProperty(PrimitiveThickness.prototype, "left", {
  39561. /**
  39562. * Get/set the left thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39563. */
  39564. get: function () {
  39565. return this._getStringValue(1);
  39566. },
  39567. set: function (value) {
  39568. this._setStringValue(value, 1, true);
  39569. },
  39570. enumerable: true,
  39571. configurable: true
  39572. });
  39573. Object.defineProperty(PrimitiveThickness.prototype, "right", {
  39574. /**
  39575. * Get/set the right thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39576. */
  39577. get: function () {
  39578. return this._getStringValue(2);
  39579. },
  39580. set: function (value) {
  39581. this._setStringValue(value, 2, true);
  39582. },
  39583. enumerable: true,
  39584. configurable: true
  39585. });
  39586. Object.defineProperty(PrimitiveThickness.prototype, "bottom", {
  39587. /**
  39588. * Get/set the bottom thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39589. */
  39590. get: function () {
  39591. return this._getStringValue(3);
  39592. },
  39593. set: function (value) {
  39594. this._setStringValue(value, 3, true);
  39595. },
  39596. enumerable: true,
  39597. configurable: true
  39598. });
  39599. Object.defineProperty(PrimitiveThickness.prototype, "topPixels", {
  39600. /**
  39601. * Get/set the top thickness in pixel.
  39602. */
  39603. get: function () {
  39604. return this._pixels[0];
  39605. },
  39606. set: function (value) {
  39607. this._setPixels(value, 0, true);
  39608. },
  39609. enumerable: true,
  39610. configurable: true
  39611. });
  39612. Object.defineProperty(PrimitiveThickness.prototype, "leftPixels", {
  39613. /**
  39614. * Get/set the left thickness in pixel.
  39615. */
  39616. get: function () {
  39617. return this._pixels[1];
  39618. },
  39619. set: function (value) {
  39620. this._setPixels(value, 1, true);
  39621. },
  39622. enumerable: true,
  39623. configurable: true
  39624. });
  39625. Object.defineProperty(PrimitiveThickness.prototype, "rightPixels", {
  39626. /**
  39627. * Get/set the right thickness in pixel.
  39628. */
  39629. get: function () {
  39630. return this._pixels[2];
  39631. },
  39632. set: function (value) {
  39633. this._setPixels(value, 2, true);
  39634. },
  39635. enumerable: true,
  39636. configurable: true
  39637. });
  39638. Object.defineProperty(PrimitiveThickness.prototype, "bottomPixels", {
  39639. /**
  39640. * Get/set the bottom thickness in pixel.
  39641. */
  39642. get: function () {
  39643. return this._pixels[3];
  39644. },
  39645. set: function (value) {
  39646. this._setPixels(value, 3, true);
  39647. },
  39648. enumerable: true,
  39649. configurable: true
  39650. });
  39651. Object.defineProperty(PrimitiveThickness.prototype, "topPercentage", {
  39652. /**
  39653. * Get/set the top thickness in percentage.
  39654. * The get will return a valid value only if the edge type is percentage.
  39655. * The Set will change the edge mode if needed
  39656. */
  39657. get: function () {
  39658. return this._percentages[0];
  39659. },
  39660. set: function (value) {
  39661. this._setPercentage(value, 0, true);
  39662. },
  39663. enumerable: true,
  39664. configurable: true
  39665. });
  39666. Object.defineProperty(PrimitiveThickness.prototype, "leftPercentage", {
  39667. /**
  39668. * Get/set the left thickness in percentage.
  39669. * The get will return a valid value only if the edge mode is percentage.
  39670. * The Set will change the edge mode if needed
  39671. */
  39672. get: function () {
  39673. return this._percentages[1];
  39674. },
  39675. set: function (value) {
  39676. this._setPercentage(value, 1, true);
  39677. },
  39678. enumerable: true,
  39679. configurable: true
  39680. });
  39681. Object.defineProperty(PrimitiveThickness.prototype, "rightPercentage", {
  39682. /**
  39683. * Get/set the right thickness in percentage.
  39684. * The get will return a valid value only if the edge mode is percentage.
  39685. * The Set will change the edge mode if needed
  39686. */
  39687. get: function () {
  39688. return this._percentages[2];
  39689. },
  39690. set: function (value) {
  39691. this._setPercentage(value, 2, true);
  39692. },
  39693. enumerable: true,
  39694. configurable: true
  39695. });
  39696. Object.defineProperty(PrimitiveThickness.prototype, "bottomPercentage", {
  39697. /**
  39698. * Get/set the bottom thickness in percentage.
  39699. * The get will return a valid value only if the edge mode is percentage.
  39700. * The Set will change the edge mode if needed
  39701. */
  39702. get: function () {
  39703. return this._percentages[3];
  39704. },
  39705. set: function (value) {
  39706. this._setPercentage(value, 3, true);
  39707. },
  39708. enumerable: true,
  39709. configurable: true
  39710. });
  39711. Object.defineProperty(PrimitiveThickness.prototype, "topMode", {
  39712. /**
  39713. * Get/set the top mode. The setter shouldn't be used, other setters with value should be preferred
  39714. */
  39715. get: function () {
  39716. return this._getType(0, false);
  39717. },
  39718. set: function (mode) {
  39719. this._setType(0, mode);
  39720. },
  39721. enumerable: true,
  39722. configurable: true
  39723. });
  39724. Object.defineProperty(PrimitiveThickness.prototype, "leftMode", {
  39725. /**
  39726. * Get/set the left mode. The setter shouldn't be used, other setters with value should be preferred
  39727. */
  39728. get: function () {
  39729. return this._getType(1, false);
  39730. },
  39731. set: function (mode) {
  39732. this._setType(1, mode);
  39733. },
  39734. enumerable: true,
  39735. configurable: true
  39736. });
  39737. Object.defineProperty(PrimitiveThickness.prototype, "rightMode", {
  39738. /**
  39739. * Get/set the right mode. The setter shouldn't be used, other setters with value should be preferred
  39740. */
  39741. get: function () {
  39742. return this._getType(2, false);
  39743. },
  39744. set: function (mode) {
  39745. this._setType(2, mode);
  39746. },
  39747. enumerable: true,
  39748. configurable: true
  39749. });
  39750. Object.defineProperty(PrimitiveThickness.prototype, "bottomMode", {
  39751. /**
  39752. * Get/set the bottom mode. The setter shouldn't be used, other setters with value should be preferred
  39753. */
  39754. get: function () {
  39755. return this._getType(3, false);
  39756. },
  39757. set: function (mode) {
  39758. this._setType(3, mode);
  39759. },
  39760. enumerable: true,
  39761. configurable: true
  39762. });
  39763. PrimitiveThickness.prototype._computePixels = function (index, sourceArea, emitChanged) {
  39764. var type = this._getType(index, false);
  39765. if (type === PrimitiveThickness.Inherit) {
  39766. this._parentAccess()._computePixels(index, sourceArea, emitChanged);
  39767. return;
  39768. }
  39769. if (type !== PrimitiveThickness.Percentage) {
  39770. return;
  39771. }
  39772. var pixels = ((index === 0 || index === 3) ? sourceArea.height : sourceArea.width) * this._percentages[index];
  39773. this._pixels[index] = pixels;
  39774. if (emitChanged) {
  39775. this._changedCallback();
  39776. }
  39777. };
  39778. /**
  39779. * Compute the positioning/size of an area considering the thickness of this object and a given alignment
  39780. * @param sourceArea the source area
  39781. * @param contentSize the content size to position/resize
  39782. * @param alignment the alignment setting
  39783. * @param dstOffset the position of the content
  39784. * @param dstArea the new size of the content
  39785. */
  39786. PrimitiveThickness.prototype.computeWithAlignment = function (sourceArea, contentSize, alignment, dstOffset, dstArea) {
  39787. // Fetch some data
  39788. var topType = this._getType(0, true);
  39789. var leftType = this._getType(1, true);
  39790. var rightType = this._getType(2, true);
  39791. var bottomType = this._getType(3, true);
  39792. var hasWidth = contentSize && (contentSize.width != null);
  39793. var hasHeight = contentSize && (contentSize.height != null);
  39794. var width = hasWidth ? contentSize.width : 0;
  39795. var height = hasHeight ? contentSize.height : 0;
  39796. var isTopAuto = topType === PrimitiveThickness.Auto;
  39797. var isLeftAuto = leftType === PrimitiveThickness.Auto;
  39798. var isRightAuto = rightType === PrimitiveThickness.Auto;
  39799. var isBottomAuto = bottomType === PrimitiveThickness.Auto;
  39800. switch (alignment.horizontal) {
  39801. case PrimitiveAlignment.AlignLeft:
  39802. {
  39803. if (isLeftAuto) {
  39804. dstOffset.x = 0;
  39805. }
  39806. else {
  39807. this._computePixels(1, sourceArea, true);
  39808. dstOffset.x = this.leftPixels;
  39809. }
  39810. dstArea.width = width;
  39811. break;
  39812. }
  39813. case PrimitiveAlignment.AlignRight:
  39814. {
  39815. if (isRightAuto) {
  39816. dstOffset.x = Math.round(sourceArea.width - width);
  39817. }
  39818. else {
  39819. this._computePixels(2, sourceArea, true);
  39820. dstOffset.x = Math.round(sourceArea.width - (width + this.rightPixels));
  39821. }
  39822. dstArea.width = width;
  39823. break;
  39824. }
  39825. case PrimitiveAlignment.AlignStretch:
  39826. {
  39827. if (isLeftAuto) {
  39828. dstOffset.x = 0;
  39829. }
  39830. else {
  39831. this._computePixels(1, sourceArea, true);
  39832. dstOffset.x = this.leftPixels;
  39833. }
  39834. var right = 0;
  39835. if (!isRightAuto) {
  39836. this._computePixels(2, sourceArea, true);
  39837. right = this.rightPixels;
  39838. }
  39839. dstArea.width = sourceArea.width - (dstOffset.x + right);
  39840. break;
  39841. }
  39842. case PrimitiveAlignment.AlignCenter:
  39843. {
  39844. if (!isLeftAuto) {
  39845. this._computePixels(1, sourceArea, true);
  39846. }
  39847. if (!isRightAuto) {
  39848. this._computePixels(2, sourceArea, true);
  39849. }
  39850. var offset = (isLeftAuto ? 0 : this.leftPixels) - (isRightAuto ? 0 : this.rightPixels);
  39851. dstOffset.x = Math.round(((sourceArea.width - width) / 2) + offset);
  39852. dstArea.width = width;
  39853. break;
  39854. }
  39855. }
  39856. switch (alignment.vertical) {
  39857. case PrimitiveAlignment.AlignTop:
  39858. {
  39859. if (isTopAuto) {
  39860. dstOffset.y = sourceArea.height - height;
  39861. }
  39862. else {
  39863. this._computePixels(0, sourceArea, true);
  39864. dstOffset.y = Math.round(sourceArea.height - (height + this.topPixels));
  39865. }
  39866. dstArea.height = height;
  39867. break;
  39868. }
  39869. case PrimitiveAlignment.AlignBottom:
  39870. {
  39871. if (isBottomAuto) {
  39872. dstOffset.y = 0;
  39873. }
  39874. else {
  39875. this._computePixels(3, sourceArea, true);
  39876. dstOffset.y = this.bottomPixels;
  39877. }
  39878. dstArea.height = height;
  39879. break;
  39880. }
  39881. case PrimitiveAlignment.AlignStretch:
  39882. {
  39883. if (isBottomAuto) {
  39884. dstOffset.y = 0;
  39885. }
  39886. else {
  39887. this._computePixels(3, sourceArea, true);
  39888. dstOffset.y = this.bottomPixels;
  39889. }
  39890. var top_1 = 0;
  39891. if (!isTopAuto) {
  39892. this._computePixels(0, sourceArea, true);
  39893. top_1 = this.topPixels;
  39894. }
  39895. dstArea.height = sourceArea.height - (dstOffset.y + top_1);
  39896. break;
  39897. }
  39898. case PrimitiveAlignment.AlignCenter:
  39899. {
  39900. if (!isTopAuto) {
  39901. this._computePixels(0, sourceArea, true);
  39902. }
  39903. if (!isBottomAuto) {
  39904. this._computePixels(3, sourceArea, true);
  39905. }
  39906. var offset = (isBottomAuto ? 0 : this.bottomPixels) - (isTopAuto ? 0 : this.topPixels);
  39907. dstOffset.y = Math.round(((sourceArea.height - height) / 2) + offset);
  39908. dstArea.height = height;
  39909. break;
  39910. }
  39911. }
  39912. };
  39913. /**
  39914. * Compute an area and its position considering this thickness properties based on a given source area
  39915. * @param sourceArea the source area
  39916. * @param dstOffset the position of the resulting area
  39917. * @param dstArea the size of the resulting area
  39918. */
  39919. PrimitiveThickness.prototype.compute = function (sourceArea, dstOffset, dstArea) {
  39920. this._computePixels(0, sourceArea, true);
  39921. this._computePixels(1, sourceArea, true);
  39922. this._computePixels(2, sourceArea, true);
  39923. this._computePixels(3, sourceArea, true);
  39924. dstOffset.x = this.leftPixels;
  39925. dstArea.width = sourceArea.width - (dstOffset.x + this.rightPixels);
  39926. dstOffset.y = this.bottomPixels;
  39927. dstArea.height = sourceArea.height - (dstOffset.y + this.topPixels);
  39928. };
  39929. /**
  39930. * Compute an area considering this thickness properties based on a given source area
  39931. * @param sourceArea the source area
  39932. * @param result the resulting area
  39933. */
  39934. PrimitiveThickness.prototype.computeArea = function (sourceArea, result) {
  39935. this._computePixels(0, sourceArea, true);
  39936. this._computePixels(1, sourceArea, true);
  39937. this._computePixels(2, sourceArea, true);
  39938. this._computePixels(3, sourceArea, true);
  39939. result.width = this.leftPixels + sourceArea.width + this.rightPixels;
  39940. result.height = this.bottomPixels + sourceArea.height + this.topPixels;
  39941. };
  39942. PrimitiveThickness.prototype.enlarge = function (sourceArea, dstOffset, enlargedArea) {
  39943. this._computePixels(0, sourceArea, true);
  39944. this._computePixels(1, sourceArea, true);
  39945. this._computePixels(2, sourceArea, true);
  39946. this._computePixels(3, sourceArea, true);
  39947. dstOffset.x = this.leftPixels;
  39948. enlargedArea.width = sourceArea.width + (dstOffset.x + this.rightPixels);
  39949. dstOffset.y = this.bottomPixels;
  39950. enlargedArea.height = sourceArea.height + (dstOffset.y + this.topPixels);
  39951. };
  39952. PrimitiveThickness.Auto = 0x1;
  39953. PrimitiveThickness.Inherit = 0x2;
  39954. PrimitiveThickness.Percentage = 0x4;
  39955. PrimitiveThickness.Pixel = 0x8;
  39956. return PrimitiveThickness;
  39957. })();
  39958. BABYLON.PrimitiveThickness = PrimitiveThickness;
  39959. /**
  39960. * Main class used for the Primitive Intersection API
  39961. */
  39962. var IntersectInfo2D = (function () {
  39963. function IntersectInfo2D() {
  39964. this.findFirstOnly = false;
  39965. this.intersectHidden = false;
  39966. this.pickPosition = BABYLON.Vector2.Zero();
  39967. }
  39968. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  39969. /**
  39970. * true if at least one primitive intersected during the test
  39971. */
  39972. get: function () {
  39973. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  39974. },
  39975. enumerable: true,
  39976. configurable: true
  39977. });
  39978. IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
  39979. for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
  39980. var cur = _a[_i];
  39981. if (cur.prim === prim) {
  39982. return cur.intersectionLocation;
  39983. }
  39984. }
  39985. return null;
  39986. };
  39987. // Internals, don't use
  39988. IntersectInfo2D.prototype._exit = function (firstLevel) {
  39989. if (firstLevel) {
  39990. this._globalPickPosition = null;
  39991. }
  39992. };
  39993. return IntersectInfo2D;
  39994. })();
  39995. BABYLON.IntersectInfo2D = IntersectInfo2D;
  39996. var Prim2DBase = (function (_super) {
  39997. __extends(Prim2DBase, _super);
  39998. function Prim2DBase(settings) {
  39999. // Avoid checking every time if the object exists
  40000. if (settings == null) {
  40001. settings = {};
  40002. }
  40003. // BASE CLASS CALL
  40004. _super.call(this);
  40005. // Fetch the owner, parent. There're many ways to do it and we can end up with nothing for both
  40006. var owner;
  40007. var parent;
  40008. if (Prim2DBase._isCanvasInit) {
  40009. owner = this;
  40010. parent = null;
  40011. this._canvasPreInit(settings);
  40012. }
  40013. else {
  40014. if (settings.parent != null) {
  40015. parent = settings.parent;
  40016. owner = settings.parent.owner;
  40017. if (!owner) {
  40018. throw new Error("Parent " + parent.id + " of " + settings.id + " doesn't have a valid owner!");
  40019. }
  40020. 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)) {
  40021. 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");
  40022. }
  40023. }
  40024. }
  40025. // Fields initialization
  40026. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  40027. this._size = null; //Size.Zero();
  40028. this._scale = new BABYLON.Vector2(1, 1);
  40029. this._actualSize = null;
  40030. this._boundingSize = BABYLON.Size.Zero();
  40031. this._layoutArea = BABYLON.Size.Zero();
  40032. this._layoutAreaPos = BABYLON.Vector2.Zero();
  40033. this._marginOffset = BABYLON.Vector2.Zero();
  40034. this._paddingOffset = BABYLON.Vector2.Zero();
  40035. this._parentPaddingOffset = BABYLON.Vector2.Zero();
  40036. this._parentContentArea = BABYLON.Size.Zero();
  40037. this._lastAutoSizeArea = BABYLON.Size.Zero();
  40038. this._contentArea = new BABYLON.Size(null, null);
  40039. this._pointerEventObservable = new BABYLON.Observable();
  40040. this._boundingInfo = new BABYLON.BoundingInfo2D();
  40041. this._owner = owner;
  40042. this._parent = null;
  40043. this._margin = null;
  40044. this._padding = null;
  40045. this._marginAlignment = null;
  40046. this._id = settings.id;
  40047. this.propertyChanged = new BABYLON.Observable();
  40048. this._children = new Array();
  40049. this._localTransform = new BABYLON.Matrix();
  40050. this._globalTransform = null;
  40051. this._invGlobalTransform = null;
  40052. this._globalTransformProcessStep = 0;
  40053. this._globalTransformStep = 0;
  40054. this._renderGroup = null;
  40055. this._primLinearPosition = 0;
  40056. this._manualZOrder = null;
  40057. this._zOrder = 0;
  40058. this._zMax = 0;
  40059. this._firstZDirtyIndex = Prim2DBase._bigInt;
  40060. this._setFlags(BABYLON.SmartPropertyPrim.flagIsPickable | BABYLON.SmartPropertyPrim.flagBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  40061. if (settings.opacity != null) {
  40062. this._opacity = settings.opacity;
  40063. }
  40064. else {
  40065. this._opacity = 1;
  40066. }
  40067. this._updateRenderMode();
  40068. if (settings.childrenFlatZOrder) {
  40069. this._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  40070. }
  40071. // If the parent is given, initialize the hierarchy/owner related data
  40072. if (parent != null) {
  40073. parent.addChild(this);
  40074. this._patchHierarchy(parent.owner);
  40075. }
  40076. // If it's a group, detect its own states
  40077. if (this.owner && this instanceof BABYLON.Group2D) {
  40078. var group = this;
  40079. group.detectGroupStates();
  40080. }
  40081. // Time to insert children if some are specified
  40082. if (settings.children != null) {
  40083. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  40084. var child = _a[_i];
  40085. this.addChild(child);
  40086. // Good time to patch the hierarchy, it won't go very far if there's no need to
  40087. child._patchHierarchy(this.owner);
  40088. }
  40089. }
  40090. if (settings.zOrder != null) {
  40091. this.zOrder = settings.zOrder;
  40092. }
  40093. // Set the model related properties
  40094. if (settings.position != null) {
  40095. this.position = settings.position;
  40096. }
  40097. else if (settings.x != null || settings.y != null) {
  40098. this.position = new BABYLON.Vector2(settings.x || 0, settings.y || 0);
  40099. }
  40100. else {
  40101. this._position = null;
  40102. }
  40103. this.rotation = (settings.rotation == null) ? 0 : settings.rotation;
  40104. if (settings.scale != null) {
  40105. this.scale = settings.scale;
  40106. }
  40107. else {
  40108. if (settings.scaleX != null) {
  40109. this.scaleX = settings.scaleX;
  40110. }
  40111. if (settings.scaleY != null) {
  40112. this.scaleY = settings.scaleY;
  40113. }
  40114. }
  40115. this.levelVisible = (settings.isVisible == null) ? true : settings.isVisible;
  40116. this.origin = settings.origin || new BABYLON.Vector2(0.5, 0.5);
  40117. // Layout Engine
  40118. if (settings.layoutEngine != null) {
  40119. if (typeof settings.layoutEngine === "string") {
  40120. var name_1 = settings.layoutEngine.toLocaleLowerCase().trim();
  40121. if (name_1 === "canvas" || name_1 === "canvaslayoutengine") {
  40122. this.layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  40123. }
  40124. else if (name_1.indexOf("stackpanel") === 0 || name_1.indexOf("horizontalstackpanel") === 0) {
  40125. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Horizontal;
  40126. }
  40127. else if (name_1.indexOf("verticalstackpanel") === 0) {
  40128. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Vertical;
  40129. }
  40130. }
  40131. else if (settings.layoutEngine instanceof BABYLON.LayoutEngineBase) {
  40132. this.layoutEngine = settings.layoutEngine;
  40133. }
  40134. }
  40135. // Set the layout/margin stuffs
  40136. if (settings.marginTop) {
  40137. this.margin.setTop(settings.marginTop);
  40138. }
  40139. if (settings.marginLeft) {
  40140. this.margin.setLeft(settings.marginLeft);
  40141. }
  40142. if (settings.marginRight) {
  40143. this.margin.setRight(settings.marginRight);
  40144. }
  40145. if (settings.marginBottom) {
  40146. this.margin.setBottom(settings.marginBottom);
  40147. }
  40148. if (settings.margin) {
  40149. if (typeof settings.margin === "string") {
  40150. this.margin.fromString(settings.margin);
  40151. }
  40152. else {
  40153. this.margin.fromUniformPixels(settings.margin);
  40154. }
  40155. }
  40156. if (settings.marginHAlignment) {
  40157. this.marginAlignment.horizontal = settings.marginHAlignment;
  40158. }
  40159. if (settings.marginVAlignment) {
  40160. this.marginAlignment.vertical = settings.marginVAlignment;
  40161. }
  40162. if (settings.marginAlignment) {
  40163. this.marginAlignment.fromString(settings.marginAlignment);
  40164. }
  40165. if (settings.paddingTop) {
  40166. this.padding.setTop(settings.paddingTop);
  40167. }
  40168. if (settings.paddingLeft) {
  40169. this.padding.setLeft(settings.paddingLeft);
  40170. }
  40171. if (settings.paddingRight) {
  40172. this.padding.setRight(settings.paddingRight);
  40173. }
  40174. if (settings.paddingBottom) {
  40175. this.padding.setBottom(settings.paddingBottom);
  40176. }
  40177. if (settings.padding) {
  40178. this.padding.fromString(settings.padding);
  40179. }
  40180. // Dirty layout and positioning
  40181. this._parentLayoutDirty();
  40182. this._positioningDirty();
  40183. }
  40184. Object.defineProperty(Prim2DBase.prototype, "actionManager", {
  40185. get: function () {
  40186. if (!this._actionManager) {
  40187. this._actionManager = new BABYLON.ActionManager(this.owner.scene);
  40188. }
  40189. return this._actionManager;
  40190. },
  40191. enumerable: true,
  40192. configurable: true
  40193. });
  40194. /**
  40195. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  40196. * @param predicate the predicate to test on each parent
  40197. * @return the first primitive where the predicate was successful
  40198. */
  40199. Prim2DBase.prototype.traverseUp = function (predicate) {
  40200. var p = this;
  40201. while (p != null) {
  40202. if (predicate(p)) {
  40203. return p;
  40204. }
  40205. p = p._parent;
  40206. }
  40207. return null;
  40208. };
  40209. Object.defineProperty(Prim2DBase.prototype, "owner", {
  40210. /**
  40211. * Retrieve the owner Canvas2D
  40212. */
  40213. get: function () {
  40214. return this._owner;
  40215. },
  40216. enumerable: true,
  40217. configurable: true
  40218. });
  40219. Object.defineProperty(Prim2DBase.prototype, "parent", {
  40220. /**
  40221. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  40222. */
  40223. get: function () {
  40224. return this._parent;
  40225. },
  40226. enumerable: true,
  40227. configurable: true
  40228. });
  40229. Object.defineProperty(Prim2DBase.prototype, "children", {
  40230. /**
  40231. * The array of direct children primitives
  40232. */
  40233. get: function () {
  40234. return this._children;
  40235. },
  40236. enumerable: true,
  40237. configurable: true
  40238. });
  40239. Object.defineProperty(Prim2DBase.prototype, "id", {
  40240. /**
  40241. * The identifier of this primitive, may not be unique, it's for information purpose only
  40242. */
  40243. get: function () {
  40244. return this._id;
  40245. },
  40246. enumerable: true,
  40247. configurable: true
  40248. });
  40249. Object.defineProperty(Prim2DBase.prototype, "actualPosition", {
  40250. get: function () {
  40251. if (this._actualPosition != null) {
  40252. return this._actualPosition;
  40253. }
  40254. if (this._position != null) {
  40255. return this._position;
  40256. }
  40257. // At least return 0,0, we can't return null on actualPosition
  40258. return Prim2DBase._nullPosition;
  40259. },
  40260. /**
  40261. * DO NOT INVOKE for internal purpose only
  40262. */
  40263. set: function (val) {
  40264. this._actualPosition = val;
  40265. },
  40266. enumerable: true,
  40267. configurable: true
  40268. });
  40269. Object.defineProperty(Prim2DBase.prototype, "actualX", {
  40270. /**
  40271. * Shortcut to actualPosition.x
  40272. */
  40273. get: function () {
  40274. return this.actualPosition.x;
  40275. },
  40276. enumerable: true,
  40277. configurable: true
  40278. });
  40279. Object.defineProperty(Prim2DBase.prototype, "actualY", {
  40280. /**
  40281. * Shortcut to actualPosition.y
  40282. */
  40283. get: function () {
  40284. return this.actualPosition.y;
  40285. },
  40286. enumerable: true,
  40287. configurable: true
  40288. });
  40289. Object.defineProperty(Prim2DBase.prototype, "position", {
  40290. /**
  40291. * Position of the primitive, relative to its parent.
  40292. * BEWARE: if you change only position.x or y it won't trigger a property change and you won't have the expected behavior.
  40293. * Use this property to set a new Vector2 object, otherwise to change only the x/y use Prim2DBase.x or y properties.
  40294. * Setting this property may have no effect is specific alignment are in effect.
  40295. */
  40296. get: function () {
  40297. return this._position || Prim2DBase._nullPosition;
  40298. },
  40299. set: function (value) {
  40300. if (!this._checkPositionChange()) {
  40301. return;
  40302. }
  40303. this._position = value;
  40304. this.markAsDirty("actualPosition");
  40305. },
  40306. enumerable: true,
  40307. configurable: true
  40308. });
  40309. Object.defineProperty(Prim2DBase.prototype, "x", {
  40310. /**
  40311. * Direct access to the position.x value of the primitive
  40312. * Use this property when you only want to change one component of the position property
  40313. */
  40314. get: function () {
  40315. if (!this._position) {
  40316. return null;
  40317. }
  40318. return this._position.x;
  40319. },
  40320. set: function (value) {
  40321. if (!this._checkPositionChange()) {
  40322. return;
  40323. }
  40324. if (!this._position) {
  40325. this._position = BABYLON.Vector2.Zero();
  40326. }
  40327. if (this._position.x === value) {
  40328. return;
  40329. }
  40330. this._position.x = value;
  40331. this.markAsDirty("position");
  40332. this.markAsDirty("actualPosition");
  40333. },
  40334. enumerable: true,
  40335. configurable: true
  40336. });
  40337. Object.defineProperty(Prim2DBase.prototype, "y", {
  40338. /**
  40339. * Direct access to the position.y value of the primitive
  40340. * Use this property when you only want to change one component of the position property
  40341. */
  40342. get: function () {
  40343. if (!this._position) {
  40344. return null;
  40345. }
  40346. return this._position.y;
  40347. },
  40348. set: function (value) {
  40349. if (!this._checkPositionChange()) {
  40350. return;
  40351. }
  40352. if (!this._position) {
  40353. this._position = BABYLON.Vector2.Zero();
  40354. }
  40355. if (this._position.y === value) {
  40356. return;
  40357. }
  40358. this._position.y = value;
  40359. this.markAsDirty("position");
  40360. this.markAsDirty("actualPosition");
  40361. },
  40362. enumerable: true,
  40363. configurable: true
  40364. });
  40365. Object.defineProperty(Prim2DBase.prototype, "size", {
  40366. /**
  40367. * Size of the primitive or its bounding area
  40368. * BEWARE: if you change only size.width or height it won't trigger a property change and you won't have the expected behavior.
  40369. * Use this property to set a new Size object, otherwise to change only the width/height use Prim2DBase.width or height properties.
  40370. */
  40371. get: function () {
  40372. if (!this._size || this._size.width == null || this._size.height == null) {
  40373. if (Prim2DBase.boundinbBoxReentrency) {
  40374. return Prim2DBase.nullSize;
  40375. }
  40376. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  40377. return this._boundingSize;
  40378. }
  40379. Prim2DBase.boundinbBoxReentrency = true;
  40380. var b = this.boundingInfo;
  40381. Prim2DBase.boundinbBoxReentrency = false;
  40382. return this._boundingSize;
  40383. }
  40384. return this._size;
  40385. },
  40386. set: function (value) {
  40387. this._size = value;
  40388. },
  40389. enumerable: true,
  40390. configurable: true
  40391. });
  40392. Object.defineProperty(Prim2DBase.prototype, "width", {
  40393. /**
  40394. * Direct access to the size.width value of the primitive
  40395. * Use this property when you only want to change one component of the size property
  40396. */
  40397. get: function () {
  40398. if (!this.size) {
  40399. return null;
  40400. }
  40401. return this.size.width;
  40402. },
  40403. set: function (value) {
  40404. if (!this.size) {
  40405. this.size = new BABYLON.Size(value, 0);
  40406. return;
  40407. }
  40408. if (this.size.width === value) {
  40409. return;
  40410. }
  40411. this.size.width = value;
  40412. this.markAsDirty("size");
  40413. this._positioningDirty();
  40414. },
  40415. enumerable: true,
  40416. configurable: true
  40417. });
  40418. Object.defineProperty(Prim2DBase.prototype, "height", {
  40419. /**
  40420. * Direct access to the size.height value of the primitive
  40421. * Use this property when you only want to change one component of the size property
  40422. */
  40423. get: function () {
  40424. if (!this.size) {
  40425. return null;
  40426. }
  40427. return this.size.height;
  40428. },
  40429. set: function (value) {
  40430. if (!this.size) {
  40431. this.size = new BABYLON.Size(0, value);
  40432. return;
  40433. }
  40434. if (this.size.height === value) {
  40435. return;
  40436. }
  40437. this.size.height = value;
  40438. this.markAsDirty("size");
  40439. this._positioningDirty();
  40440. },
  40441. enumerable: true,
  40442. configurable: true
  40443. });
  40444. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  40445. get: function () {
  40446. return this._rotation;
  40447. },
  40448. set: function (value) {
  40449. this._rotation = value;
  40450. },
  40451. enumerable: true,
  40452. configurable: true
  40453. });
  40454. Object.defineProperty(Prim2DBase.prototype, "scale", {
  40455. get: function () {
  40456. return this._scale.x;
  40457. },
  40458. set: function (value) {
  40459. this._scale.x = this._scale.y = value;
  40460. },
  40461. enumerable: true,
  40462. configurable: true
  40463. });
  40464. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  40465. /**
  40466. * Return the size of the primitive as it's being rendered into the target.
  40467. * 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.
  40468. * BEWARE: don't use the setter, it's for internal purpose only
  40469. * Note to implementers: you have to override this property and declare if necessary a @xxxxInstanceLevel decorator
  40470. */
  40471. get: function () {
  40472. if (this._actualSize) {
  40473. return this._actualSize;
  40474. }
  40475. return this._size;
  40476. },
  40477. set: function (value) {
  40478. if (this._actualSize.equals(value)) {
  40479. return;
  40480. }
  40481. this._actualSize = value;
  40482. },
  40483. enumerable: true,
  40484. configurable: true
  40485. });
  40486. Object.defineProperty(Prim2DBase.prototype, "actualZOffset", {
  40487. get: function () {
  40488. if (this._manualZOrder != null) {
  40489. return this._manualZOrder;
  40490. }
  40491. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  40492. this._updateZOrder();
  40493. }
  40494. return (1 - this._zOrder);
  40495. },
  40496. enumerable: true,
  40497. configurable: true
  40498. });
  40499. Object.defineProperty(Prim2DBase.prototype, "minSize", {
  40500. /**
  40501. * Get or set the minimal size the Layout Engine should respect when computing the primitive's actualSize.
  40502. * The Primitive's size won't be less than specified.
  40503. * The default value depends of the Primitive type
  40504. */
  40505. get: function () {
  40506. return this._minSize;
  40507. },
  40508. set: function (value) {
  40509. if (this._minSize && value && this._minSize.equals(value)) {
  40510. return;
  40511. }
  40512. this._minSize = value;
  40513. this._parentLayoutDirty();
  40514. },
  40515. enumerable: true,
  40516. configurable: true
  40517. });
  40518. Object.defineProperty(Prim2DBase.prototype, "maxSize", {
  40519. /**
  40520. * Get or set the maximal size the Layout Engine should respect when computing the primitive's actualSize.
  40521. * The Primitive's size won't be more than specified.
  40522. * The default value depends of the Primitive type
  40523. */
  40524. get: function () {
  40525. return this._maxSize;
  40526. },
  40527. set: function (value) {
  40528. if (this._maxSize && value && this._maxSize.equals(value)) {
  40529. return;
  40530. }
  40531. this._maxSize = value;
  40532. this._parentLayoutDirty();
  40533. },
  40534. enumerable: true,
  40535. configurable: true
  40536. });
  40537. Object.defineProperty(Prim2DBase.prototype, "origin", {
  40538. /**
  40539. * The origin defines the normalized coordinate of the center of the primitive, from the bottom/left corner.
  40540. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  40541. * For instance:
  40542. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  40543. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  40544. * 0,1 means the center is top/left
  40545. * @returns The normalized center.
  40546. */
  40547. get: function () {
  40548. return this._origin;
  40549. },
  40550. set: function (value) {
  40551. this._origin = value;
  40552. },
  40553. enumerable: true,
  40554. configurable: true
  40555. });
  40556. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  40557. get: function () {
  40558. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelVisible);
  40559. },
  40560. set: function (value) {
  40561. this._changeFlags(BABYLON.SmartPropertyPrim.flagLevelVisible, value);
  40562. },
  40563. enumerable: true,
  40564. configurable: true
  40565. });
  40566. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  40567. get: function () {
  40568. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsVisible);
  40569. },
  40570. set: function (value) {
  40571. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsVisible, value);
  40572. },
  40573. enumerable: true,
  40574. configurable: true
  40575. });
  40576. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  40577. get: function () {
  40578. return this._manualZOrder;
  40579. },
  40580. set: function (value) {
  40581. if (this._manualZOrder === value) {
  40582. return;
  40583. }
  40584. this._manualZOrder = value;
  40585. this.onZOrderChanged();
  40586. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  40587. this._actualZOrderChangedObservable.notifyObservers(value);
  40588. }
  40589. },
  40590. enumerable: true,
  40591. configurable: true
  40592. });
  40593. Object.defineProperty(Prim2DBase.prototype, "isManualZOrder", {
  40594. get: function () {
  40595. return this._manualZOrder != null;
  40596. },
  40597. enumerable: true,
  40598. configurable: true
  40599. });
  40600. Object.defineProperty(Prim2DBase.prototype, "margin", {
  40601. get: function () {
  40602. var _this = this;
  40603. if (!this._margin) {
  40604. this._margin = new PrimitiveThickness(function () {
  40605. if (!_this.parent) {
  40606. return null;
  40607. }
  40608. return _this.parent.margin;
  40609. }, function () { return _this._positioningDirty(); });
  40610. }
  40611. return this._margin;
  40612. },
  40613. enumerable: true,
  40614. configurable: true
  40615. });
  40616. Object.defineProperty(Prim2DBase.prototype, "_hasMargin", {
  40617. get: function () {
  40618. return (this._margin !== null) || (this._marginAlignment !== null);
  40619. },
  40620. enumerable: true,
  40621. configurable: true
  40622. });
  40623. Object.defineProperty(Prim2DBase.prototype, "padding", {
  40624. get: function () {
  40625. var _this = this;
  40626. if (!this._padding) {
  40627. this._padding = new PrimitiveThickness(function () {
  40628. if (!_this.parent) {
  40629. return null;
  40630. }
  40631. return _this.parent.padding;
  40632. }, function () { return _this._positioningDirty(); });
  40633. }
  40634. return this._padding;
  40635. },
  40636. enumerable: true,
  40637. configurable: true
  40638. });
  40639. Object.defineProperty(Prim2DBase.prototype, "_hasPadding", {
  40640. get: function () {
  40641. return this._padding !== null;
  40642. },
  40643. enumerable: true,
  40644. configurable: true
  40645. });
  40646. Object.defineProperty(Prim2DBase.prototype, "marginAlignment", {
  40647. get: function () {
  40648. var _this = this;
  40649. if (!this._marginAlignment) {
  40650. this._marginAlignment = new PrimitiveAlignment(function () { return _this._positioningDirty(); });
  40651. }
  40652. return this._marginAlignment;
  40653. },
  40654. enumerable: true,
  40655. configurable: true
  40656. });
  40657. Object.defineProperty(Prim2DBase.prototype, "opacity", {
  40658. get: function () {
  40659. return this._opacity;
  40660. },
  40661. set: function (value) {
  40662. if (value < 0) {
  40663. value = 0;
  40664. }
  40665. else if (value > 1) {
  40666. value = 1;
  40667. }
  40668. if (this._opacity === value) {
  40669. return;
  40670. }
  40671. this._opacity = value;
  40672. this._updateRenderMode();
  40673. this._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  40674. this._spreadActualOpacityChanged();
  40675. },
  40676. enumerable: true,
  40677. configurable: true
  40678. });
  40679. Object.defineProperty(Prim2DBase.prototype, "scaleX", {
  40680. get: function () {
  40681. return this._scale.x;
  40682. },
  40683. set: function (value) {
  40684. this._scale.x = value;
  40685. },
  40686. enumerable: true,
  40687. configurable: true
  40688. });
  40689. Object.defineProperty(Prim2DBase.prototype, "scaleY", {
  40690. get: function () {
  40691. return this._scale.y;
  40692. },
  40693. set: function (value) {
  40694. this._scale.y = value;
  40695. },
  40696. enumerable: true,
  40697. configurable: true
  40698. });
  40699. Object.defineProperty(Prim2DBase.prototype, "actualOpacity", {
  40700. get: function () {
  40701. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualOpacityDirty)) {
  40702. var cur = this.parent;
  40703. var op = this.opacity;
  40704. while (cur) {
  40705. op *= cur.opacity;
  40706. cur = cur.parent;
  40707. }
  40708. this._actualOpacity = op;
  40709. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  40710. }
  40711. return this._actualOpacity;
  40712. },
  40713. enumerable: true,
  40714. configurable: true
  40715. });
  40716. Object.defineProperty(Prim2DBase.prototype, "layoutEngine", {
  40717. /**
  40718. * Get/set the layout engine to use for this primitive.
  40719. * The default layout engine is the CanvasLayoutEngine.
  40720. */
  40721. get: function () {
  40722. if (!this._layoutEngine) {
  40723. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  40724. }
  40725. return this._layoutEngine;
  40726. },
  40727. set: function (value) {
  40728. if (this._layoutEngine === value) {
  40729. return;
  40730. }
  40731. this._changeLayoutEngine(value);
  40732. },
  40733. enumerable: true,
  40734. configurable: true
  40735. });
  40736. Object.defineProperty(Prim2DBase.prototype, "layoutArea", {
  40737. /**
  40738. * Get/set the layout are of this primitive.
  40739. * The Layout area is the zone allocated by the Layout Engine for this particular primitive. Margins/Alignment will be computed based on this area.
  40740. * The setter should only be called by a Layout Engine class.
  40741. */
  40742. get: function () {
  40743. return this._layoutArea;
  40744. },
  40745. set: function (val) {
  40746. if (this._layoutArea.equals(val)) {
  40747. return;
  40748. }
  40749. this._positioningDirty();
  40750. this._layoutArea = val;
  40751. },
  40752. enumerable: true,
  40753. configurable: true
  40754. });
  40755. Object.defineProperty(Prim2DBase.prototype, "layoutAreaPos", {
  40756. /**
  40757. * Get/set the layout area position (relative to the parent primitive).
  40758. * The setter should only be called by a Layout Engine class.
  40759. */
  40760. get: function () {
  40761. return this._layoutAreaPos;
  40762. },
  40763. set: function (val) {
  40764. if (this._layoutAreaPos.equals(val)) {
  40765. return;
  40766. }
  40767. this._positioningDirty();
  40768. this._layoutAreaPos = val;
  40769. },
  40770. enumerable: true,
  40771. configurable: true
  40772. });
  40773. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  40774. /**
  40775. * Define if the Primitive can be subject to intersection test or not (default is true)
  40776. */
  40777. get: function () {
  40778. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsPickable);
  40779. },
  40780. set: function (value) {
  40781. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsPickable, value);
  40782. },
  40783. enumerable: true,
  40784. configurable: true
  40785. });
  40786. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  40787. /**
  40788. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  40789. */
  40790. get: function () {
  40791. return this._hierarchyDepth;
  40792. },
  40793. enumerable: true,
  40794. configurable: true
  40795. });
  40796. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  40797. /**
  40798. * Retrieve the Group that is responsible to render this primitive
  40799. */
  40800. get: function () {
  40801. return this._renderGroup;
  40802. },
  40803. enumerable: true,
  40804. configurable: true
  40805. });
  40806. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  40807. /**
  40808. * Get the global transformation matrix of the primitive
  40809. */
  40810. get: function () {
  40811. return this._globalTransform;
  40812. },
  40813. enumerable: true,
  40814. configurable: true
  40815. });
  40816. /**
  40817. * return the global position of the primitive, relative to its canvas
  40818. */
  40819. Prim2DBase.prototype.getGlobalPosition = function () {
  40820. var v = new BABYLON.Vector2(0, 0);
  40821. this.getGlobalPositionByRef(v);
  40822. return v;
  40823. };
  40824. /**
  40825. * return the global position of the primitive, relative to its canvas
  40826. * @param v the valid Vector2 object where the global position will be stored
  40827. */
  40828. Prim2DBase.prototype.getGlobalPositionByRef = function (v) {
  40829. v.x = this.globalTransform.m[12];
  40830. v.y = this.globalTransform.m[13];
  40831. };
  40832. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  40833. /**
  40834. * Get invert of the global transformation matrix of the primitive
  40835. */
  40836. get: function () {
  40837. return this._invGlobalTransform;
  40838. },
  40839. enumerable: true,
  40840. configurable: true
  40841. });
  40842. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  40843. /**
  40844. * Get the local transformation of the primitive
  40845. */
  40846. get: function () {
  40847. this._updateLocalTransform();
  40848. return this._localTransform;
  40849. },
  40850. enumerable: true,
  40851. configurable: true
  40852. });
  40853. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  40854. /**
  40855. * Get the boundingInfo associated to the primitive and its children.
  40856. * The value is supposed to be always up to date
  40857. */
  40858. get: function () {
  40859. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  40860. if (this.owner) {
  40861. this.owner.boundingInfoRecomputeCounter.addCount(1, false);
  40862. }
  40863. if (this.isSizedByContent) {
  40864. this._boundingInfo.clear();
  40865. }
  40866. else {
  40867. this._boundingInfo.copyFrom(this.levelBoundingInfo);
  40868. }
  40869. var bi = this._boundingInfo;
  40870. var tps = new BABYLON.BoundingInfo2D();
  40871. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40872. var curChild = _a[_i];
  40873. curChild.boundingInfo.transformToRef(curChild.localTransform, tps);
  40874. bi.unionToRef(tps, bi);
  40875. }
  40876. this._boundingInfo.maxToRef(Prim2DBase._bMax);
  40877. 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);
  40878. this._clearFlags(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
  40879. }
  40880. return this._boundingInfo;
  40881. },
  40882. enumerable: true,
  40883. configurable: true
  40884. });
  40885. Object.defineProperty(Prim2DBase.prototype, "isSizeAuto", {
  40886. /**
  40887. * Determine if the size is automatically computed or fixed because manually specified.
  40888. * Use the actualSize property to get the final/real size of the primitive
  40889. * @returns true if the size is automatically computed, false if it were manually specified.
  40890. */
  40891. get: function () {
  40892. return this._size == null;
  40893. },
  40894. enumerable: true,
  40895. configurable: true
  40896. });
  40897. Object.defineProperty(Prim2DBase.prototype, "isSizedByContent", {
  40898. /**
  40899. * Return true if this prim has an auto size which is set by the children's global bounding box
  40900. */
  40901. get: function () {
  40902. return (this._size == null) && (this._children.length > 0);
  40903. },
  40904. enumerable: true,
  40905. configurable: true
  40906. });
  40907. Object.defineProperty(Prim2DBase.prototype, "isPositionAuto", {
  40908. /**
  40909. * Determine if the position is automatically computed or fixed because manually specified.
  40910. * Use the actualPosition property to get the final/real position of the primitive
  40911. * @returns true if the position is automatically computed, false if it were manually specified.
  40912. */
  40913. get: function () {
  40914. return this._position == null;
  40915. },
  40916. enumerable: true,
  40917. configurable: true
  40918. });
  40919. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  40920. /**
  40921. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  40922. */
  40923. get: function () {
  40924. return this._pointerEventObservable;
  40925. },
  40926. enumerable: true,
  40927. configurable: true
  40928. });
  40929. Object.defineProperty(Prim2DBase.prototype, "zActualOrderChangedObservable", {
  40930. get: function () {
  40931. if (!this._actualZOrderChangedObservable) {
  40932. this._actualZOrderChangedObservable = new BABYLON.Observable();
  40933. }
  40934. return this._actualZOrderChangedObservable;
  40935. },
  40936. enumerable: true,
  40937. configurable: true
  40938. });
  40939. Prim2DBase.prototype.findById = function (id) {
  40940. if (this._id === id) {
  40941. return this;
  40942. }
  40943. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40944. var child = _a[_i];
  40945. var r = child.findById(id);
  40946. if (r != null) {
  40947. return r;
  40948. }
  40949. }
  40950. };
  40951. Prim2DBase.prototype.onZOrderChanged = function () {
  40952. };
  40953. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  40954. return false;
  40955. };
  40956. /**
  40957. * Capture all the Events of the given PointerId for this primitive.
  40958. * Don't forget to call releasePointerEventsCapture when done.
  40959. * @param pointerId the Id of the pointer to capture the events from.
  40960. */
  40961. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  40962. return this.owner._setPointerCapture(pointerId, this);
  40963. };
  40964. /**
  40965. * Release a captured pointer made with setPointerEventCapture.
  40966. * @param pointerId the Id of the pointer to release the capture from.
  40967. */
  40968. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  40969. return this.owner._releasePointerCapture(pointerId, this);
  40970. };
  40971. /**
  40972. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  40973. * @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.
  40974. */
  40975. Prim2DBase.prototype.intersect = function (intersectInfo) {
  40976. if (!intersectInfo) {
  40977. return false;
  40978. }
  40979. // If this is null it means this method is call for the first level, initialize stuffs
  40980. var firstLevel = !intersectInfo._globalPickPosition;
  40981. if (firstLevel) {
  40982. // 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).
  40983. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  40984. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  40985. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  40986. intersectInfo.intersectedPrimitives = new Array();
  40987. intersectInfo.topMostIntersectedPrimitive = null;
  40988. }
  40989. if (!intersectInfo.intersectHidden && !this.isVisible) {
  40990. return false;
  40991. }
  40992. // Fast rejection test with boundingInfo
  40993. if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  40994. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  40995. intersectInfo._exit(firstLevel);
  40996. return false;
  40997. }
  40998. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  40999. var levelIntersectRes = false;
  41000. if (this.isPickable) {
  41001. levelIntersectRes = this.levelIntersect(intersectInfo);
  41002. if (levelIntersectRes) {
  41003. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  41004. intersectInfo.intersectedPrimitives.push(pii);
  41005. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.actualZOffset > pii.prim.actualZOffset)) {
  41006. intersectInfo.topMostIntersectedPrimitive = pii;
  41007. }
  41008. // If we must stop at the first intersection, we're done, quit!
  41009. if (intersectInfo.findFirstOnly) {
  41010. intersectInfo._exit(firstLevel);
  41011. return true;
  41012. }
  41013. }
  41014. }
  41015. // Recurse to children if needed
  41016. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  41017. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41018. var curChild = _a[_i];
  41019. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  41020. if (!curChild.isPickable || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  41021. continue;
  41022. }
  41023. // Must compute the localPickLocation for the children level
  41024. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  41025. // If we got an intersection with the child and we only need to find the first one, quit!
  41026. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  41027. intersectInfo._exit(firstLevel);
  41028. return true;
  41029. }
  41030. }
  41031. }
  41032. intersectInfo._exit(firstLevel);
  41033. return intersectInfo.isIntersected;
  41034. };
  41035. Prim2DBase.prototype.moveChild = function (child, previous) {
  41036. if (child.parent !== this) {
  41037. return false;
  41038. }
  41039. var childIndex = this._children.indexOf(child);
  41040. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  41041. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  41042. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41043. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, prevIndex + 1);
  41044. }
  41045. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  41046. };
  41047. Prim2DBase.prototype.addChild = function (child) {
  41048. child._parent = this;
  41049. this._boundingBoxDirty();
  41050. var flat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  41051. if (flat) {
  41052. child._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  41053. child._setZOrder(this._zOrder, true);
  41054. child._zMax = this._zOrder;
  41055. }
  41056. else {
  41057. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41058. }
  41059. var length = this._children.push(child);
  41060. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, length - 1);
  41061. };
  41062. /**
  41063. * Dispose the primitive, remove it from its parent.
  41064. */
  41065. Prim2DBase.prototype.dispose = function () {
  41066. if (!_super.prototype.dispose.call(this)) {
  41067. return false;
  41068. }
  41069. if (this._actionManager) {
  41070. this._actionManager.dispose();
  41071. this._actionManager = null;
  41072. }
  41073. // If there's a parent, remove this object from its parent list
  41074. if (this._parent) {
  41075. var i = this._parent._children.indexOf(this);
  41076. if (i !== undefined) {
  41077. this._parent._children.splice(i, 1);
  41078. }
  41079. this._parent = null;
  41080. }
  41081. // Recurse dispose to children
  41082. if (this._children) {
  41083. while (this._children.length > 0) {
  41084. this._children[this._children.length - 1].dispose();
  41085. }
  41086. }
  41087. return true;
  41088. };
  41089. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  41090. if (this._renderGroup && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPrimInDirtyList)) {
  41091. this._renderGroup._addPrimToDirtyList(this);
  41092. this._setFlags(BABYLON.SmartPropertyPrim.flagPrimInDirtyList);
  41093. }
  41094. };
  41095. Prim2DBase.prototype._needPrepare = function () {
  41096. return this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagModelDirty) || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  41097. };
  41098. Prim2DBase.prototype._prepareRender = function (context) {
  41099. this._prepareRenderPre(context);
  41100. this._prepareRenderPost(context);
  41101. };
  41102. Prim2DBase.prototype._prepareRenderPre = function (context) {
  41103. };
  41104. Prim2DBase.prototype._prepareRenderPost = function (context) {
  41105. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  41106. if (this instanceof BABYLON.Group2D) {
  41107. var self = this;
  41108. if (self.isRenderableGroup) {
  41109. return;
  41110. }
  41111. }
  41112. // Check if we need to recurse the prepare to children primitives
  41113. // - must have children
  41114. // - the global transform of this level have changed, or
  41115. // - the visible state of primitive has changed
  41116. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  41117. this.checkPropertiesDirty(Prim2DBase.isVisibleProperty.flagId))) {
  41118. this._children.forEach(function (c) {
  41119. // As usual stop the recursion if we meet a renderable group
  41120. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  41121. c._prepareRender(context);
  41122. }
  41123. });
  41124. }
  41125. // Finally reset the dirty flags as we've processed everything
  41126. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  41127. this._instanceDirtyFlags = 0;
  41128. };
  41129. Prim2DBase.prototype._canvasPreInit = function (settings) {
  41130. };
  41131. Prim2DBase.CheckParent = function (parent) {
  41132. //if (!Prim2DBase._isCanvasInit && !parent) {
  41133. // 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)");
  41134. //}
  41135. };
  41136. Prim2DBase.prototype.updateCachedStatesOf = function (list, recurse) {
  41137. for (var _i = 0; _i < list.length; _i++) {
  41138. var cur = list[_i];
  41139. cur.updateCachedStates(recurse);
  41140. }
  41141. };
  41142. Prim2DBase.prototype._parentLayoutDirty = function () {
  41143. if (!this._parent || this._parent.isDisposed) {
  41144. return;
  41145. }
  41146. this._parent._setLayoutDirty();
  41147. };
  41148. Prim2DBase.prototype._setLayoutDirty = function () {
  41149. this.onPrimBecomesDirty();
  41150. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  41151. };
  41152. Prim2DBase.prototype._checkPositionChange = function () {
  41153. if (this.parent && this.parent.layoutEngine.isChildPositionAllowed === false) {
  41154. console.log("Can't manually set the position of " + this.id + ", the Layout Engine of its parent doesn't allow it");
  41155. return false;
  41156. }
  41157. return true;
  41158. };
  41159. Prim2DBase.prototype._positioningDirty = function () {
  41160. this.onPrimBecomesDirty();
  41161. this._setFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41162. };
  41163. Prim2DBase.prototype._spreadActualOpacityChanged = function () {
  41164. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41165. var child = _a[_i];
  41166. child._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  41167. child._spreadActualOpacityChanged();
  41168. }
  41169. };
  41170. Prim2DBase.prototype._changeLayoutEngine = function (engine) {
  41171. this._layoutEngine = engine;
  41172. };
  41173. Prim2DBase.prototype._updateLocalTransform = function () {
  41174. var tflags = Prim2DBase.actualPositionProperty.flagId | Prim2DBase.rotationProperty.flagId | Prim2DBase.scaleProperty.flagId | Prim2DBase.scaleXProperty.flagId | Prim2DBase.scaleYProperty.flagId | Prim2DBase.originProperty.flagId;
  41175. if (this.checkPropertiesDirty(tflags)) {
  41176. if (this.owner) {
  41177. this.owner.addupdateLocalTransformCounter(1);
  41178. }
  41179. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  41180. var local;
  41181. var pos = this.position;
  41182. if (this._origin.x === 0 && this._origin.y === 0) {
  41183. local = BABYLON.Matrix.Compose(new BABYLON.Vector3(this._scale.x, this._scale.y, 1), rot, new BABYLON.Vector3(pos.x, pos.y, 0));
  41184. this._localTransform = local;
  41185. }
  41186. else {
  41187. // -Origin offset
  41188. var as = this.actualSize;
  41189. BABYLON.Matrix.TranslationToRef((-as.width * this._origin.x), (-as.height * this._origin.y), 0, Prim2DBase._t0);
  41190. // -Origin * rotation
  41191. rot.toRotationMatrix(Prim2DBase._t1);
  41192. Prim2DBase._t0.multiplyToRef(Prim2DBase._t1, Prim2DBase._t2);
  41193. // -Origin * rotation * scale
  41194. BABYLON.Matrix.ScalingToRef(this._scale.x, this._scale.y, 1, Prim2DBase._t0);
  41195. Prim2DBase._t2.multiplyToRef(Prim2DBase._t0, Prim2DBase._t1);
  41196. // -Origin * rotation * scale * (Origin + Position)
  41197. BABYLON.Matrix.TranslationToRef((as.width * this._origin.x) + pos.x, (as.height * this._origin.y) + pos.y, 0, Prim2DBase._t2);
  41198. Prim2DBase._t1.multiplyToRef(Prim2DBase._t2, this._localTransform);
  41199. }
  41200. this.clearPropertiesDirty(tflags);
  41201. return true;
  41202. }
  41203. return false;
  41204. };
  41205. Prim2DBase.prototype.updateCachedStates = function (recurse) {
  41206. if (this.isDisposed) {
  41207. return;
  41208. }
  41209. this.owner.addCachedGroupRenderCounter(1);
  41210. // Check if the parent is synced
  41211. if (this._parent && ((this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || this._parent._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLayoutDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty | BABYLON.SmartPropertyPrim.flagZOrderDirty))) {
  41212. this._parent.updateCachedStates(false);
  41213. }
  41214. // Update Z-Order if needed
  41215. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  41216. this._updateZOrder();
  41217. }
  41218. // Update actualSize only if there' not positioning to recompute and the size changed
  41219. // Otherwise positioning will take care of it.
  41220. var sizeDirty = this.checkPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  41221. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty) && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) && sizeDirty) {
  41222. var size = this.size;
  41223. if (size) {
  41224. if (this.size.width != null) {
  41225. this.actualSize.width = this.size.width;
  41226. }
  41227. if (this.size.height != null) {
  41228. this.actualSize.height = this.size.height;
  41229. }
  41230. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  41231. }
  41232. }
  41233. // Check for layout update
  41234. var positioningDirty = this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41235. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  41236. this.owner.addUpdateLayoutCounter(1);
  41237. this._layoutEngine.updateLayout(this);
  41238. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  41239. }
  41240. var positioningComputed = positioningDirty && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41241. var autoContentChanged = false;
  41242. if (this.isSizeAuto) {
  41243. if (!this._lastAutoSizeArea) {
  41244. autoContentChanged = this.size !== null;
  41245. }
  41246. else {
  41247. autoContentChanged = (!this._lastAutoSizeArea.equals(this.size));
  41248. }
  41249. }
  41250. // Check for positioning update
  41251. if (!positioningComputed && (autoContentChanged || sizeDirty || this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) || (this._parent && !this._parent.contentArea.equals(this._parentContentArea)))) {
  41252. this._updatePositioning();
  41253. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41254. if (sizeDirty) {
  41255. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  41256. }
  41257. positioningComputed = true;
  41258. }
  41259. if (positioningComputed && this._parent) {
  41260. this._parentContentArea.copyFrom(this._parent.contentArea);
  41261. }
  41262. // Check if we must update this prim
  41263. if (this === this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  41264. this.owner.addUpdateGlobalTransformCounter(1);
  41265. var curVisibleState = this.isVisible;
  41266. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  41267. // Detect a change of visibility
  41268. this._changeFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged, curVisibleState !== this.isVisible);
  41269. // Get/compute the localTransform
  41270. var localDirty = this._updateLocalTransform();
  41271. var parentPaddingChanged = false;
  41272. var parentPaddingOffset = Prim2DBase._v0;
  41273. if (this._parent) {
  41274. parentPaddingOffset = this._parent._paddingOffset;
  41275. parentPaddingChanged = !parentPaddingOffset.equals(this._parentPaddingOffset);
  41276. }
  41277. // Check if there are changes in the parent that will force us to update the global matrix
  41278. var parentDirty = (this._parent != null) ? (this._parent._globalTransformStep !== this._parentTransformStep) : false;
  41279. // Check if we have to update the globalTransform
  41280. if (!this._globalTransform || localDirty || parentDirty || parentPaddingChanged) {
  41281. var globalTransform = this._parent ? this._parent._globalTransform : null;
  41282. var localTransform;
  41283. Prim2DBase._transMtx.copyFrom(this._localTransform);
  41284. Prim2DBase._transMtx.m[12] += this._layoutAreaPos.x + this._marginOffset.x + parentPaddingOffset.x;
  41285. Prim2DBase._transMtx.m[13] += this._layoutAreaPos.y + this._marginOffset.y + parentPaddingOffset.y;
  41286. localTransform = Prim2DBase._transMtx;
  41287. this._globalTransform = this._parent ? localTransform.multiply(globalTransform) : localTransform.clone();
  41288. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  41289. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  41290. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  41291. }
  41292. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  41293. }
  41294. if (recurse) {
  41295. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41296. var child = _a[_i];
  41297. // Stop the recursion if we meet a renderable group
  41298. child.updateCachedStates(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  41299. }
  41300. }
  41301. };
  41302. Prim2DBase.prototype._updatePositioning = function () {
  41303. if (this.owner) {
  41304. this.owner.addUpdatePositioningCounter(1);
  41305. }
  41306. // From this point we assume that the primitive layoutArea is computed and up to date.
  41307. // We know have to :
  41308. // 1. Determine the PaddingArea and the ActualPosition based on the margin/marginAlignment properties, which will also set the size property of the primitive
  41309. // 2. Determine the contentArea based on the padding property.
  41310. // 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
  41311. if (!this._hasMargin && (this.actualSize.width == null || this.actualSize.height == null)) {
  41312. if (this.actualSize.width == null) {
  41313. this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  41314. }
  41315. if (this.actualSize.height == null) {
  41316. this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  41317. }
  41318. }
  41319. // Apply margin
  41320. if (this._hasMargin) {
  41321. this.margin.computeWithAlignment(this.layoutArea, this.size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  41322. this.actualSize = Prim2DBase._size.clone();
  41323. }
  41324. var isSizeAuto = this.isSizeAuto;
  41325. if (this._hasPadding) {
  41326. // Two cases from here: the size of the Primitive is Auto, its content can't be shrink, so me resize the primitive itself
  41327. if (isSizeAuto) {
  41328. var content = this.size.clone();
  41329. this._getActualSizeFromContentToRef(content, Prim2DBase._icArea);
  41330. this.padding.enlarge(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  41331. this._contentArea.copyFrom(content);
  41332. this.actualSize = Prim2DBase._size.clone();
  41333. // Changing the padding has resize the prim, which forces us to recompute margin again
  41334. if (this._hasMargin) {
  41335. this.margin.computeWithAlignment(this.layoutArea, Prim2DBase._size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  41336. }
  41337. }
  41338. else {
  41339. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  41340. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  41341. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  41342. this.padding.compute(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  41343. this._paddingOffset.x += Prim2DBase._icPos.x;
  41344. this._paddingOffset.y += Prim2DBase._icPos.y;
  41345. this._contentArea.copyFrom(Prim2DBase._size);
  41346. }
  41347. }
  41348. else {
  41349. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  41350. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  41351. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  41352. this._paddingOffset.copyFrom(Prim2DBase._icPos);
  41353. this._contentArea.copyFrom(Prim2DBase._icArea);
  41354. }
  41355. if (!this._position) {
  41356. var aPos = new BABYLON.Vector2(this._layoutAreaPos.x + this._marginOffset.x, this._layoutAreaPos.y + this._marginOffset.y);
  41357. this.actualPosition = aPos;
  41358. }
  41359. if (isSizeAuto) {
  41360. this._lastAutoSizeArea = this.size;
  41361. }
  41362. };
  41363. Object.defineProperty(Prim2DBase.prototype, "contentArea", {
  41364. /**
  41365. * Get the content are of this primitive, this area is computed using the padding property and also possibly the primitive type itself.
  41366. * Children of this primitive will be positioned relative to the bottom/left corner of this area.
  41367. */
  41368. get: function () {
  41369. // Check for positioning update
  41370. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  41371. this._updatePositioning();
  41372. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41373. }
  41374. return this._contentArea;
  41375. },
  41376. enumerable: true,
  41377. configurable: true
  41378. });
  41379. Prim2DBase.prototype._patchHierarchy = function (owner) {
  41380. this._owner = owner;
  41381. // The only place we initialize the _renderGroup is this method, if it's set, we already been there, no need to execute more
  41382. if (this._renderGroup != null) {
  41383. return;
  41384. }
  41385. if (this instanceof BABYLON.Group2D) {
  41386. var group = this;
  41387. group.detectGroupStates();
  41388. if (group._trackedNode && !group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  41389. group.owner._registerTrackedNode(this);
  41390. }
  41391. }
  41392. this._renderGroup = this.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  41393. if (this._parent) {
  41394. this._parentLayoutDirty();
  41395. }
  41396. // Make sure the prim is in the dirtyList if it should be
  41397. if (this._renderGroup && this.isDirty) {
  41398. var list = this._renderGroup._renderableData._primDirtyList;
  41399. var i = list.indexOf(this);
  41400. if (i === -1) {
  41401. list.push(this);
  41402. }
  41403. }
  41404. // Recurse
  41405. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41406. var child = _a[_i];
  41407. child._hierarchyDepth = this._hierarchyDepth + 1;
  41408. child._patchHierarchy(owner);
  41409. }
  41410. };
  41411. Prim2DBase.prototype._updateZOrder = function () {
  41412. var prevLinPos = this._primLinearPosition;
  41413. var startI = 0;
  41414. var startZ = this._zOrder;
  41415. // 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
  41416. var childrenCount = this._children.length;
  41417. if (this._firstZDirtyIndex > 0) {
  41418. if ((this._firstZDirtyIndex - 1) < childrenCount) {
  41419. var prevPrim = this._children[this._firstZDirtyIndex - 1];
  41420. prevLinPos = prevPrim._primLinearPosition;
  41421. startI = this._firstZDirtyIndex - 1;
  41422. startZ = prevPrim._zOrder;
  41423. }
  41424. }
  41425. var startPos = prevLinPos;
  41426. // Update the linear position of the primitive from the first one to the last inside this primitive, compute the total number of prim traversed
  41427. Prim2DBase._totalCount = 0;
  41428. for (var i = startI; i < childrenCount; i++) {
  41429. var child = this._children[i];
  41430. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  41431. }
  41432. // Compute the new Z-Order for all the primitives
  41433. // Add 20% to the current total count to reserve space for future insertions, except if we're rebuilding due to a zMinDelta reached
  41434. var zDelta = (this._zMax - startZ) / (Prim2DBase._totalCount * (Prim2DBase._zRebuildReentrency ? 1 : 1.2));
  41435. // 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.
  41436. if (zDelta < BABYLON.Canvas2D._zMinDelta) {
  41437. // 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...
  41438. if (Prim2DBase._zRebuildReentrency) {
  41439. var p = this._parent;
  41440. if (p == null) {
  41441. // 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...)
  41442. console.log("Can't compute Z-Order for " + this.id + "'s children, zDelta is too small, Z-Order is now in an unstable state");
  41443. Prim2DBase._zRebuildReentrency = false;
  41444. return;
  41445. }
  41446. p._firstZDirtyIndex = 0;
  41447. return p._updateZOrder();
  41448. }
  41449. Prim2DBase._zRebuildReentrency = true;
  41450. this._firstZDirtyIndex = 0;
  41451. this._updateZOrder();
  41452. Prim2DBase._zRebuildReentrency = false;
  41453. }
  41454. for (var i = startI; i < childrenCount; i++) {
  41455. var child = this._children[i];
  41456. child._updatePrimitiveZOrder(startPos, startZ, zDelta);
  41457. }
  41458. // Notify the Observers that we found during the Z change (we do it after to avoid any kind of re-entrance)
  41459. for (var _i = 0, _a = Prim2DBase._zOrderChangedNotifList; _i < _a.length; _i++) {
  41460. var p = _a[_i];
  41461. p._actualZOrderChangedObservable.notifyObservers(p.actualZOffset);
  41462. }
  41463. Prim2DBase._zOrderChangedNotifList.splice(0);
  41464. this._firstZDirtyIndex = Prim2DBase._bigInt;
  41465. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41466. };
  41467. Prim2DBase.prototype._updatePrimitiveLinearPosition = function (prevLinPos) {
  41468. if (this.isManualZOrder) {
  41469. return prevLinPos;
  41470. }
  41471. this._primLinearPosition = ++prevLinPos;
  41472. Prim2DBase._totalCount++;
  41473. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  41474. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  41475. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41476. var child = _a[_i];
  41477. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  41478. }
  41479. }
  41480. return prevLinPos;
  41481. };
  41482. Prim2DBase.prototype._updatePrimitiveZOrder = function (startPos, startZ, deltaZ) {
  41483. if (this.isManualZOrder) {
  41484. return null;
  41485. }
  41486. var newZ = startZ + ((this._primLinearPosition - startPos) * deltaZ);
  41487. var isFlat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  41488. this._setZOrder(newZ, false);
  41489. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  41490. this._firstZDirtyIndex = Prim2DBase._bigInt;
  41491. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41492. }
  41493. var curZ = newZ;
  41494. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  41495. if (isFlat) {
  41496. if (this._children.length > 0) {
  41497. //let childrenZOrder = startZ + ((this._children[0]._primLinearPosition - startPos) * deltaZ);
  41498. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41499. var child = _a[_i];
  41500. child._updatePrimitiveFlatZOrder(this._zOrder);
  41501. }
  41502. }
  41503. }
  41504. else {
  41505. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  41506. var child = _c[_b];
  41507. var r = child._updatePrimitiveZOrder(startPos, startZ, deltaZ);
  41508. if (r != null) {
  41509. curZ = r;
  41510. }
  41511. }
  41512. }
  41513. this._zMax = isFlat ? newZ : (curZ + deltaZ);
  41514. return curZ;
  41515. };
  41516. Prim2DBase.prototype._updatePrimitiveFlatZOrder = function (newZ) {
  41517. if (this.isManualZOrder) {
  41518. return;
  41519. }
  41520. this._setZOrder(newZ, false);
  41521. this._zMax = newZ;
  41522. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  41523. this._firstZDirtyIndex = Prim2DBase._bigInt;
  41524. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41525. }
  41526. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41527. var child = _a[_i];
  41528. child._updatePrimitiveFlatZOrder(newZ);
  41529. }
  41530. };
  41531. Prim2DBase.prototype._setZOrder = function (newZ, directEmit) {
  41532. if (newZ !== this._zOrder) {
  41533. this._zOrder = newZ;
  41534. this.onPrimBecomesDirty();
  41535. this.onZOrderChanged();
  41536. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  41537. if (directEmit) {
  41538. this._actualZOrderChangedObservable.notifyObservers(newZ);
  41539. }
  41540. else {
  41541. Prim2DBase._zOrderChangedNotifList.push(this);
  41542. }
  41543. }
  41544. }
  41545. };
  41546. Prim2DBase.prototype._updateRenderMode = function () {
  41547. };
  41548. /**
  41549. * This method is used to alter the contentArea of the Primitive before margin is applied.
  41550. * 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.
  41551. * @param primSize the current size of the primitive
  41552. * @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!
  41553. * @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!
  41554. */
  41555. Prim2DBase.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  41556. initialContentArea.copyFrom(primSize);
  41557. initialContentPosition.x = initialContentPosition.y = 0;
  41558. };
  41559. /**
  41560. * This method is used to calculate the new size of the primitive based on the content which must stay the same
  41561. * Check the Rectangle2D implementation for a concrete application.
  41562. * @param primSize the current size of the primitive
  41563. * @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!
  41564. */
  41565. Prim2DBase.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  41566. newPrimSize.copyFrom(primSize);
  41567. };
  41568. Prim2DBase.PRIM2DBASE_PROPCOUNT = 16;
  41569. Prim2DBase._bigInt = Math.pow(2, 30);
  41570. Prim2DBase._nullPosition = BABYLON.Vector2.Zero();
  41571. Prim2DBase.boundinbBoxReentrency = false;
  41572. Prim2DBase.nullSize = BABYLON.Size.Zero();
  41573. Prim2DBase._bMax = BABYLON.Vector2.Zero();
  41574. Prim2DBase._isCanvasInit = false;
  41575. Prim2DBase._t0 = new BABYLON.Matrix();
  41576. Prim2DBase._t1 = new BABYLON.Matrix();
  41577. Prim2DBase._t2 = new BABYLON.Matrix();
  41578. Prim2DBase._v0 = BABYLON.Vector2.Zero(); // Must stay with the value 0,0
  41579. Prim2DBase._transMtx = BABYLON.Matrix.Zero();
  41580. Prim2DBase._icPos = BABYLON.Vector2.Zero();
  41581. Prim2DBase._icArea = BABYLON.Size.Zero();
  41582. Prim2DBase._size = BABYLON.Size.Zero();
  41583. Prim2DBase._zOrderChangedNotifList = new Array();
  41584. Prim2DBase._zRebuildReentrency = false;
  41585. Prim2DBase._totalCount = 0;
  41586. __decorate([
  41587. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase.actualPositionProperty = pi; }, false, false, true)
  41588. ], Prim2DBase.prototype, "actualPosition", null);
  41589. __decorate([
  41590. BABYLON.dynamicLevelProperty(2, function (pi) { return Prim2DBase.positionProperty = pi; }, false, false, true)
  41591. ], Prim2DBase.prototype, "position", null);
  41592. __decorate([
  41593. BABYLON.dynamicLevelProperty(3, function (pi) { return Prim2DBase.sizeProperty = pi; }, false, true)
  41594. ], Prim2DBase.prototype, "size", null);
  41595. __decorate([
  41596. BABYLON.instanceLevelProperty(4, function (pi) { return Prim2DBase.rotationProperty = pi; }, false, true)
  41597. ], Prim2DBase.prototype, "rotation", null);
  41598. __decorate([
  41599. BABYLON.instanceLevelProperty(5, function (pi) { return Prim2DBase.scaleProperty = pi; }, false, true)
  41600. ], Prim2DBase.prototype, "scale", null);
  41601. __decorate([
  41602. BABYLON.dynamicLevelProperty(6, function (pi) { return Prim2DBase.originProperty = pi; }, false, true)
  41603. ], Prim2DBase.prototype, "origin", null);
  41604. __decorate([
  41605. BABYLON.dynamicLevelProperty(7, function (pi) { return Prim2DBase.levelVisibleProperty = pi; })
  41606. ], Prim2DBase.prototype, "levelVisible", null);
  41607. __decorate([
  41608. BABYLON.instanceLevelProperty(8, function (pi) { return Prim2DBase.isVisibleProperty = pi; })
  41609. ], Prim2DBase.prototype, "isVisible", null);
  41610. __decorate([
  41611. BABYLON.instanceLevelProperty(9, function (pi) { return Prim2DBase.zOrderProperty = pi; })
  41612. ], Prim2DBase.prototype, "zOrder", null);
  41613. __decorate([
  41614. BABYLON.dynamicLevelProperty(10, function (pi) { return Prim2DBase.marginProperty = pi; })
  41615. ], Prim2DBase.prototype, "margin", null);
  41616. __decorate([
  41617. BABYLON.dynamicLevelProperty(11, function (pi) { return Prim2DBase.paddingProperty = pi; })
  41618. ], Prim2DBase.prototype, "padding", null);
  41619. __decorate([
  41620. BABYLON.dynamicLevelProperty(12, function (pi) { return Prim2DBase.marginAlignmentProperty = pi; })
  41621. ], Prim2DBase.prototype, "marginAlignment", null);
  41622. __decorate([
  41623. BABYLON.instanceLevelProperty(13, function (pi) { return Prim2DBase.opacityProperty = pi; })
  41624. ], Prim2DBase.prototype, "opacity", null);
  41625. __decorate([
  41626. BABYLON.instanceLevelProperty(14, function (pi) { return Prim2DBase.scaleXProperty = pi; }, false, true)
  41627. ], Prim2DBase.prototype, "scaleX", null);
  41628. __decorate([
  41629. BABYLON.instanceLevelProperty(15, function (pi) { return Prim2DBase.scaleYProperty = pi; }, false, true)
  41630. ], Prim2DBase.prototype, "scaleY", null);
  41631. Prim2DBase = __decorate([
  41632. BABYLON.className("Prim2DBase")
  41633. ], Prim2DBase);
  41634. return Prim2DBase;
  41635. })(BABYLON.SmartPropertyPrim);
  41636. BABYLON.Prim2DBase = Prim2DBase;
  41637. })(BABYLON || (BABYLON = {}));
  41638. var BABYLON;
  41639. (function (BABYLON) {
  41640. var GroupInstanceInfo = (function () {
  41641. function GroupInstanceInfo(owner, mrc, partCount) {
  41642. this._partCount = partCount;
  41643. this.owner = owner;
  41644. this.modelRenderCache = mrc;
  41645. this.modelRenderCache.addRef();
  41646. this.partIndexFromId = new BABYLON.StringDictionary();
  41647. this._usedShaderCategories = new Array(partCount);
  41648. this._strides = new Array(partCount);
  41649. this._opaqueData = null;
  41650. this._alphaTestData = null;
  41651. this._transparentData = null;
  41652. this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
  41653. }
  41654. GroupInstanceInfo.prototype.dispose = function () {
  41655. if (this._isDisposed) {
  41656. return false;
  41657. }
  41658. if (this.modelRenderCache) {
  41659. this.modelRenderCache.dispose();
  41660. }
  41661. var engine = this.owner.owner.engine;
  41662. if (this.opaqueData) {
  41663. this.opaqueData.forEach(function (d) { return d.dispose(engine); });
  41664. this.opaqueData = null;
  41665. }
  41666. this.partIndexFromId = null;
  41667. this._isDisposed = true;
  41668. return true;
  41669. };
  41670. Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
  41671. get: function () {
  41672. return this._opaqueData != null;
  41673. },
  41674. enumerable: true,
  41675. configurable: true
  41676. });
  41677. Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
  41678. get: function () {
  41679. return this._alphaTestData != null;
  41680. },
  41681. enumerable: true,
  41682. configurable: true
  41683. });
  41684. Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
  41685. get: function () {
  41686. return this._transparentData != null;
  41687. },
  41688. enumerable: true,
  41689. configurable: true
  41690. });
  41691. Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
  41692. get: function () {
  41693. if (!this._opaqueData) {
  41694. this._opaqueData = new Array(this._partCount);
  41695. for (var i = 0; i < this._partCount; i++) {
  41696. this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
  41697. }
  41698. }
  41699. return this._opaqueData;
  41700. },
  41701. enumerable: true,
  41702. configurable: true
  41703. });
  41704. Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
  41705. get: function () {
  41706. if (!this._alphaTestData) {
  41707. this._alphaTestData = new Array(this._partCount);
  41708. for (var i = 0; i < this._partCount; i++) {
  41709. this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
  41710. }
  41711. }
  41712. return this._alphaTestData;
  41713. },
  41714. enumerable: true,
  41715. configurable: true
  41716. });
  41717. Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
  41718. get: function () {
  41719. if (!this._transparentData) {
  41720. this._transparentData = new Array(this._partCount);
  41721. for (var i = 0; i < this._partCount; i++) {
  41722. var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
  41723. this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
  41724. }
  41725. }
  41726. return this._transparentData;
  41727. },
  41728. enumerable: true,
  41729. configurable: true
  41730. });
  41731. GroupInstanceInfo.prototype.sortTransparentData = function () {
  41732. if (!this.transparentOrderDirty) {
  41733. return;
  41734. }
  41735. for (var i = 0; i < this._transparentData.length; i++) {
  41736. var td = this._transparentData[i];
  41737. td._partData.sort();
  41738. }
  41739. this.transparentOrderDirty = false;
  41740. };
  41741. Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
  41742. get: function () {
  41743. return this._usedShaderCategories;
  41744. },
  41745. enumerable: true,
  41746. configurable: true
  41747. });
  41748. Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
  41749. get: function () {
  41750. return this._strides;
  41751. },
  41752. enumerable: true,
  41753. configurable: true
  41754. });
  41755. return GroupInstanceInfo;
  41756. })();
  41757. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  41758. var TransparentSegment = (function () {
  41759. function TransparentSegment() {
  41760. this.groupInsanceInfo = null;
  41761. this.startZ = 0;
  41762. this.endZ = 0;
  41763. this.startDataIndex = BABYLON.Prim2DBase._bigInt;
  41764. this.endDataIndex = 0;
  41765. this.partBuffers = null;
  41766. }
  41767. TransparentSegment.prototype.dispose = function (engine) {
  41768. if (this.partBuffers) {
  41769. this.partBuffers.forEach(function (b) { return engine._releaseBuffer(b); });
  41770. this.partBuffers.splice(0);
  41771. this.partBuffers = null;
  41772. }
  41773. };
  41774. return TransparentSegment;
  41775. })();
  41776. BABYLON.TransparentSegment = TransparentSegment;
  41777. var GroupInfoPartData = (function () {
  41778. function GroupInfoPartData(stride) {
  41779. this._partData = null;
  41780. this._partBuffer = null;
  41781. this._partBufferSize = 0;
  41782. this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
  41783. this._isDisposed = false;
  41784. }
  41785. GroupInfoPartData.prototype.dispose = function (engine) {
  41786. if (this._isDisposed) {
  41787. return false;
  41788. }
  41789. if (this._partBuffer) {
  41790. engine._releaseBuffer(this._partBuffer);
  41791. this._partBuffer = null;
  41792. }
  41793. this._partData = null;
  41794. this._isDisposed = true;
  41795. };
  41796. return GroupInfoPartData;
  41797. })();
  41798. BABYLON.GroupInfoPartData = GroupInfoPartData;
  41799. var TransparentGroupInfoPartData = (function (_super) {
  41800. __extends(TransparentGroupInfoPartData, _super);
  41801. function TransparentGroupInfoPartData(stride, zoff) {
  41802. _super.call(this, stride);
  41803. this._partData.compareValueOffset = zoff;
  41804. this._partData.sortingAscending = false;
  41805. }
  41806. return TransparentGroupInfoPartData;
  41807. })(GroupInfoPartData);
  41808. BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
  41809. var ModelRenderCache = (function () {
  41810. function ModelRenderCache(engine, modelKey) {
  41811. this._engine = engine;
  41812. this._modelKey = modelKey;
  41813. this._nextKey = 1;
  41814. this._refCounter = 1;
  41815. this._partData = null;
  41816. }
  41817. ModelRenderCache.prototype.dispose = function () {
  41818. if (--this._refCounter !== 0) {
  41819. return false;
  41820. }
  41821. // Remove the Model Render Cache from the global dictionary
  41822. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  41823. if (edata) {
  41824. edata.DisposeModelRenderCache(this);
  41825. }
  41826. return true;
  41827. };
  41828. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  41829. get: function () {
  41830. return this._refCounter <= 0;
  41831. },
  41832. enumerable: true,
  41833. configurable: true
  41834. });
  41835. ModelRenderCache.prototype.addRef = function () {
  41836. return ++this._refCounter;
  41837. };
  41838. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  41839. get: function () {
  41840. return this._modelKey;
  41841. },
  41842. enumerable: true,
  41843. configurable: true
  41844. });
  41845. /**
  41846. * Render the model instances
  41847. * @param instanceInfo
  41848. * @param context
  41849. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  41850. */
  41851. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  41852. return true;
  41853. };
  41854. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  41855. for (var i = 0; i < this._partData.length; i++) {
  41856. if (this._partData[i]._partId === partId) {
  41857. return i;
  41858. }
  41859. }
  41860. return null;
  41861. };
  41862. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  41863. var i = this.getPartIndexFromId(partId);
  41864. if (i === null) {
  41865. return null;
  41866. }
  41867. var ci = this._partsClassInfo[i];
  41868. var categories = this._partData[i]._partUsedCategories;
  41869. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  41870. return res;
  41871. };
  41872. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  41873. var pd = this._partData[partIndex];
  41874. var offset = (pd._partDataStride / 4) * elementCount;
  41875. var pci = this._partsClassInfo[partIndex];
  41876. var self = this;
  41877. pci.fullContent.forEach(function (k, v) {
  41878. if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
  41879. switch (v.dataType) {
  41880. case 4 /* float */:
  41881. {
  41882. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  41883. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  41884. break;
  41885. }
  41886. case 0 /* Vector2 */:
  41887. {
  41888. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  41889. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  41890. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  41891. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  41892. break;
  41893. }
  41894. case 5 /* Color3 */:
  41895. case 1 /* Vector3 */:
  41896. {
  41897. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  41898. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  41899. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  41900. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  41901. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  41902. break;
  41903. }
  41904. case 6 /* Color4 */:
  41905. case 2 /* Vector4 */:
  41906. {
  41907. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  41908. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  41909. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  41910. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  41911. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  41912. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  41913. break;
  41914. }
  41915. default:
  41916. }
  41917. }
  41918. });
  41919. };
  41920. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  41921. // let i = this.getPartIndexFromId(partId);
  41922. // if (i === null) {
  41923. // return null;
  41924. // }
  41925. // let pci = this._partsClassInfo[i];
  41926. // pci.fullContent.forEach((k, v) => {
  41927. // if (uniforms.indexOf(v.attributeName) !== -1) {
  41928. // v.uniformLocation = effect.getUniform(v.attributeName);
  41929. // }
  41930. // });
  41931. //}
  41932. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  41933. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  41934. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  41935. return ModelRenderCache;
  41936. })();
  41937. BABYLON.ModelRenderCache = ModelRenderCache;
  41938. var ModelRenderCachePartData = (function () {
  41939. function ModelRenderCachePartData() {
  41940. }
  41941. return ModelRenderCachePartData;
  41942. })();
  41943. BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
  41944. })(BABYLON || (BABYLON = {}));
  41945. var BABYLON;
  41946. (function (BABYLON) {
  41947. var InstanceClassInfo = (function () {
  41948. function InstanceClassInfo(base) {
  41949. this._baseInfo = base;
  41950. this._nextOffset = new BABYLON.StringDictionary();
  41951. this._attributes = new Array();
  41952. }
  41953. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  41954. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  41955. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  41956. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  41957. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  41958. if (push) {
  41959. this._attributes.push(propInfo);
  41960. }
  41961. };
  41962. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  41963. var catInline = ";" + categories.join(";") + ";";
  41964. var res = new Array();
  41965. var curInfo = this;
  41966. while (curInfo) {
  41967. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  41968. var attrib = _a[_i];
  41969. // 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
  41970. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  41971. var index = effect.getAttributeLocationByName(attrib.attributeName);
  41972. var iai = new BABYLON.InstancingAttributeInfo();
  41973. iai.index = index;
  41974. 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)
  41975. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  41976. iai.attributeName = attrib.attributeName;
  41977. res.push(iai);
  41978. }
  41979. }
  41980. curInfo = curInfo._baseInfo;
  41981. }
  41982. return res;
  41983. };
  41984. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  41985. var res = new Array();
  41986. var curInfo = this;
  41987. while (curInfo) {
  41988. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  41989. var attrib = _a[_i];
  41990. // 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
  41991. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  41992. res.push(attrib.attributeName);
  41993. }
  41994. }
  41995. curInfo = curInfo._baseInfo;
  41996. }
  41997. return res;
  41998. };
  41999. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  42000. var curOffset = 0;
  42001. var curBase = this._baseInfo;
  42002. while (curBase) {
  42003. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  42004. curBase = curBase._baseInfo;
  42005. }
  42006. return curOffset;
  42007. };
  42008. return InstanceClassInfo;
  42009. })();
  42010. BABYLON.InstanceClassInfo = InstanceClassInfo;
  42011. var InstancePropInfo = (function () {
  42012. function InstancePropInfo() {
  42013. this.instanceOffset = new BABYLON.StringDictionary();
  42014. }
  42015. InstancePropInfo.prototype.setSize = function (val) {
  42016. if (val instanceof BABYLON.Vector2) {
  42017. this.size = 8;
  42018. this.dataType = 0 /* Vector2 */;
  42019. return;
  42020. }
  42021. if (val instanceof BABYLON.Vector3) {
  42022. this.size = 12;
  42023. this.dataType = 1 /* Vector3 */;
  42024. return;
  42025. }
  42026. if (val instanceof BABYLON.Vector4) {
  42027. this.size = 16;
  42028. this.dataType = 2 /* Vector4 */;
  42029. return;
  42030. }
  42031. if (val instanceof BABYLON.Matrix) {
  42032. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  42033. }
  42034. if (typeof (val) === "number") {
  42035. this.size = 4;
  42036. this.dataType = 4 /* float */;
  42037. return;
  42038. }
  42039. if (val instanceof BABYLON.Color3) {
  42040. this.size = 12;
  42041. this.dataType = 5 /* Color3 */;
  42042. return;
  42043. }
  42044. if (val instanceof BABYLON.Color4) {
  42045. this.size = 16;
  42046. this.dataType = 6 /* Color4 */;
  42047. return;
  42048. }
  42049. if (val instanceof BABYLON.Size) {
  42050. this.size = 8;
  42051. this.dataType = 7 /* Size */;
  42052. return;
  42053. }
  42054. return;
  42055. };
  42056. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  42057. switch (this.dataType) {
  42058. case 0 /* Vector2 */:
  42059. {
  42060. var v = val;
  42061. array[offset + 0] = v.x;
  42062. array[offset + 1] = v.y;
  42063. break;
  42064. }
  42065. case 1 /* Vector3 */:
  42066. {
  42067. var v = val;
  42068. array[offset + 0] = v.x;
  42069. array[offset + 1] = v.y;
  42070. array[offset + 2] = v.z;
  42071. break;
  42072. }
  42073. case 2 /* Vector4 */:
  42074. {
  42075. var v = val;
  42076. array[offset + 0] = v.x;
  42077. array[offset + 1] = v.y;
  42078. array[offset + 2] = v.z;
  42079. array[offset + 3] = v.w;
  42080. break;
  42081. }
  42082. case 5 /* Color3 */:
  42083. {
  42084. var v = val;
  42085. array[offset + 0] = v.r;
  42086. array[offset + 1] = v.g;
  42087. array[offset + 2] = v.b;
  42088. break;
  42089. }
  42090. case 6 /* Color4 */:
  42091. {
  42092. var v = val;
  42093. array[offset + 0] = v.r;
  42094. array[offset + 1] = v.g;
  42095. array[offset + 2] = v.b;
  42096. array[offset + 3] = v.a;
  42097. break;
  42098. }
  42099. case 4 /* float */:
  42100. {
  42101. var v = val;
  42102. array[offset] = v;
  42103. break;
  42104. }
  42105. case 3 /* Matrix */:
  42106. {
  42107. var v = val;
  42108. for (var i = 0; i < 16; i++) {
  42109. array[offset + i] = v.m[i];
  42110. }
  42111. break;
  42112. }
  42113. case 7 /* Size */:
  42114. {
  42115. var s = val;
  42116. array[offset + 0] = s.width;
  42117. array[offset + 1] = s.height;
  42118. break;
  42119. }
  42120. }
  42121. };
  42122. return InstancePropInfo;
  42123. })();
  42124. BABYLON.InstancePropInfo = InstancePropInfo;
  42125. function instanceData(category, shaderAttributeName) {
  42126. return function (target, propName, descriptor) {
  42127. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  42128. var node = dic.getLevelOf(target);
  42129. var instanceDataName = propName;
  42130. shaderAttributeName = shaderAttributeName || instanceDataName;
  42131. var info = node.levelContent.get(instanceDataName);
  42132. if (info) {
  42133. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  42134. }
  42135. info = new InstancePropInfo();
  42136. info.attributeName = shaderAttributeName;
  42137. info.category = category || null;
  42138. if (info.category) {
  42139. info.delimitedCategory = ";" + info.category + ";";
  42140. }
  42141. node.levelContent.add(instanceDataName, info);
  42142. descriptor.get = function () {
  42143. return null;
  42144. };
  42145. descriptor.set = function (val) {
  42146. // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
  42147. // Quit if it's the case, otherwise we could overwrite data somewhere...
  42148. if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
  42149. return;
  42150. }
  42151. if (!info.size) {
  42152. info.setSize(val);
  42153. node.classContent.mapProperty(info, true);
  42154. }
  42155. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  42156. node.classContent.mapProperty(info, false);
  42157. }
  42158. var obj = this;
  42159. if (obj.dataBuffer && obj.dataElements) {
  42160. var offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  42161. info.writeData(obj.dataBuffer.buffer, offset, val);
  42162. }
  42163. };
  42164. };
  42165. }
  42166. BABYLON.instanceData = instanceData;
  42167. var InstanceDataBase = (function () {
  42168. function InstanceDataBase(partId, dataElementCount) {
  42169. this.id = partId;
  42170. this.curElement = 0;
  42171. this._dataElementCount = dataElementCount;
  42172. this.renderMode = 0;
  42173. this.arrayLengthChanged = false;
  42174. }
  42175. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  42176. get: function () {
  42177. return null;
  42178. },
  42179. enumerable: true,
  42180. configurable: true
  42181. });
  42182. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  42183. get: function () {
  42184. return null;
  42185. },
  42186. enumerable: true,
  42187. configurable: true
  42188. });
  42189. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  42190. get: function () {
  42191. return null;
  42192. },
  42193. enumerable: true,
  42194. configurable: true
  42195. });
  42196. Object.defineProperty(InstanceDataBase.prototype, "opacity", {
  42197. get: function () {
  42198. return null;
  42199. },
  42200. enumerable: true,
  42201. configurable: true
  42202. });
  42203. InstanceDataBase.prototype.getClassTreeInfo = function () {
  42204. if (!this.typeInfo) {
  42205. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  42206. }
  42207. return this.typeInfo;
  42208. };
  42209. InstanceDataBase.prototype.allocElements = function () {
  42210. if (!this.dataBuffer || this.dataElements) {
  42211. return;
  42212. }
  42213. var res = new Array(this.dataElementCount);
  42214. for (var i = 0; i < this.dataElementCount; i++) {
  42215. res[i] = this.dataBuffer.allocElement();
  42216. }
  42217. this.dataElements = res;
  42218. };
  42219. InstanceDataBase.prototype.freeElements = function () {
  42220. if (!this.dataElements) {
  42221. return;
  42222. }
  42223. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  42224. var ei = _a[_i];
  42225. this.dataBuffer.freeElement(ei);
  42226. }
  42227. this.dataElements = null;
  42228. };
  42229. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  42230. get: function () {
  42231. return this._dataElementCount;
  42232. },
  42233. set: function (value) {
  42234. if (value === this._dataElementCount) {
  42235. return;
  42236. }
  42237. this.arrayLengthChanged = true;
  42238. this.freeElements();
  42239. this._dataElementCount = value;
  42240. this.allocElements();
  42241. },
  42242. enumerable: true,
  42243. configurable: true
  42244. });
  42245. __decorate([
  42246. instanceData()
  42247. ], InstanceDataBase.prototype, "zBias", null);
  42248. __decorate([
  42249. instanceData()
  42250. ], InstanceDataBase.prototype, "transformX", null);
  42251. __decorate([
  42252. instanceData()
  42253. ], InstanceDataBase.prototype, "transformY", null);
  42254. __decorate([
  42255. instanceData()
  42256. ], InstanceDataBase.prototype, "opacity", null);
  42257. return InstanceDataBase;
  42258. })();
  42259. BABYLON.InstanceDataBase = InstanceDataBase;
  42260. var RenderablePrim2D = (function (_super) {
  42261. __extends(RenderablePrim2D, _super);
  42262. function RenderablePrim2D(settings) {
  42263. _super.call(this, settings);
  42264. this._isTransparent = false;
  42265. this._isAlphaTest = false;
  42266. this._transparentPrimitiveInfo = null;
  42267. }
  42268. Object.defineProperty(RenderablePrim2D.prototype, "isAlphaTest", {
  42269. get: function () {
  42270. return this._isAlphaTest;
  42271. },
  42272. set: function (value) {
  42273. if (this._isAlphaTest === value) {
  42274. return;
  42275. }
  42276. this._isAlphaTest = value;
  42277. this._updateRenderMode();
  42278. },
  42279. enumerable: true,
  42280. configurable: true
  42281. });
  42282. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  42283. get: function () {
  42284. return this._isTransparent || (this._opacity < 1);
  42285. },
  42286. set: function (value) {
  42287. if (this._isTransparent === value) {
  42288. return;
  42289. }
  42290. this._isTransparent = value;
  42291. this._updateRenderMode();
  42292. },
  42293. enumerable: true,
  42294. configurable: true
  42295. });
  42296. Object.defineProperty(RenderablePrim2D.prototype, "renderMode", {
  42297. get: function () {
  42298. return this._renderMode;
  42299. },
  42300. enumerable: true,
  42301. configurable: true
  42302. });
  42303. /**
  42304. * Dispose the primitive and its resources, remove it from its parent
  42305. */
  42306. RenderablePrim2D.prototype.dispose = function () {
  42307. if (!_super.prototype.dispose.call(this)) {
  42308. return false;
  42309. }
  42310. if (this.renderGroup) {
  42311. this.renderGroup._setCacheGroupDirty();
  42312. }
  42313. if (this._transparentPrimitiveInfo) {
  42314. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  42315. this._transparentPrimitiveInfo = null;
  42316. }
  42317. if (this._instanceDataParts) {
  42318. this._cleanupInstanceDataParts();
  42319. }
  42320. if (this._modelRenderCache) {
  42321. this._modelRenderCache.dispose();
  42322. this._modelRenderCache = null;
  42323. }
  42324. if (this._instanceDataParts) {
  42325. this._instanceDataParts.forEach(function (p) {
  42326. p.freeElements();
  42327. });
  42328. this._instanceDataParts = null;
  42329. }
  42330. return true;
  42331. };
  42332. RenderablePrim2D.prototype._cleanupInstanceDataParts = function () {
  42333. var gii = null;
  42334. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  42335. var part = _a[_i];
  42336. part.freeElements();
  42337. gii = part.groupInstanceInfo;
  42338. }
  42339. if (gii) {
  42340. var usedCount = 0;
  42341. if (gii.hasOpaqueData) {
  42342. var od = gii.opaqueData[0];
  42343. usedCount += od._partData.usedElementCount;
  42344. }
  42345. if (gii.hasAlphaTestData) {
  42346. var atd = gii.alphaTestData[0];
  42347. usedCount += atd._partData.usedElementCount;
  42348. }
  42349. if (gii.hasTransparentData) {
  42350. var td = gii.transparentData[0];
  42351. usedCount += td._partData.usedElementCount;
  42352. }
  42353. if (usedCount === 0) {
  42354. this.renderGroup._renderableData._renderGroupInstancesInfo.remove(gii.modelRenderCache.modelKey);
  42355. }
  42356. gii.modelRenderCache.dispose();
  42357. }
  42358. this._instanceDataParts = null;
  42359. };
  42360. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  42361. _super.prototype._prepareRenderPre.call(this, context);
  42362. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  42363. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty) && this._instanceDataParts) {
  42364. this._cleanupInstanceDataParts();
  42365. }
  42366. // Need to create the model?
  42367. var setupModelRenderCache = false;
  42368. if (!this._modelRenderCache || this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty)) {
  42369. setupModelRenderCache = this._createModelRenderCache();
  42370. }
  42371. var gii = null;
  42372. var newInstance = false;
  42373. // Need to create the instance data parts?
  42374. if (!this._instanceDataParts) {
  42375. // Yes, flag it for later, more processing will have to be done
  42376. newInstance = true;
  42377. gii = this._createModelDataParts();
  42378. }
  42379. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  42380. if (setupModelRenderCache) {
  42381. this.setupModelRenderCache(this._modelRenderCache);
  42382. }
  42383. // 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.
  42384. // 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.
  42385. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged) || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep)) {
  42386. this._updateInstanceDataParts(gii);
  42387. }
  42388. };
  42389. RenderablePrim2D.prototype._createModelRenderCache = function () {
  42390. var _this = this;
  42391. var setupModelRenderCache = false;
  42392. if (this._modelRenderCache) {
  42393. this._modelRenderCache.dispose();
  42394. }
  42395. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  42396. var mrc = _this.createModelRenderCache(key);
  42397. setupModelRenderCache = true;
  42398. return mrc;
  42399. });
  42400. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  42401. // if this is still false it means the MRC already exists, so we add a reference to it
  42402. if (!setupModelRenderCache) {
  42403. this._modelRenderCache.addRef();
  42404. }
  42405. return setupModelRenderCache;
  42406. };
  42407. RenderablePrim2D.prototype._createModelDataParts = function () {
  42408. var _this = this;
  42409. // Create the instance data parts of the primitive and store them
  42410. var parts = this.createInstanceDataParts();
  42411. this._instanceDataParts = parts;
  42412. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  42413. if (!this._modelRenderCache._partData) {
  42414. this._setupModelRenderCache(parts);
  42415. }
  42416. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  42417. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  42418. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  42419. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) {
  42420. var res = new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache, _this._modelRenderCache._partData.length);
  42421. for (var j = 0; j < _this._modelRenderCache._partData.length; j++) {
  42422. var part = _this._instanceDataParts[j];
  42423. res.partIndexFromId.add(part.id.toString(), j);
  42424. res.usedShaderCategories[j] = ";" + _this.getUsedShaderCategories(part).join(";") + ";";
  42425. res.strides[j] = _this._modelRenderCache._partData[j]._partDataStride;
  42426. }
  42427. return res;
  42428. });
  42429. // Get the GroupInfoDataPart corresponding to the render category of the part
  42430. var rm = 0;
  42431. var gipd = null;
  42432. if (this.isTransparent) {
  42433. gipd = gii.transparentData;
  42434. rm = BABYLON.Render2DContext.RenderModeTransparent;
  42435. }
  42436. else if (this.isAlphaTest) {
  42437. gipd = gii.alphaTestData;
  42438. rm = BABYLON.Render2DContext.RenderModeAlphaTest;
  42439. }
  42440. else {
  42441. gipd = gii.opaqueData;
  42442. rm = BABYLON.Render2DContext.RenderModeOpaque;
  42443. }
  42444. // For each instance data part of the primitive, allocate the instanced element it needs for render
  42445. for (var i = 0; i < parts.length; i++) {
  42446. var part = parts[i];
  42447. part.dataBuffer = gipd[i]._partData;
  42448. part.allocElements();
  42449. part.renderMode = rm;
  42450. part.groupInstanceInfo = gii;
  42451. }
  42452. return gii;
  42453. };
  42454. RenderablePrim2D.prototype._setupModelRenderCache = function (parts) {
  42455. var ctiArray = new Array();
  42456. this._modelRenderCache._partData = new Array();
  42457. for (var _i = 0; _i < parts.length; _i++) {
  42458. var dataPart = parts[_i];
  42459. var pd = new BABYLON.ModelRenderCachePartData();
  42460. this._modelRenderCache._partData.push(pd);
  42461. var cat = this.getUsedShaderCategories(dataPart);
  42462. var cti = dataPart.getClassTreeInfo();
  42463. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  42464. var curVisible = this.isVisible;
  42465. this.isVisible = true;
  42466. // 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.
  42467. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  42468. var joinCat = ";" + cat.join(";") + ";";
  42469. pd._partJoinedUsedCategories = joinCat;
  42470. InstanceClassInfo._CurCategories = joinCat;
  42471. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  42472. if (!this.refreshInstanceDataPart(dataPart)) {
  42473. console.log("Layout construction for " + BABYLON.Tools.getClassName(this._instanceDataParts[0]) + " failed because refresh returned false");
  42474. }
  42475. this.afterRefreshForLayoutConstruction(dataPart, obj);
  42476. this.isVisible = curVisible;
  42477. var size = 0;
  42478. cti.fullContent.forEach(function (k, v) {
  42479. if (!v.category || cat.indexOf(v.category) !== -1) {
  42480. if (v.attributeName === "zBias") {
  42481. pd._zBiasOffset = v.instanceOffset.get(joinCat);
  42482. }
  42483. if (!v.size) {
  42484. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  42485. }
  42486. else {
  42487. size += v.size;
  42488. }
  42489. }
  42490. });
  42491. pd._partDataStride = size;
  42492. pd._partUsedCategories = cat;
  42493. pd._partId = dataPart.id;
  42494. ctiArray.push(cti);
  42495. }
  42496. this._modelRenderCache._partsClassInfo = ctiArray;
  42497. };
  42498. RenderablePrim2D.prototype.onZOrderChanged = function () {
  42499. if (this.isTransparent && this._transparentPrimitiveInfo) {
  42500. this.renderGroup._renderableData.transparentPrimitiveZChanged(this._transparentPrimitiveInfo);
  42501. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  42502. // Flag the transparentData dirty has will have to sort it again
  42503. gii.transparentOrderDirty = true;
  42504. }
  42505. };
  42506. RenderablePrim2D.prototype._updateInstanceDataParts = function (gii) {
  42507. // Fetch the GroupInstanceInfo if we don't already have it
  42508. var rd = this.renderGroup._renderableData;
  42509. if (!gii) {
  42510. gii = rd._renderGroupInstancesInfo.get(this.modelKey);
  42511. }
  42512. var isTransparent = this.isTransparent;
  42513. var isAlphaTest = this.isAlphaTest;
  42514. var wereTransparent = false;
  42515. // Check a render mode change
  42516. var rmChanged = false;
  42517. if (this._instanceDataParts.length > 0) {
  42518. var firstPart = this._instanceDataParts[0];
  42519. var partRM = firstPart.renderMode;
  42520. var curRM = this.renderMode;
  42521. if (partRM !== curRM) {
  42522. wereTransparent = partRM === BABYLON.Render2DContext.RenderModeTransparent;
  42523. rmChanged = true;
  42524. var gipd;
  42525. switch (curRM) {
  42526. case BABYLON.Render2DContext.RenderModeTransparent:
  42527. gipd = gii.transparentData;
  42528. break;
  42529. case BABYLON.Render2DContext.RenderModeAlphaTest:
  42530. gipd = gii.alphaTestData;
  42531. break;
  42532. default:
  42533. gipd = gii.opaqueData;
  42534. }
  42535. for (var i = 0; i < this._instanceDataParts.length; i++) {
  42536. var part = this._instanceDataParts[i];
  42537. part.freeElements();
  42538. part.dataBuffer = gipd[i]._partData;
  42539. part.renderMode = curRM;
  42540. }
  42541. }
  42542. }
  42543. // Handle changes related to ZOffset
  42544. var visChanged = this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged);
  42545. if (isTransparent || wereTransparent) {
  42546. // Handle visibility change, which is also triggered when the primitive just got created
  42547. if (visChanged || rmChanged) {
  42548. if (this.isVisible && !wereTransparent) {
  42549. if (!this._transparentPrimitiveInfo) {
  42550. // Add the primitive to the list of transparent ones in the group that render is
  42551. this._transparentPrimitiveInfo = rd.addNewTransparentPrimitiveInfo(this, gii);
  42552. }
  42553. }
  42554. else {
  42555. if (this._transparentPrimitiveInfo) {
  42556. rd.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  42557. this._transparentPrimitiveInfo = null;
  42558. }
  42559. }
  42560. gii.transparentOrderDirty = true;
  42561. }
  42562. }
  42563. var rebuildTrans = false;
  42564. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  42565. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  42566. var part = _a[_i];
  42567. var justAllocated = false;
  42568. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  42569. if (!part.dataElements && (visChanged || rmChanged || this.isVisible)) {
  42570. part.allocElements();
  42571. justAllocated = true;
  42572. }
  42573. InstanceClassInfo._CurCategories = gii.usedShaderCategories[gii.partIndexFromId.get(part.id.toString())];
  42574. // Will return false if the instance should not be rendered (not visible or other any reasons)
  42575. part.arrayLengthChanged = false;
  42576. if (!this.refreshInstanceDataPart(part)) {
  42577. // Free the data element
  42578. if (part.dataElements) {
  42579. part.freeElements();
  42580. }
  42581. }
  42582. rebuildTrans = rebuildTrans || part.arrayLengthChanged || justAllocated;
  42583. }
  42584. this._instanceDirtyFlags = 0;
  42585. // Make the appropriate data dirty
  42586. if (isTransparent) {
  42587. gii.transparentDirty = true;
  42588. if (rebuildTrans) {
  42589. rd._transparentListChanged = true;
  42590. }
  42591. }
  42592. else if (isAlphaTest) {
  42593. gii.alphaTestDirty = true;
  42594. }
  42595. else {
  42596. gii.opaqueDirty = true;
  42597. }
  42598. this._clearFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged); // Reset the flag as we've handled the case
  42599. };
  42600. RenderablePrim2D.prototype._updateTransparentSegmentIndices = function (ts) {
  42601. var minOff = BABYLON.Prim2DBase._bigInt;
  42602. var maxOff = 0;
  42603. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  42604. var part = _a[_i];
  42605. if (part && part.dataElements) {
  42606. part.dataBuffer.pack();
  42607. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  42608. var el = _c[_b];
  42609. minOff = Math.min(minOff, el.offset);
  42610. maxOff = Math.max(maxOff, el.offset);
  42611. }
  42612. ts.startDataIndex = Math.min(ts.startDataIndex, minOff / part.dataBuffer.stride);
  42613. ts.endDataIndex = Math.max(ts.endDataIndex, (maxOff / part.dataBuffer.stride) + 1); // +1 for exclusive
  42614. }
  42615. }
  42616. };
  42617. // This internal method is mainly used for transparency processing
  42618. RenderablePrim2D.prototype._getNextPrimZOrder = function () {
  42619. var length = this._instanceDataParts.length;
  42620. for (var i = 0; i < length; i++) {
  42621. var part = this._instanceDataParts[i];
  42622. if (part) {
  42623. var stride = part.dataBuffer.stride;
  42624. var lastElementOffset = part.dataElements[part.dataElements.length - 1].offset;
  42625. // check if it's the last in the DFA
  42626. if (part.dataBuffer.totalElementCount * stride <= lastElementOffset) {
  42627. return null;
  42628. }
  42629. // Return the Z of the next primitive that lies in the DFA
  42630. return part.dataBuffer[lastElementOffset + stride + this.modelRenderCache._partData[i]._zBiasOffset];
  42631. }
  42632. }
  42633. return null;
  42634. };
  42635. // This internal method is mainly used for transparency processing
  42636. RenderablePrim2D.prototype._getPrevPrimZOrder = function () {
  42637. var length = this._instanceDataParts.length;
  42638. for (var i = 0; i < length; i++) {
  42639. var part = this._instanceDataParts[i];
  42640. if (part) {
  42641. var stride = part.dataBuffer.stride;
  42642. var firstElementOffset = part.dataElements[0].offset;
  42643. // check if it's the first in the DFA
  42644. if (firstElementOffset === 0) {
  42645. return null;
  42646. }
  42647. // Return the Z of the previous primitive that lies in the DFA
  42648. return part.dataBuffer[firstElementOffset - stride + this.modelRenderCache._partData[i]._zBiasOffset];
  42649. }
  42650. }
  42651. return null;
  42652. };
  42653. /**
  42654. * Transform a given point using the Primitive's origin setting.
  42655. * This method requires the Primitive's actualSize to be accurate
  42656. * @param p the point to transform
  42657. * @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.
  42658. * @param res an allocated Vector2 that will receive the transformed content
  42659. */
  42660. RenderablePrim2D.prototype.transformPointWithOriginByRef = function (p, originOffset, res) {
  42661. var actualSize = this.actualSize;
  42662. res.x = p.x - ((this.origin.x + (originOffset ? originOffset.x : 0)) * actualSize.width);
  42663. res.y = p.y - ((this.origin.y + (originOffset ? originOffset.y : 0)) * actualSize.height);
  42664. };
  42665. RenderablePrim2D.prototype.transformPointWithOriginToRef = function (p, originOffset, res) {
  42666. this.transformPointWithOriginByRef(p, originOffset, res);
  42667. return res;
  42668. };
  42669. /**
  42670. * Get the info for a given effect based on the dataPart metadata
  42671. * @param dataPartId partId in part list to get the info
  42672. * @param vertexBufferAttributes vertex buffer attributes to manually add
  42673. * @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
  42674. */
  42675. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes, useInstanced) {
  42676. if (useInstanced === void 0) { useInstanced = null; }
  42677. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  42678. if (!dataPart) {
  42679. return null;
  42680. }
  42681. var instancedArray = this.owner.supportInstancedArray;
  42682. if (useInstanced != null) {
  42683. // Check if the caller ask for Instanced Array and the engine does not support it, return null if it's the case
  42684. if (useInstanced && instancedArray === false) {
  42685. return null;
  42686. }
  42687. // Use the caller's setting
  42688. instancedArray = useInstanced;
  42689. }
  42690. var cti = dataPart.getClassTreeInfo();
  42691. var categories = this.getUsedShaderCategories(dataPart);
  42692. var att = cti.classContent.getShaderAttributes(categories);
  42693. var defines = "";
  42694. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  42695. if (instancedArray) {
  42696. defines += "#define Instanced\n";
  42697. }
  42698. return { attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes, uniforms: instancedArray ? [] : att, defines: defines };
  42699. };
  42700. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  42701. get: function () {
  42702. return this._modelRenderCache;
  42703. },
  42704. enumerable: true,
  42705. configurable: true
  42706. });
  42707. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey) {
  42708. return null;
  42709. };
  42710. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  42711. };
  42712. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  42713. return null;
  42714. };
  42715. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  42716. return [];
  42717. };
  42718. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  42719. };
  42720. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  42721. };
  42722. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  42723. if (!this.isVisible) {
  42724. return false;
  42725. }
  42726. part.isVisible = this.isVisible;
  42727. // 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)
  42728. if (part.dataElementCount === 1) {
  42729. part.curElement = 0;
  42730. this.updateInstanceDataPart(part);
  42731. }
  42732. return true;
  42733. };
  42734. /**
  42735. * Update the instanceDataBase level properties of a part
  42736. * @param part the part to update
  42737. * @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).
  42738. */
  42739. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset) {
  42740. if (positionOffset === void 0) { positionOffset = null; }
  42741. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform);
  42742. var size = this.renderGroup.viewportSize;
  42743. var zBias = this.actualZOffset;
  42744. var offX = 0;
  42745. var offY = 0;
  42746. // If there's an offset, apply the global transformation matrix on it to get a global offset
  42747. if (positionOffset) {
  42748. offX = positionOffset.x * t.m[0] + positionOffset.y * t.m[4];
  42749. offY = positionOffset.x * t.m[1] + positionOffset.y * t.m[5];
  42750. }
  42751. // 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
  42752. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  42753. // So for X:
  42754. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  42755. // - 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].
  42756. var w = size.width;
  42757. var h = size.height;
  42758. var invZBias = 1 / zBias;
  42759. var tx = new BABYLON.Vector4(t.m[0] * 2 / w, t.m[4] * 2 / w, 0 /*t.m[8]*/, ((t.m[12] + offX) * 2 / w) - 1);
  42760. var ty = new BABYLON.Vector4(t.m[1] * 2 / h, t.m[5] * 2 / h, 0 /*t.m[9]*/, ((t.m[13] + offY) * 2 / h) - 1);
  42761. part.transformX = tx;
  42762. part.transformY = ty;
  42763. part.opacity = this.actualOpacity;
  42764. // 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)
  42765. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  42766. };
  42767. RenderablePrim2D.prototype._updateRenderMode = function () {
  42768. if (this.isTransparent) {
  42769. this._renderMode = BABYLON.Render2DContext.RenderModeTransparent;
  42770. }
  42771. else if (this.isAlphaTest) {
  42772. this._renderMode = BABYLON.Render2DContext.RenderModeAlphaTest;
  42773. }
  42774. else {
  42775. this._renderMode = BABYLON.Render2DContext.RenderModeOpaque;
  42776. }
  42777. };
  42778. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  42779. __decorate([
  42780. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 0, function (pi) { return RenderablePrim2D.isAlphaTestProperty = pi; })
  42781. ], RenderablePrim2D.prototype, "isAlphaTest", null);
  42782. __decorate([
  42783. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D.isTransparentProperty = pi; })
  42784. ], RenderablePrim2D.prototype, "isTransparent", null);
  42785. RenderablePrim2D = __decorate([
  42786. BABYLON.className("RenderablePrim2D")
  42787. ], RenderablePrim2D);
  42788. return RenderablePrim2D;
  42789. })(BABYLON.Prim2DBase);
  42790. BABYLON.RenderablePrim2D = RenderablePrim2D;
  42791. })(BABYLON || (BABYLON = {}));
  42792. var BABYLON;
  42793. (function (BABYLON) {
  42794. var Shape2D = (function (_super) {
  42795. __extends(Shape2D, _super);
  42796. function Shape2D(settings) {
  42797. _super.call(this, settings);
  42798. if (!settings) {
  42799. settings = {};
  42800. }
  42801. var borderBrush = null;
  42802. if (settings.border) {
  42803. if (typeof (settings.border) === "string") {
  42804. borderBrush = BABYLON.Canvas2D.GetBrushFromString(settings.border);
  42805. }
  42806. else {
  42807. borderBrush = settings.border;
  42808. }
  42809. }
  42810. var fillBrush = null;
  42811. if (settings.fill) {
  42812. if (typeof (settings.fill) === "string") {
  42813. fillBrush = BABYLON.Canvas2D.GetBrushFromString(settings.fill);
  42814. }
  42815. else {
  42816. fillBrush = settings.fill;
  42817. }
  42818. }
  42819. this.border = borderBrush;
  42820. this.fill = fillBrush;
  42821. this.borderThickness = settings.borderThickness;
  42822. }
  42823. Object.defineProperty(Shape2D.prototype, "border", {
  42824. get: function () {
  42825. return this._border;
  42826. },
  42827. set: function (value) {
  42828. this._border = value;
  42829. this._updateTransparencyStatus();
  42830. },
  42831. enumerable: true,
  42832. configurable: true
  42833. });
  42834. Object.defineProperty(Shape2D.prototype, "fill", {
  42835. /**
  42836. * Get/set the brush to render the Fill part of the Primitive
  42837. */
  42838. get: function () {
  42839. return this._fill;
  42840. },
  42841. set: function (value) {
  42842. this._fill = value;
  42843. this._updateTransparencyStatus();
  42844. },
  42845. enumerable: true,
  42846. configurable: true
  42847. });
  42848. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  42849. get: function () {
  42850. return this._borderThickness;
  42851. },
  42852. set: function (value) {
  42853. this._borderThickness = value;
  42854. },
  42855. enumerable: true,
  42856. configurable: true
  42857. });
  42858. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  42859. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  42860. // Fill Part
  42861. if (dataPart.id === Shape2D.SHAPE2D_FILLPARTID) {
  42862. var fill = this.fill;
  42863. if (fill instanceof BABYLON.SolidColorBrush2D) {
  42864. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLSOLID);
  42865. }
  42866. if (fill instanceof BABYLON.GradientColorBrush2D) {
  42867. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT);
  42868. }
  42869. }
  42870. // Border Part
  42871. if (dataPart.id === Shape2D.SHAPE2D_BORDERPARTID) {
  42872. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDER);
  42873. var border = this.border;
  42874. if (border instanceof BABYLON.SolidColorBrush2D) {
  42875. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID);
  42876. }
  42877. if (border instanceof BABYLON.GradientColorBrush2D) {
  42878. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT);
  42879. }
  42880. }
  42881. return cat;
  42882. };
  42883. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  42884. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  42885. return false;
  42886. }
  42887. // Fill Part
  42888. if (part.id === Shape2D.SHAPE2D_FILLPARTID) {
  42889. var d = part;
  42890. if (this.fill) {
  42891. var fill = this.fill;
  42892. if (fill instanceof BABYLON.SolidColorBrush2D) {
  42893. d.fillSolidColor = fill.color;
  42894. }
  42895. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  42896. d.fillGradientColor1 = fill.color1;
  42897. d.fillGradientColor2 = fill.color2;
  42898. 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));
  42899. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  42900. d.fillGradientTY = ty;
  42901. }
  42902. }
  42903. }
  42904. else if (part.id === Shape2D.SHAPE2D_BORDERPARTID) {
  42905. var d = part;
  42906. if (this.border) {
  42907. d.borderThickness = this.borderThickness;
  42908. var border = this.border;
  42909. if (border instanceof BABYLON.SolidColorBrush2D) {
  42910. d.borderSolidColor = border.color;
  42911. }
  42912. else if (border instanceof BABYLON.GradientColorBrush2D) {
  42913. d.borderGradientColor1 = border.color1;
  42914. d.borderGradientColor2 = border.color2;
  42915. 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));
  42916. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  42917. d.borderGradientTY = ty;
  42918. }
  42919. }
  42920. }
  42921. return true;
  42922. };
  42923. Shape2D.prototype._updateTransparencyStatus = function () {
  42924. this.isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent()) || (this.actualOpacity < 1);
  42925. };
  42926. Shape2D.SHAPE2D_BORDERPARTID = 1;
  42927. Shape2D.SHAPE2D_FILLPARTID = 2;
  42928. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  42929. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  42930. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  42931. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  42932. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  42933. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  42934. __decorate([
  42935. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D.borderProperty = pi; }, true)
  42936. ], Shape2D.prototype, "border", null);
  42937. __decorate([
  42938. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D.fillProperty = pi; }, true)
  42939. ], Shape2D.prototype, "fill", null);
  42940. __decorate([
  42941. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D.borderThicknessProperty = pi; })
  42942. ], Shape2D.prototype, "borderThickness", null);
  42943. Shape2D = __decorate([
  42944. BABYLON.className("Shape2D")
  42945. ], Shape2D);
  42946. return Shape2D;
  42947. })(BABYLON.RenderablePrim2D);
  42948. BABYLON.Shape2D = Shape2D;
  42949. var Shape2DInstanceData = (function (_super) {
  42950. __extends(Shape2DInstanceData, _super);
  42951. function Shape2DInstanceData() {
  42952. _super.apply(this, arguments);
  42953. }
  42954. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  42955. // FILL ATTRIBUTES
  42956. get: function () {
  42957. return null;
  42958. },
  42959. enumerable: true,
  42960. configurable: true
  42961. });
  42962. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  42963. get: function () {
  42964. return null;
  42965. },
  42966. enumerable: true,
  42967. configurable: true
  42968. });
  42969. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  42970. get: function () {
  42971. return null;
  42972. },
  42973. enumerable: true,
  42974. configurable: true
  42975. });
  42976. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  42977. get: function () {
  42978. return null;
  42979. },
  42980. enumerable: true,
  42981. configurable: true
  42982. });
  42983. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  42984. // BORDER ATTRIBUTES
  42985. get: function () {
  42986. return null;
  42987. },
  42988. enumerable: true,
  42989. configurable: true
  42990. });
  42991. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  42992. get: function () {
  42993. return null;
  42994. },
  42995. enumerable: true,
  42996. configurable: true
  42997. });
  42998. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  42999. get: function () {
  43000. return null;
  43001. },
  43002. enumerable: true,
  43003. configurable: true
  43004. });
  43005. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  43006. get: function () {
  43007. return null;
  43008. },
  43009. enumerable: true,
  43010. configurable: true
  43011. });
  43012. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  43013. get: function () {
  43014. return null;
  43015. },
  43016. enumerable: true,
  43017. configurable: true
  43018. });
  43019. __decorate([
  43020. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  43021. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  43022. __decorate([
  43023. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  43024. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  43025. __decorate([
  43026. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  43027. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  43028. __decorate([
  43029. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  43030. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  43031. __decorate([
  43032. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  43033. ], Shape2DInstanceData.prototype, "borderThickness", null);
  43034. __decorate([
  43035. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  43036. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  43037. __decorate([
  43038. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  43039. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  43040. __decorate([
  43041. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  43042. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  43043. __decorate([
  43044. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  43045. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  43046. return Shape2DInstanceData;
  43047. })(BABYLON.InstanceDataBase);
  43048. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  43049. })(BABYLON || (BABYLON = {}));
  43050. var BABYLON;
  43051. (function (BABYLON) {
  43052. var Group2D = (function (_super) {
  43053. __extends(Group2D, _super);
  43054. /**
  43055. * Create an Logical or Renderable Group.
  43056. * @param settings a combination of settings, possible ones are
  43057. * - 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)
  43058. * - children: an array of direct children
  43059. * - id a text identifier, for information purpose
  43060. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  43061. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  43062. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  43063. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  43064. * - zOrder: override the zOrder with the specified value
  43065. * - origin: define the normalized origin point location, default [0.5;0.5]
  43066. * - 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.
  43067. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  43068. * - 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).
  43069. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  43070. * - 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!
  43071. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43072. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43073. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43074. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43075. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  43076. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  43077. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  43078. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  43079. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43080. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43081. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43082. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43083. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  43084. */
  43085. function Group2D(settings) {
  43086. if (settings == null) {
  43087. settings = {};
  43088. }
  43089. if (settings.origin == null) {
  43090. settings.origin = new BABYLON.Vector2(0, 0);
  43091. }
  43092. _super.call(this, settings);
  43093. var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));
  43094. this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;
  43095. if (this._trackedNode && this.owner) {
  43096. this.owner._registerTrackedNode(this);
  43097. }
  43098. this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;
  43099. this.size = size;
  43100. this._viewportPosition = BABYLON.Vector2.Zero();
  43101. }
  43102. Group2D._createCachedCanvasGroup = function (owner) {
  43103. var g = new Group2D({ parent: owner, id: "__cachedCanvasGroup__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), size: null, isVisible: true });
  43104. return g;
  43105. };
  43106. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  43107. this._bindCacheTarget();
  43108. if (vertexData) {
  43109. var uv = vertexData.uvs;
  43110. var nodeuv = this._renderableData._cacheNodeUVs;
  43111. for (var i = 0; i < 4; i++) {
  43112. uv[i * 2 + 0] = nodeuv[i].x;
  43113. uv[i * 2 + 1] = nodeuv[i].y;
  43114. }
  43115. }
  43116. if (material) {
  43117. material.diffuseTexture = this._renderableData._cacheTexture;
  43118. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  43119. }
  43120. this._renderableData._cacheTexture.hasAlpha = true;
  43121. this._unbindCacheTarget();
  43122. };
  43123. Object.defineProperty(Group2D.prototype, "cachedRect", {
  43124. /**
  43125. * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
  43126. * 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.
  43127. */
  43128. get: function () {
  43129. if (!this._renderableData) {
  43130. return null;
  43131. }
  43132. return this._renderableData._cacheNode;
  43133. },
  43134. enumerable: true,
  43135. configurable: true
  43136. });
  43137. Object.defineProperty(Group2D.prototype, "cachedUVs", {
  43138. /**
  43139. * The UVs into the MapTexture that map the cached group
  43140. */
  43141. get: function () {
  43142. if (!this._renderableData) {
  43143. return null;
  43144. }
  43145. return this._renderableData._cacheNodeUVs;
  43146. },
  43147. enumerable: true,
  43148. configurable: true
  43149. });
  43150. Object.defineProperty(Group2D.prototype, "cachedUVsChanged", {
  43151. get: function () {
  43152. if (!this._renderableData) {
  43153. return null;
  43154. }
  43155. if (!this._renderableData._cacheNodeUVsChangedObservable) {
  43156. this._renderableData._cacheNodeUVsChangedObservable = new BABYLON.Observable();
  43157. }
  43158. return this._renderableData._cacheNodeUVsChangedObservable;
  43159. },
  43160. enumerable: true,
  43161. configurable: true
  43162. });
  43163. Object.defineProperty(Group2D.prototype, "cacheTexture", {
  43164. /**
  43165. * Access the texture that maintains a cached version of the Group2D.
  43166. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
  43167. */
  43168. get: function () {
  43169. if (!this._renderableData) {
  43170. return null;
  43171. }
  43172. return this._renderableData._cacheTexture;
  43173. },
  43174. enumerable: true,
  43175. configurable: true
  43176. });
  43177. /**
  43178. * Call this method to remove this Group and its children from the Canvas
  43179. */
  43180. Group2D.prototype.dispose = function () {
  43181. if (!_super.prototype.dispose.call(this)) {
  43182. return false;
  43183. }
  43184. if (this._trackedNode != null) {
  43185. this.owner._unregisterTrackedNode(this);
  43186. this._trackedNode = null;
  43187. }
  43188. if (this._renderableData) {
  43189. this._renderableData.dispose(this.owner.engine);
  43190. this._renderableData = null;
  43191. }
  43192. return true;
  43193. };
  43194. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  43195. /**
  43196. * @returns Returns true if the Group render content, false if it's a logical group only
  43197. */
  43198. get: function () {
  43199. return this._isRenderableGroup;
  43200. },
  43201. enumerable: true,
  43202. configurable: true
  43203. });
  43204. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  43205. /**
  43206. * @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
  43207. */
  43208. get: function () {
  43209. return this._isCachedGroup;
  43210. },
  43211. enumerable: true,
  43212. configurable: true
  43213. });
  43214. Object.defineProperty(Group2D.prototype, "size", {
  43215. get: function () {
  43216. return this._size;
  43217. },
  43218. /**
  43219. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  43220. * 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.
  43221. */
  43222. set: function (val) {
  43223. this._size = val;
  43224. },
  43225. enumerable: true,
  43226. configurable: true
  43227. });
  43228. Object.defineProperty(Group2D.prototype, "viewportSize", {
  43229. get: function () {
  43230. return this._viewportSize;
  43231. },
  43232. enumerable: true,
  43233. configurable: true
  43234. });
  43235. Object.defineProperty(Group2D.prototype, "actualSize", {
  43236. get: function () {
  43237. // The computed size will be floor on both width and height
  43238. var actualSize;
  43239. // Return the size if set by the user
  43240. if (this._size) {
  43241. actualSize = new BABYLON.Size(Math.ceil(this._size.width), Math.ceil(this._size.height));
  43242. }
  43243. else {
  43244. var m = this.boundingInfo.max();
  43245. actualSize = new BABYLON.Size(Math.ceil(m.x), Math.ceil(m.y));
  43246. }
  43247. // 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)
  43248. if (!actualSize.equals(this._actualSize)) {
  43249. this.onPrimitivePropertyDirty(Group2D.actualSizeProperty.flagId);
  43250. this._actualSize = actualSize;
  43251. this.handleGroupChanged(Group2D.actualSizeProperty);
  43252. }
  43253. return actualSize;
  43254. },
  43255. enumerable: true,
  43256. configurable: true
  43257. });
  43258. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  43259. /**
  43260. * 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.
  43261. * 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.
  43262. */
  43263. get: function () {
  43264. return this._cacheBehavior;
  43265. },
  43266. enumerable: true,
  43267. configurable: true
  43268. });
  43269. Group2D.prototype._addPrimToDirtyList = function (prim) {
  43270. this._renderableData._primDirtyList.push(prim);
  43271. };
  43272. Group2D.prototype._renderCachedCanvas = function () {
  43273. this.owner._addGroupRenderCount(1);
  43274. this.updateCachedStates(true);
  43275. var context = new BABYLON.PrepareRender2DContext();
  43276. this._prepareGroupRender(context);
  43277. this._groupRender();
  43278. };
  43279. Object.defineProperty(Group2D.prototype, "trackedNode", {
  43280. /**
  43281. * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node.
  43282. */
  43283. get: function () {
  43284. return this._trackedNode;
  43285. },
  43286. set: function (val) {
  43287. if (val != null) {
  43288. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  43289. this.owner._registerTrackedNode(this);
  43290. }
  43291. this._trackedNode = val;
  43292. }
  43293. else {
  43294. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  43295. this.owner._unregisterTrackedNode(this);
  43296. }
  43297. this._trackedNode = null;
  43298. }
  43299. },
  43300. enumerable: true,
  43301. configurable: true
  43302. });
  43303. Group2D.prototype.levelIntersect = function (intersectInfo) {
  43304. // 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
  43305. return true;
  43306. };
  43307. Group2D.prototype.updateLevelBoundingInfo = function () {
  43308. var size;
  43309. // If the size is set by the user, the boundingInfo is computed from this value
  43310. if (this.size) {
  43311. size = this.size;
  43312. }
  43313. else {
  43314. size = new BABYLON.Size(0, 0);
  43315. }
  43316. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  43317. };
  43318. // Method called only on renderable groups to prepare the rendering
  43319. Group2D.prototype._prepareGroupRender = function (context) {
  43320. var sortedDirtyList = null;
  43321. // Update the Global Transformation and visibility status of the changed primitives
  43322. if ((this._renderableData._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  43323. sortedDirtyList = this._renderableData._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  43324. this.updateCachedStatesOf(sortedDirtyList, true);
  43325. }
  43326. // Setup the size of the rendering viewport
  43327. // 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
  43328. if (!this._isCachedGroup) {
  43329. // Compute the WebGL viewport's location/size
  43330. var t = this._globalTransform.getTranslation();
  43331. var s = this.actualSize.clone();
  43332. var rs = this.owner._renderingSize;
  43333. s.height = Math.min(s.height, rs.height - t.y);
  43334. s.width = Math.min(s.width, rs.width - t.x);
  43335. var x = t.x;
  43336. var y = t.y;
  43337. // 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
  43338. this._viewportPosition.x = x;
  43339. this._viewportPosition.y = y;
  43340. var vw = s.width;
  43341. var vh = s.height;
  43342. if (!this._viewportSize) {
  43343. this._viewportSize = new BABYLON.Size(vw, vh);
  43344. }
  43345. else {
  43346. if (this._viewportSize.width !== vw || this._viewportSize.height !== vh) {
  43347. context.forceRefreshPrimitive = true;
  43348. }
  43349. this._viewportSize.width = vw;
  43350. this._viewportSize.height = vh;
  43351. }
  43352. }
  43353. else {
  43354. var newSize = this.actualSize.clone();
  43355. if (!newSize.equals(this._viewportSize)) {
  43356. context.forceRefreshPrimitive = true;
  43357. }
  43358. this._viewportSize = newSize;
  43359. }
  43360. if ((this._renderableData._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  43361. // If the group is cached, set the dirty flag to true because of the incoming changes
  43362. this._cacheGroupDirty = this._isCachedGroup;
  43363. // If it's a force refresh, prepare all the children
  43364. if (context.forceRefreshPrimitive) {
  43365. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  43366. var p = _a[_i];
  43367. p._prepareRender(context);
  43368. }
  43369. }
  43370. else {
  43371. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  43372. // the hierarchyDepth in order to prepare primitives from top to bottom
  43373. if (!sortedDirtyList) {
  43374. sortedDirtyList = this._renderableData._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  43375. }
  43376. sortedDirtyList.forEach(function (p) {
  43377. // 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.
  43378. // 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.
  43379. if (!p.isDisposed && p._needPrepare()) {
  43380. p._prepareRender(context);
  43381. }
  43382. });
  43383. }
  43384. // Everything is updated, clear the dirty list
  43385. this._renderableData._primDirtyList.forEach(function (p) { return p._resetPropertiesDirty(); });
  43386. this._renderableData._primDirtyList.splice(0);
  43387. }
  43388. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  43389. this._renderableData._childrenRenderableGroups.forEach(function (g) {
  43390. g._prepareGroupRender(context);
  43391. });
  43392. };
  43393. Group2D.prototype._groupRender = function () {
  43394. var _this = this;
  43395. var engine = this.owner.engine;
  43396. var failedCount = 0;
  43397. // First recurse to children render group to render them (in their cache or on screen)
  43398. for (var _i = 0, _a = this._renderableData._childrenRenderableGroups; _i < _a.length; _i++) {
  43399. var childGroup = _a[_i];
  43400. childGroup._groupRender();
  43401. }
  43402. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  43403. if (!this.isCachedGroup || this._cacheGroupDirty) {
  43404. this.owner._addGroupRenderCount(1);
  43405. if (this.isCachedGroup) {
  43406. this._bindCacheTarget();
  43407. }
  43408. else {
  43409. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  43410. }
  43411. var curAlphaTest = engine.getAlphaTesting() === true;
  43412. var curDepthWrite = engine.getDepthWrite() === true;
  43413. // ===================================================================
  43414. // First pass, update the InstancedArray and render Opaque primitives
  43415. // Disable Alpha Testing, Enable Depth Write
  43416. engine.setAlphaTesting(false);
  43417. engine.setDepthWrite(true);
  43418. // For each different model of primitive to render
  43419. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeOpaque);
  43420. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  43421. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  43422. var renderCount = _this._prepareContext(engine, context, v);
  43423. // If null is returned, there's no opaque data to render
  43424. if (renderCount === null) {
  43425. return;
  43426. }
  43427. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  43428. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  43429. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  43430. var renderFailed = !v.modelRenderCache.render(v, context);
  43431. // Update dirty flag/related
  43432. v.opaqueDirty = renderFailed;
  43433. failedCount += renderFailed ? 1 : 0;
  43434. }
  43435. });
  43436. // =======================================================================
  43437. // Second pass, update the InstancedArray and render AlphaTest primitives
  43438. // Enable Alpha Testing, Enable Depth Write
  43439. engine.setAlphaTesting(true);
  43440. engine.setDepthWrite(true);
  43441. // For each different model of primitive to render
  43442. context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeAlphaTest);
  43443. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  43444. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  43445. var renderCount = _this._prepareContext(engine, context, v);
  43446. // If null is returned, there's no opaque data to render
  43447. if (renderCount === null) {
  43448. return;
  43449. }
  43450. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  43451. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  43452. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  43453. var renderFailed = !v.modelRenderCache.render(v, context);
  43454. // Update dirty flag/related
  43455. v.opaqueDirty = renderFailed;
  43456. failedCount += renderFailed ? 1 : 0;
  43457. }
  43458. });
  43459. // =======================================================================
  43460. // Third pass, transparent primitive rendering
  43461. // Enable Alpha Testing, Disable Depth Write
  43462. engine.setAlphaTesting(true);
  43463. engine.setDepthWrite(false);
  43464. // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
  43465. if (this._renderableData._transparentListChanged) {
  43466. this._updateTransparentData();
  43467. }
  43468. // From this point on we have up to date data to render, so let's go
  43469. failedCount += this._renderTransparentData();
  43470. // =======================================================================
  43471. // Unbind target/restore viewport setting, clear dirty flag, and quit
  43472. // The group's content is no longer dirty
  43473. this._cacheGroupDirty = failedCount !== 0;
  43474. if (this.isCachedGroup) {
  43475. this._unbindCacheTarget();
  43476. }
  43477. else {
  43478. if (curVP) {
  43479. engine.setViewport(curVP);
  43480. }
  43481. }
  43482. // Restore saved states
  43483. engine.setAlphaTesting(curAlphaTest);
  43484. engine.setDepthWrite(curDepthWrite);
  43485. }
  43486. };
  43487. Group2D.prototype._setCacheGroupDirty = function () {
  43488. this._cacheGroupDirty = true;
  43489. };
  43490. Group2D.prototype._updateTransparentData = function () {
  43491. this.owner._addUpdateTransparentDataCount(1);
  43492. var rd = this._renderableData;
  43493. // Sort all the primitive from their depth, max (bottom) to min (top)
  43494. rd._transparentPrimitives.sort(function (a, b) { return b._primitive.actualZOffset - a._primitive.actualZOffset; });
  43495. var checkAndAddPrimInSegment = function (seg, tpiI) {
  43496. var tpi = rd._transparentPrimitives[tpiI];
  43497. // Fast rejection: if gii are different
  43498. if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
  43499. return false;
  43500. }
  43501. //let tpiZ = tpi._primitive.actualZOffset;
  43502. // We've made it so far, the tpi can be part of the segment, add it
  43503. tpi._transparentSegment = seg;
  43504. tpi._primitive._updateTransparentSegmentIndices(seg);
  43505. return true;
  43506. };
  43507. // Free the existing TransparentSegments
  43508. for (var _i = 0, _a = rd._transparentSegments; _i < _a.length; _i++) {
  43509. var ts = _a[_i];
  43510. ts.dispose(this.owner.engine);
  43511. }
  43512. rd._transparentSegments.splice(0);
  43513. var prevSeg = null;
  43514. for (var tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
  43515. var tpi = rd._transparentPrimitives[tpiI];
  43516. // Check if the Data in which the primitive is stored is not sorted properly
  43517. if (tpi._groupInstanceInfo.transparentOrderDirty) {
  43518. tpi._groupInstanceInfo.sortTransparentData();
  43519. }
  43520. // Reset the segment, we have to create/rebuild it
  43521. tpi._transparentSegment = null;
  43522. // If there's a previous valid segment, check if this prim can be part of it
  43523. if (prevSeg) {
  43524. checkAndAddPrimInSegment(prevSeg, tpiI);
  43525. }
  43526. // If we couldn't insert in the adjacent segments, he have to create one
  43527. if (!tpi._transparentSegment) {
  43528. var ts = new BABYLON.TransparentSegment();
  43529. ts.groupInsanceInfo = tpi._groupInstanceInfo;
  43530. var prim = tpi._primitive;
  43531. ts.startZ = prim.actualZOffset;
  43532. prim._updateTransparentSegmentIndices(ts);
  43533. ts.endZ = ts.startZ;
  43534. tpi._transparentSegment = ts;
  43535. rd._transparentSegments.push(ts);
  43536. }
  43537. // Update prevSeg
  43538. prevSeg = tpi._transparentSegment;
  43539. }
  43540. //rd._firstChangedPrim = null;
  43541. rd._transparentListChanged = false;
  43542. };
  43543. Group2D.prototype._renderTransparentData = function () {
  43544. var failedCount = 0;
  43545. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeTransparent);
  43546. var rd = this._renderableData;
  43547. var useInstanced = this.owner.supportInstancedArray;
  43548. var length = rd._transparentSegments.length;
  43549. for (var i = 0; i < length; i++) {
  43550. context.instancedBuffers = null;
  43551. var ts = rd._transparentSegments[i];
  43552. var gii = ts.groupInsanceInfo;
  43553. var mrc = gii.modelRenderCache;
  43554. var engine = this.owner.engine;
  43555. var count = ts.endDataIndex - ts.startDataIndex;
  43556. // Use Instanced Array if it's supported and if there's at least 5 prims to draw.
  43557. // We don't want to create an Instanced Buffer for less that 5 prims
  43558. if (useInstanced && count >= 5) {
  43559. if (!ts.partBuffers) {
  43560. var buffers = new Array();
  43561. for (var j = 0; j < gii.transparentData.length; j++) {
  43562. var gitd = gii.transparentData[j];
  43563. var dfa = gitd._partData;
  43564. var data = dfa.pack();
  43565. var stride = dfa.stride;
  43566. var neededSize = count * stride * 4;
  43567. var buffer = engine.createInstancesBuffer(neededSize); // Create + bind
  43568. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  43569. engine.updateArrayBuffer(segData);
  43570. buffers.push(buffer);
  43571. }
  43572. ts.partBuffers = buffers;
  43573. }
  43574. else if (gii.transparentDirty) {
  43575. for (var j = 0; j < gii.transparentData.length; j++) {
  43576. var gitd = gii.transparentData[j];
  43577. var dfa = gitd._partData;
  43578. var data = dfa.pack();
  43579. var stride = dfa.stride;
  43580. var buffer = ts.partBuffers[j];
  43581. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  43582. engine.bindArrayBuffer(buffer);
  43583. engine.updateArrayBuffer(segData);
  43584. }
  43585. }
  43586. context.useInstancing = true;
  43587. context.instancesCount = count;
  43588. context.instancedBuffers = ts.partBuffers;
  43589. context.groupInfoPartData = gii.transparentData;
  43590. var renderFailed = !mrc.render(gii, context);
  43591. failedCount += renderFailed ? 1 : 0;
  43592. }
  43593. else {
  43594. context.useInstancing = false;
  43595. context.partDataStartIndex = ts.startDataIndex;
  43596. context.partDataEndIndex = ts.endDataIndex;
  43597. context.groupInfoPartData = gii.transparentData;
  43598. var renderFailed = !mrc.render(gii, context);
  43599. failedCount += renderFailed ? 1 : 0;
  43600. }
  43601. }
  43602. return failedCount;
  43603. };
  43604. Group2D.prototype._prepareContext = function (engine, context, gii) {
  43605. var gipd = null;
  43606. var setDirty;
  43607. var getDirty;
  43608. // Render Mode specifics
  43609. switch (context.renderMode) {
  43610. case BABYLON.Render2DContext.RenderModeOpaque:
  43611. {
  43612. if (!gii.hasOpaqueData) {
  43613. return null;
  43614. }
  43615. setDirty = function (dirty) { gii.opaqueDirty = dirty; };
  43616. getDirty = function () { return gii.opaqueDirty; };
  43617. context.groupInfoPartData = gii.opaqueData;
  43618. gipd = gii.opaqueData;
  43619. break;
  43620. }
  43621. case BABYLON.Render2DContext.RenderModeAlphaTest:
  43622. {
  43623. if (!gii.hasAlphaTestData) {
  43624. return null;
  43625. }
  43626. setDirty = function (dirty) { gii.alphaTestDirty = dirty; };
  43627. getDirty = function () { return gii.alphaTestDirty; };
  43628. context.groupInfoPartData = gii.alphaTestData;
  43629. gipd = gii.alphaTestData;
  43630. break;
  43631. }
  43632. default:
  43633. throw new Error("_prepareContext is only for opaque or alphaTest");
  43634. }
  43635. var renderCount = 0;
  43636. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  43637. // Skip it if instanced arrays are not supported
  43638. if (this.owner.supportInstancedArray) {
  43639. // Flag for instancing
  43640. context.useInstancing = true;
  43641. // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
  43642. for (var i = 0; i < gipd.length; i++) {
  43643. var pid = gipd[i];
  43644. // If the instances of the model was changed, pack the data
  43645. var array = pid._partData;
  43646. var instanceData_1 = array.pack();
  43647. renderCount += array.usedElementCount;
  43648. // Compute the size the instance buffer should have
  43649. var neededSize = array.usedElementCount * array.stride * 4;
  43650. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  43651. if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
  43652. if (pid._partBuffer) {
  43653. engine.deleteInstancesBuffer(pid._partBuffer);
  43654. }
  43655. pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
  43656. pid._partBufferSize = neededSize;
  43657. setDirty(false);
  43658. // Update the WebGL buffer to match the new content of the instances data
  43659. engine.updateArrayBuffer(instanceData_1);
  43660. }
  43661. else if (getDirty()) {
  43662. // Update the WebGL buffer to match the new content of the instances data
  43663. engine.bindArrayBuffer(pid._partBuffer);
  43664. engine.updateArrayBuffer(instanceData_1);
  43665. }
  43666. }
  43667. setDirty(false);
  43668. }
  43669. else {
  43670. context.partDataStartIndex = 0;
  43671. // Find the first valid object to get the count
  43672. if (context.groupInfoPartData.length > 0) {
  43673. var i = 0;
  43674. while (!context.groupInfoPartData[i]) {
  43675. i++;
  43676. }
  43677. context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
  43678. }
  43679. }
  43680. return renderCount;
  43681. };
  43682. Group2D.prototype._setRenderingScale = function (scale) {
  43683. if (this._renderableData._renderingScale === scale) {
  43684. return;
  43685. }
  43686. this._renderableData._renderingScale = scale;
  43687. };
  43688. Group2D.prototype._bindCacheTarget = function () {
  43689. var curWidth;
  43690. var curHeight;
  43691. var rd = this._renderableData;
  43692. var rs = rd._renderingScale;
  43693. Group2D._s.width = Math.ceil(this.actualSize.width * rs);
  43694. Group2D._s.height = Math.ceil(this.actualSize.height * rs);
  43695. var sizeChanged = !Group2D._s.equals(rd._cacheSize);
  43696. if (rd._cacheNode) {
  43697. var size = rd._cacheNode.contentSize;
  43698. // Check if we have to deallocate because the size is too small
  43699. if ((size.width < Group2D._s.width) || (size.height < Group2D._s.height)) {
  43700. // For Screen space: over-provisioning of 7% more to avoid frequent resizing for few pixels...
  43701. // For World space: no over-provisioning
  43702. var overprovisioning = this.owner.isScreenSpace ? 1.07 : 1;
  43703. curWidth = Math.floor(Group2D._s.width * overprovisioning);
  43704. curHeight = Math.floor(Group2D._s.height * overprovisioning);
  43705. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  43706. rd._cacheTexture.freeRect(rd._cacheNode);
  43707. rd._cacheNode = null;
  43708. }
  43709. }
  43710. if (!rd._cacheNode) {
  43711. // Check if we have to allocate a rendering zone in the global cache texture
  43712. var res = this.owner._allocateGroupCache(this, this.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null, rd._useMipMap, rd._anisotropicLevel);
  43713. rd._cacheNode = res.node;
  43714. rd._cacheTexture = res.texture;
  43715. rd._cacheRenderSprite = res.sprite;
  43716. sizeChanged = true;
  43717. }
  43718. if (sizeChanged) {
  43719. rd._cacheSize.copyFrom(Group2D._s);
  43720. rd._cacheNodeUVs = rd._cacheNode.getUVsForCustomSize(rd._cacheSize);
  43721. this.scale = this._renderableData._renderingScale;
  43722. if (rd._cacheNodeUVsChangedObservable && rd._cacheNodeUVsChangedObservable.hasObservers()) {
  43723. rd._cacheNodeUVsChangedObservable.notifyObservers(rd._cacheNodeUVs);
  43724. }
  43725. this._setFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  43726. }
  43727. var n = rd._cacheNode;
  43728. rd._cacheTexture.bindTextureForPosSize(n.pos, Group2D._s, true);
  43729. };
  43730. Group2D.prototype._unbindCacheTarget = function () {
  43731. if (this._renderableData._cacheTexture) {
  43732. this._renderableData._cacheTexture.unbindTexture();
  43733. }
  43734. };
  43735. Group2D.prototype.handleGroupChanged = function (prop) {
  43736. // This method is only for cachedGroup
  43737. var rd = this._renderableData;
  43738. if (!this.isCachedGroup || !rd._cacheRenderSprite) {
  43739. return;
  43740. }
  43741. // For now we only support these property changes
  43742. // TODO: add more! :)
  43743. if (prop.id === BABYLON.Prim2DBase.actualPositionProperty.id) {
  43744. rd._cacheRenderSprite.actualPosition = this.actualPosition.clone();
  43745. }
  43746. else if (prop.id === BABYLON.Prim2DBase.rotationProperty.id) {
  43747. rd._cacheRenderSprite.rotation = this.rotation;
  43748. }
  43749. else if (prop.id === BABYLON.Prim2DBase.scaleProperty.id) {
  43750. rd._cacheRenderSprite.scale = this.scale;
  43751. }
  43752. else if (prop.id === BABYLON.Prim2DBase.originProperty.id) {
  43753. rd._cacheRenderSprite.origin = this.origin.clone();
  43754. }
  43755. else if (prop.id === Group2D.actualSizeProperty.id) {
  43756. rd._cacheRenderSprite.size = this.actualSize.clone();
  43757. }
  43758. };
  43759. Group2D.prototype.detectGroupStates = function () {
  43760. var isCanvas = this instanceof BABYLON.Canvas2D;
  43761. var canvasStrat = this.owner.cachingStrategy;
  43762. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  43763. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  43764. this._isRenderableGroup = isCanvas;
  43765. this._isCachedGroup = false;
  43766. }
  43767. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  43768. if (isCanvas) {
  43769. this._isRenderableGroup = true;
  43770. this._isCachedGroup = true;
  43771. }
  43772. else {
  43773. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  43774. this._isCachedGroup = false;
  43775. }
  43776. }
  43777. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  43778. if (isCanvas) {
  43779. this._isRenderableGroup = true;
  43780. this._isCachedGroup = false;
  43781. }
  43782. else {
  43783. if (this.hierarchyDepth === 1) {
  43784. this._isRenderableGroup = true;
  43785. this._isCachedGroup = true;
  43786. }
  43787. else {
  43788. this._isRenderableGroup = false;
  43789. this._isCachedGroup = false;
  43790. }
  43791. }
  43792. }
  43793. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  43794. var gcb = this.cacheBehavior;
  43795. if ((gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  43796. this._isRenderableGroup = gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  43797. this._isCachedGroup = false;
  43798. }
  43799. if (gcb === Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  43800. this._isRenderableGroup = true;
  43801. this._isCachedGroup = true;
  43802. }
  43803. }
  43804. if (this._isRenderableGroup) {
  43805. // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object...
  43806. if (!this._renderableData) {
  43807. this._renderableData = new RenderableGroupData();
  43808. }
  43809. }
  43810. // If the group is tagged as renderable we add it to the renderable tree
  43811. if (this._isCachedGroup) {
  43812. var cur = this.parent;
  43813. while (cur) {
  43814. if (cur instanceof Group2D && cur._isRenderableGroup) {
  43815. if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) {
  43816. cur._renderableData._childrenRenderableGroups.push(this);
  43817. }
  43818. break;
  43819. }
  43820. cur = cur.parent;
  43821. }
  43822. }
  43823. };
  43824. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  43825. /**
  43826. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  43827. */
  43828. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  43829. /**
  43830. * When used, this group's content won't be cached, no matter which strategy used.
  43831. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  43832. */
  43833. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  43834. /**
  43835. * When used, the group's content will be cached in the nearest cached parent group/canvas
  43836. */
  43837. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  43838. Group2D._s = BABYLON.Size.Zero();
  43839. __decorate([
  43840. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D.sizeProperty = pi; }, false, true)
  43841. ], Group2D.prototype, "size", null);
  43842. __decorate([
  43843. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 2, function (pi) { return Group2D.actualSizeProperty = pi; })
  43844. ], Group2D.prototype, "actualSize", null);
  43845. Group2D = __decorate([
  43846. BABYLON.className("Group2D")
  43847. ], Group2D);
  43848. return Group2D;
  43849. })(BABYLON.Prim2DBase);
  43850. BABYLON.Group2D = Group2D;
  43851. var RenderableGroupData = (function () {
  43852. function RenderableGroupData() {
  43853. this._primDirtyList = new Array();
  43854. this._childrenRenderableGroups = new Array();
  43855. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  43856. this._transparentPrimitives = new Array();
  43857. this._transparentSegments = new Array();
  43858. this._transparentListChanged = false;
  43859. this._cacheNode = null;
  43860. this._cacheTexture = null;
  43861. this._cacheRenderSprite = null;
  43862. this._renderingScale = 1;
  43863. this._cacheNodeUVs = null;
  43864. this._cacheNodeUVsChangedObservable = null;
  43865. this._cacheSize = BABYLON.Size.Zero();
  43866. this._useMipMap = false;
  43867. this._anisotropicLevel = 1;
  43868. }
  43869. RenderableGroupData.prototype.dispose = function (engine) {
  43870. if (this._cacheRenderSprite) {
  43871. this._cacheRenderSprite.dispose();
  43872. this._cacheRenderSprite = null;
  43873. }
  43874. if (this._cacheTexture && this._cacheNode) {
  43875. this._cacheTexture.freeRect(this._cacheNode);
  43876. this._cacheTexture = null;
  43877. this._cacheNode = null;
  43878. }
  43879. if (this._primDirtyList) {
  43880. this._primDirtyList.splice(0);
  43881. this._primDirtyList = null;
  43882. }
  43883. if (this._renderGroupInstancesInfo) {
  43884. this._renderGroupInstancesInfo.forEach(function (k, v) {
  43885. v.dispose();
  43886. });
  43887. this._renderGroupInstancesInfo = null;
  43888. }
  43889. if (this._cacheNodeUVsChangedObservable) {
  43890. this._cacheNodeUVsChangedObservable.clear();
  43891. this._cacheNodeUVsChangedObservable = null;
  43892. }
  43893. if (this._transparentSegments) {
  43894. for (var _i = 0, _a = this._transparentSegments; _i < _a.length; _i++) {
  43895. var ts = _a[_i];
  43896. ts.dispose(engine);
  43897. }
  43898. this._transparentSegments.splice(0);
  43899. this._transparentSegments = null;
  43900. }
  43901. };
  43902. RenderableGroupData.prototype.addNewTransparentPrimitiveInfo = function (prim, gii) {
  43903. var tpi = new TransparentPrimitiveInfo();
  43904. tpi._primitive = prim;
  43905. tpi._groupInstanceInfo = gii;
  43906. tpi._transparentSegment = null;
  43907. this._transparentPrimitives.push(tpi);
  43908. this._transparentListChanged = true;
  43909. return tpi;
  43910. };
  43911. RenderableGroupData.prototype.removeTransparentPrimitiveInfo = function (tpi) {
  43912. var index = this._transparentPrimitives.indexOf(tpi);
  43913. if (index !== -1) {
  43914. this._transparentPrimitives.splice(index, 1);
  43915. this._transparentListChanged = true;
  43916. }
  43917. };
  43918. RenderableGroupData.prototype.transparentPrimitiveZChanged = function (tpi) {
  43919. this._transparentListChanged = true;
  43920. //this.updateSmallestZChangedPrim(tpi);
  43921. };
  43922. return RenderableGroupData;
  43923. })();
  43924. BABYLON.RenderableGroupData = RenderableGroupData;
  43925. var TransparentPrimitiveInfo = (function () {
  43926. function TransparentPrimitiveInfo() {
  43927. }
  43928. return TransparentPrimitiveInfo;
  43929. })();
  43930. BABYLON.TransparentPrimitiveInfo = TransparentPrimitiveInfo;
  43931. })(BABYLON || (BABYLON = {}));
  43932. var BABYLON;
  43933. (function (BABYLON) {
  43934. var Rectangle2DRenderCache = (function (_super) {
  43935. __extends(Rectangle2DRenderCache, _super);
  43936. function Rectangle2DRenderCache(engine, modelKey) {
  43937. _super.call(this, engine, modelKey);
  43938. this.effectsReady = false;
  43939. this.fillVB = null;
  43940. this.fillIB = null;
  43941. this.fillIndicesCount = 0;
  43942. this.instancingFillAttributes = null;
  43943. this.effectFill = null;
  43944. this.effectFillInstanced = null;
  43945. this.borderVB = null;
  43946. this.borderIB = null;
  43947. this.borderIndicesCount = 0;
  43948. this.instancingBorderAttributes = null;
  43949. this.effectBorder = null;
  43950. this.effectBorderInstanced = null;
  43951. }
  43952. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  43953. // Do nothing if the shader is still loading/preparing
  43954. if (!this.effectsReady) {
  43955. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  43956. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  43957. return false;
  43958. }
  43959. this.effectsReady = true;
  43960. }
  43961. var canvas = instanceInfo.owner.owner;
  43962. var engine = canvas.engine;
  43963. var depthFunction = 0;
  43964. if (this.effectFill && this.effectBorder) {
  43965. depthFunction = engine.getDepthFunction();
  43966. engine.setDepthFunctionToLessOrEqual();
  43967. }
  43968. var curAlphaMode = engine.getAlphaMode();
  43969. if (this.effectFill) {
  43970. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  43971. var pid = context.groupInfoPartData[partIndex];
  43972. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  43973. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  43974. }
  43975. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  43976. engine.enableEffect(effect);
  43977. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  43978. if (context.useInstancing) {
  43979. if (!this.instancingFillAttributes) {
  43980. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  43981. }
  43982. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  43983. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  43984. canvas._addDrawCallCount(1, context.renderMode);
  43985. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  43986. engine.draw(true, 0, this.fillIndicesCount, count);
  43987. engine.unbindInstanceAttributes();
  43988. }
  43989. else {
  43990. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  43991. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  43992. this.setupUniforms(effect, partIndex, pid._partData, i);
  43993. engine.draw(true, 0, this.fillIndicesCount);
  43994. }
  43995. }
  43996. }
  43997. if (this.effectBorder) {
  43998. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  43999. var pid = context.groupInfoPartData[partIndex];
  44000. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44001. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  44002. }
  44003. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  44004. engine.enableEffect(effect);
  44005. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  44006. if (context.useInstancing) {
  44007. if (!this.instancingBorderAttributes) {
  44008. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  44009. }
  44010. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44011. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44012. canvas._addDrawCallCount(1, context.renderMode);
  44013. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  44014. engine.draw(true, 0, this.borderIndicesCount, count);
  44015. engine.unbindInstanceAttributes();
  44016. }
  44017. else {
  44018. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44019. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44020. this.setupUniforms(effect, partIndex, pid._partData, i);
  44021. engine.draw(true, 0, this.borderIndicesCount);
  44022. }
  44023. }
  44024. }
  44025. engine.setAlphaMode(curAlphaMode, true);
  44026. if (this.effectFill && this.effectBorder) {
  44027. engine.setDepthFunction(depthFunction);
  44028. }
  44029. return true;
  44030. };
  44031. Rectangle2DRenderCache.prototype.dispose = function () {
  44032. if (!_super.prototype.dispose.call(this)) {
  44033. return false;
  44034. }
  44035. if (this.fillVB) {
  44036. this._engine._releaseBuffer(this.fillVB);
  44037. this.fillVB = null;
  44038. }
  44039. if (this.fillIB) {
  44040. this._engine._releaseBuffer(this.fillIB);
  44041. this.fillIB = null;
  44042. }
  44043. this.effectFill = null;
  44044. this.effectFillInstanced = null;
  44045. this.effectBorder = null;
  44046. this.effectBorderInstanced = null;
  44047. if (this.borderVB) {
  44048. this._engine._releaseBuffer(this.borderVB);
  44049. this.borderVB = null;
  44050. }
  44051. if (this.borderIB) {
  44052. this._engine._releaseBuffer(this.borderIB);
  44053. this.borderIB = null;
  44054. }
  44055. return true;
  44056. };
  44057. return Rectangle2DRenderCache;
  44058. })(BABYLON.ModelRenderCache);
  44059. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  44060. var Rectangle2DInstanceData = (function (_super) {
  44061. __extends(Rectangle2DInstanceData, _super);
  44062. function Rectangle2DInstanceData(partId) {
  44063. _super.call(this, partId, 1);
  44064. }
  44065. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  44066. get: function () {
  44067. return null;
  44068. },
  44069. enumerable: true,
  44070. configurable: true
  44071. });
  44072. __decorate([
  44073. BABYLON.instanceData()
  44074. ], Rectangle2DInstanceData.prototype, "properties", null);
  44075. return Rectangle2DInstanceData;
  44076. })(BABYLON.Shape2DInstanceData);
  44077. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  44078. var Rectangle2D = (function (_super) {
  44079. __extends(Rectangle2D, _super);
  44080. /**
  44081. * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
  44082. * @param settings a combination of settings, possible ones are
  44083. * - 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)
  44084. * - children: an array of direct children
  44085. * - id a text identifier, for information purpose
  44086. * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0]
  44087. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  44088. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  44089. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  44090. * - zOrder: override the zOrder with the specified value
  44091. * - origin: define the normalized origin point location, default [0.5;0.5]
  44092. * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10].
  44093. * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle).
  44094. * - 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)
  44095. * - 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)
  44096. * - borderThickness: the thickness of the drawn border, default is 1.
  44097. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  44098. * - 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!
  44099. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44100. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44101. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44102. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44103. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  44104. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  44105. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  44106. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  44107. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44108. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44109. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44110. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44111. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  44112. */
  44113. function Rectangle2D(settings) {
  44114. // Avoid checking every time if the object exists
  44115. if (settings == null) {
  44116. settings = {};
  44117. }
  44118. _super.call(this, settings);
  44119. if (settings.size != null) {
  44120. this.size = settings.size;
  44121. }
  44122. else if (settings.width || settings.height) {
  44123. var size = new BABYLON.Size(settings.width, settings.height);
  44124. this.size = size;
  44125. }
  44126. //let size = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
  44127. var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
  44128. var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
  44129. //this.size = size;
  44130. this.roundRadius = roundRadius;
  44131. this.borderThickness = borderThickness;
  44132. }
  44133. Object.defineProperty(Rectangle2D.prototype, "actualSize", {
  44134. get: function () {
  44135. if (this._actualSize) {
  44136. return this._actualSize;
  44137. }
  44138. return this.size;
  44139. },
  44140. set: function (value) {
  44141. this._actualSize = value;
  44142. },
  44143. enumerable: true,
  44144. configurable: true
  44145. });
  44146. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  44147. get: function () {
  44148. return this._notRounded;
  44149. },
  44150. set: function (value) {
  44151. this._notRounded = value;
  44152. },
  44153. enumerable: true,
  44154. configurable: true
  44155. });
  44156. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  44157. get: function () {
  44158. return this._roundRadius;
  44159. },
  44160. set: function (value) {
  44161. this._roundRadius = value;
  44162. this.notRounded = value === 0;
  44163. this._positioningDirty();
  44164. },
  44165. enumerable: true,
  44166. configurable: true
  44167. });
  44168. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  44169. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  44170. if (this.notRounded) {
  44171. return true;
  44172. }
  44173. // 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.
  44174. // 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)
  44175. // 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.
  44176. // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
  44177. var size = this.size;
  44178. Rectangle2D._i0.x = intersectInfo._localPickPosition.x;
  44179. Rectangle2D._i0.y = intersectInfo._localPickPosition.y;
  44180. var rr = this.roundRadius;
  44181. var rrs = rr * rr;
  44182. // Check if the point is in the bottom/left quarter area
  44183. Rectangle2D._i1.x = rr;
  44184. Rectangle2D._i1.y = rr;
  44185. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  44186. // Compute the intersection point in the quarter local space
  44187. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  44188. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  44189. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  44190. return Rectangle2D._i2.lengthSquared() <= rrs;
  44191. }
  44192. // Check if the point is in the top/left quarter area
  44193. Rectangle2D._i1.x = rr;
  44194. Rectangle2D._i1.y = size.height - rr;
  44195. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  44196. // Compute the intersection point in the quarter local space
  44197. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  44198. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  44199. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  44200. return Rectangle2D._i2.lengthSquared() <= rrs;
  44201. }
  44202. // Check if the point is in the top/right quarter area
  44203. Rectangle2D._i1.x = size.width - rr;
  44204. Rectangle2D._i1.y = size.height - rr;
  44205. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  44206. // Compute the intersection point in the quarter local space
  44207. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  44208. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  44209. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  44210. return Rectangle2D._i2.lengthSquared() <= rrs;
  44211. }
  44212. // Check if the point is in the bottom/right quarter area
  44213. Rectangle2D._i1.x = size.width - rr;
  44214. Rectangle2D._i1.y = rr;
  44215. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  44216. // Compute the intersection point in the quarter local space
  44217. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  44218. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  44219. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  44220. return Rectangle2D._i2.lengthSquared() <= rrs;
  44221. }
  44222. // At any other locations the point is guarantied to be inside
  44223. return true;
  44224. };
  44225. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  44226. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  44227. };
  44228. Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
  44229. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
  44230. return renderCache;
  44231. };
  44232. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  44233. var renderCache = modelRenderCache;
  44234. var engine = this.owner.engine;
  44235. // Need to create WebGL resources for fill part?
  44236. if (this.fill) {
  44237. var vbSize = ((this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4) + 1;
  44238. var vb = new Float32Array(vbSize);
  44239. for (var i = 0; i < vbSize; i++) {
  44240. vb[i] = i;
  44241. }
  44242. renderCache.fillVB = engine.createVertexBuffer(vb);
  44243. var triCount = vbSize - 1;
  44244. var ib = new Float32Array(triCount * 3);
  44245. for (var i = 0; i < triCount; i++) {
  44246. ib[i * 3 + 0] = 0;
  44247. ib[i * 3 + 2] = i + 1;
  44248. ib[i * 3 + 1] = i + 2;
  44249. }
  44250. ib[triCount * 3 - 2] = 1;
  44251. renderCache.fillIB = engine.createIndexBuffer(ib);
  44252. renderCache.fillIndicesCount = triCount * 3;
  44253. // 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
  44254. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], true);
  44255. if (ei) {
  44256. renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44257. }
  44258. // Get the non instanced version
  44259. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], false);
  44260. renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44261. }
  44262. // Need to create WebGL resource for border part?
  44263. if (this.border) {
  44264. var vbSize = (this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4 * 2;
  44265. var vb = new Float32Array(vbSize);
  44266. for (var i = 0; i < vbSize; i++) {
  44267. vb[i] = i;
  44268. }
  44269. renderCache.borderVB = engine.createVertexBuffer(vb);
  44270. var triCount = vbSize;
  44271. var rs = triCount / 2;
  44272. var ib = new Float32Array(triCount * 3);
  44273. for (var i = 0; i < rs; i++) {
  44274. var r0 = i;
  44275. var r1 = (i + 1) % rs;
  44276. ib[i * 6 + 0] = rs + r1;
  44277. ib[i * 6 + 1] = rs + r0;
  44278. ib[i * 6 + 2] = r0;
  44279. ib[i * 6 + 3] = r1;
  44280. ib[i * 6 + 4] = rs + r1;
  44281. ib[i * 6 + 5] = r0;
  44282. }
  44283. renderCache.borderIB = engine.createIndexBuffer(ib);
  44284. renderCache.borderIndicesCount = triCount * 3;
  44285. // 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
  44286. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], true);
  44287. if (ei) {
  44288. renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44289. }
  44290. // Get the non instanced version
  44291. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], false);
  44292. renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44293. }
  44294. return renderCache;
  44295. };
  44296. // 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
  44297. Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  44298. // Fall back to default implementation if there's no round Radius
  44299. if (this._notRounded) {
  44300. _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
  44301. }
  44302. else {
  44303. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  44304. initialContentPosition.x = initialContentPosition.y = rr;
  44305. initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
  44306. initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
  44307. }
  44308. };
  44309. Rectangle2D.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  44310. // Fall back to default implementation if there's no round Radius
  44311. if (this._notRounded) {
  44312. _super.prototype._getActualSizeFromContentToRef.call(this, primSize, newPrimSize);
  44313. }
  44314. else {
  44315. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  44316. newPrimSize.copyFrom(primSize);
  44317. newPrimSize.width += rr * 2;
  44318. newPrimSize.height += rr * 2;
  44319. }
  44320. };
  44321. Rectangle2D.prototype.createInstanceDataParts = function () {
  44322. var res = new Array();
  44323. if (this.border) {
  44324. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  44325. }
  44326. if (this.fill) {
  44327. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  44328. }
  44329. return res;
  44330. };
  44331. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  44332. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  44333. return false;
  44334. }
  44335. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  44336. var d = part;
  44337. var size = this.actualSize;
  44338. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  44339. }
  44340. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  44341. var d = part;
  44342. var size = this.actualSize;
  44343. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  44344. }
  44345. return true;
  44346. };
  44347. Rectangle2D._i0 = BABYLON.Vector2.Zero();
  44348. Rectangle2D._i1 = BABYLON.Vector2.Zero();
  44349. Rectangle2D._i2 = BABYLON.Vector2.Zero();
  44350. Rectangle2D.roundSubdivisions = 16;
  44351. __decorate([
  44352. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D.actualSizeProperty = pi; }, false, true)
  44353. ], Rectangle2D.prototype, "actualSize", null);
  44354. __decorate([
  44355. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D.notRoundedProperty = pi; })
  44356. ], Rectangle2D.prototype, "notRounded", null);
  44357. __decorate([
  44358. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D.roundRadiusProperty = pi; })
  44359. ], Rectangle2D.prototype, "roundRadius", null);
  44360. Rectangle2D = __decorate([
  44361. BABYLON.className("Rectangle2D")
  44362. ], Rectangle2D);
  44363. return Rectangle2D;
  44364. })(BABYLON.Shape2D);
  44365. BABYLON.Rectangle2D = Rectangle2D;
  44366. })(BABYLON || (BABYLON = {}));
  44367. var BABYLON;
  44368. (function (BABYLON) {
  44369. var Ellipse2DRenderCache = (function (_super) {
  44370. __extends(Ellipse2DRenderCache, _super);
  44371. function Ellipse2DRenderCache(engine, modelKey) {
  44372. _super.call(this, engine, modelKey);
  44373. this.effectsReady = false;
  44374. this.fillVB = null;
  44375. this.fillIB = null;
  44376. this.fillIndicesCount = 0;
  44377. this.instancingFillAttributes = null;
  44378. this.effectFillInstanced = null;
  44379. this.effectFill = null;
  44380. this.borderVB = null;
  44381. this.borderIB = null;
  44382. this.borderIndicesCount = 0;
  44383. this.instancingBorderAttributes = null;
  44384. this.effectBorderInstanced = null;
  44385. this.effectBorder = null;
  44386. }
  44387. Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
  44388. // Do nothing if the shader is still loading/preparing
  44389. if (!this.effectsReady) {
  44390. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  44391. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  44392. return false;
  44393. }
  44394. this.effectsReady = true;
  44395. }
  44396. var canvas = instanceInfo.owner.owner;
  44397. var engine = canvas.engine;
  44398. var depthFunction = 0;
  44399. if (this.effectFill && this.effectBorder) {
  44400. depthFunction = engine.getDepthFunction();
  44401. engine.setDepthFunctionToLessOrEqual();
  44402. }
  44403. var curAlphaMode = engine.getAlphaMode();
  44404. if (this.effectFill) {
  44405. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  44406. var pid = context.groupInfoPartData[partIndex];
  44407. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44408. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  44409. }
  44410. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  44411. engine.enableEffect(effect);
  44412. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  44413. if (context.useInstancing) {
  44414. if (!this.instancingFillAttributes) {
  44415. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  44416. }
  44417. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44418. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44419. canvas._addDrawCallCount(1, context.renderMode);
  44420. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  44421. engine.draw(true, 0, this.fillIndicesCount, count);
  44422. engine.unbindInstanceAttributes();
  44423. }
  44424. else {
  44425. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44426. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44427. this.setupUniforms(effect, partIndex, pid._partData, i);
  44428. engine.draw(true, 0, this.fillIndicesCount);
  44429. }
  44430. }
  44431. }
  44432. if (this.effectBorder) {
  44433. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  44434. var pid = context.groupInfoPartData[partIndex];
  44435. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44436. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  44437. }
  44438. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  44439. engine.enableEffect(effect);
  44440. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  44441. if (context.useInstancing) {
  44442. if (!this.instancingBorderAttributes) {
  44443. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  44444. }
  44445. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44446. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44447. canvas._addDrawCallCount(1, context.renderMode);
  44448. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  44449. engine.draw(true, 0, this.borderIndicesCount, count);
  44450. engine.unbindInstanceAttributes();
  44451. }
  44452. else {
  44453. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44454. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44455. this.setupUniforms(effect, partIndex, pid._partData, i);
  44456. engine.draw(true, 0, this.borderIndicesCount);
  44457. }
  44458. }
  44459. }
  44460. engine.setAlphaMode(curAlphaMode, true);
  44461. if (this.effectFill && this.effectBorder) {
  44462. engine.setDepthFunction(depthFunction);
  44463. }
  44464. return true;
  44465. };
  44466. Ellipse2DRenderCache.prototype.dispose = function () {
  44467. if (!_super.prototype.dispose.call(this)) {
  44468. return false;
  44469. }
  44470. if (this.fillVB) {
  44471. this._engine._releaseBuffer(this.fillVB);
  44472. this.fillVB = null;
  44473. }
  44474. if (this.fillIB) {
  44475. this._engine._releaseBuffer(this.fillIB);
  44476. this.fillIB = null;
  44477. }
  44478. this.effectFill = null;
  44479. this.effectFillInstanced = null;
  44480. this.effectBorder = null;
  44481. this.effectBorderInstanced = null;
  44482. if (this.borderVB) {
  44483. this._engine._releaseBuffer(this.borderVB);
  44484. this.borderVB = null;
  44485. }
  44486. if (this.borderIB) {
  44487. this._engine._releaseBuffer(this.borderIB);
  44488. this.borderIB = null;
  44489. }
  44490. return true;
  44491. };
  44492. return Ellipse2DRenderCache;
  44493. })(BABYLON.ModelRenderCache);
  44494. BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
  44495. var Ellipse2DInstanceData = (function (_super) {
  44496. __extends(Ellipse2DInstanceData, _super);
  44497. function Ellipse2DInstanceData(partId) {
  44498. _super.call(this, partId, 1);
  44499. }
  44500. Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
  44501. get: function () {
  44502. return null;
  44503. },
  44504. enumerable: true,
  44505. configurable: true
  44506. });
  44507. __decorate([
  44508. BABYLON.instanceData()
  44509. ], Ellipse2DInstanceData.prototype, "properties", null);
  44510. return Ellipse2DInstanceData;
  44511. })(BABYLON.Shape2DInstanceData);
  44512. BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
  44513. var Ellipse2D = (function (_super) {
  44514. __extends(Ellipse2D, _super);
  44515. /**
  44516. * Create an Ellipse 2D Shape primitive
  44517. * @param settings a combination of settings, possible ones are
  44518. * - 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)
  44519. * - children: an array of direct children
  44520. * - id: a text identifier, for information purpose
  44521. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  44522. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  44523. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  44524. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  44525. * - zOrder: override the zOrder with the specified value
  44526. * - origin: define the normalized origin point location, default [0.5;0.5]
  44527. * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
  44528. * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
  44529. * - 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)
  44530. * - 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)
  44531. * - borderThickness: the thickness of the drawn border, default is 1.
  44532. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  44533. * - 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!
  44534. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44535. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44536. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44537. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44538. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  44539. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  44540. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  44541. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  44542. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44543. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44544. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44545. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44546. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  44547. */
  44548. function Ellipse2D(settings) {
  44549. // Avoid checking every time if the object exists
  44550. if (settings == null) {
  44551. settings = {};
  44552. }
  44553. _super.call(this, settings);
  44554. if (settings.size != null) {
  44555. this.size = settings.size;
  44556. }
  44557. else if (settings.width || settings.height) {
  44558. var size = new BABYLON.Size(settings.width, settings.height);
  44559. this.size = size;
  44560. }
  44561. var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
  44562. this.subdivisions = sub;
  44563. }
  44564. Object.defineProperty(Ellipse2D.prototype, "actualSize", {
  44565. get: function () {
  44566. if (this._actualSize) {
  44567. return this._actualSize;
  44568. }
  44569. return this.size;
  44570. },
  44571. set: function (value) {
  44572. this._actualSize = value;
  44573. },
  44574. enumerable: true,
  44575. configurable: true
  44576. });
  44577. Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
  44578. get: function () {
  44579. return this._subdivisions;
  44580. },
  44581. set: function (value) {
  44582. this._subdivisions = value;
  44583. },
  44584. enumerable: true,
  44585. configurable: true
  44586. });
  44587. Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
  44588. var w = this.size.width / 2;
  44589. var h = this.size.height / 2;
  44590. var x = intersectInfo._localPickPosition.x - w;
  44591. var y = intersectInfo._localPickPosition.y - h;
  44592. return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
  44593. };
  44594. Ellipse2D.prototype.updateLevelBoundingInfo = function () {
  44595. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  44596. };
  44597. Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
  44598. var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
  44599. return renderCache;
  44600. };
  44601. Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  44602. var renderCache = modelRenderCache;
  44603. var engine = this.owner.engine;
  44604. // Need to create WebGL resources for fill part?
  44605. if (this.fill) {
  44606. var vbSize = this.subdivisions + 1;
  44607. var vb = new Float32Array(vbSize);
  44608. for (var i = 0; i < vbSize; i++) {
  44609. vb[i] = i;
  44610. }
  44611. renderCache.fillVB = engine.createVertexBuffer(vb);
  44612. var triCount = vbSize - 1;
  44613. var ib = new Float32Array(triCount * 3);
  44614. for (var i = 0; i < triCount; i++) {
  44615. ib[i * 3 + 0] = 0;
  44616. ib[i * 3 + 2] = i + 1;
  44617. ib[i * 3 + 1] = i + 2;
  44618. }
  44619. ib[triCount * 3 - 2] = 1;
  44620. renderCache.fillIB = engine.createIndexBuffer(ib);
  44621. renderCache.fillIndicesCount = triCount * 3;
  44622. // 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
  44623. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], true);
  44624. if (ei) {
  44625. renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  44626. }
  44627. // Get the non instanced version
  44628. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], false);
  44629. renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  44630. }
  44631. // Need to create WebGL resource for border part?
  44632. if (this.border) {
  44633. var vbSize = this.subdivisions * 2;
  44634. var vb = new Float32Array(vbSize);
  44635. for (var i = 0; i < vbSize; i++) {
  44636. vb[i] = i;
  44637. }
  44638. renderCache.borderVB = engine.createVertexBuffer(vb);
  44639. var triCount = vbSize;
  44640. var rs = triCount / 2;
  44641. var ib = new Float32Array(triCount * 3);
  44642. for (var i = 0; i < rs; i++) {
  44643. var r0 = i;
  44644. var r1 = (i + 1) % rs;
  44645. ib[i * 6 + 0] = rs + r1;
  44646. ib[i * 6 + 1] = rs + r0;
  44647. ib[i * 6 + 2] = r0;
  44648. ib[i * 6 + 3] = r1;
  44649. ib[i * 6 + 4] = rs + r1;
  44650. ib[i * 6 + 5] = r0;
  44651. }
  44652. renderCache.borderIB = engine.createIndexBuffer(ib);
  44653. renderCache.borderIndicesCount = (triCount * 3);
  44654. // 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
  44655. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], true);
  44656. if (ei) {
  44657. renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44658. }
  44659. // Get the non instanced version
  44660. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], false);
  44661. renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44662. }
  44663. return renderCache;
  44664. };
  44665. Ellipse2D.prototype.createInstanceDataParts = function () {
  44666. var res = new Array();
  44667. if (this.border) {
  44668. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  44669. }
  44670. if (this.fill) {
  44671. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  44672. }
  44673. return res;
  44674. };
  44675. Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
  44676. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  44677. return false;
  44678. }
  44679. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  44680. var d = part;
  44681. var size = this.actualSize;
  44682. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  44683. }
  44684. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  44685. var d = part;
  44686. var size = this.actualSize;
  44687. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  44688. }
  44689. return true;
  44690. };
  44691. __decorate([
  44692. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Ellipse2D.acutalSizeProperty = pi; }, false, true)
  44693. ], Ellipse2D.prototype, "actualSize", null);
  44694. __decorate([
  44695. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D.subdivisionsProperty = pi; })
  44696. ], Ellipse2D.prototype, "subdivisions", null);
  44697. Ellipse2D = __decorate([
  44698. BABYLON.className("Ellipse2D")
  44699. ], Ellipse2D);
  44700. return Ellipse2D;
  44701. })(BABYLON.Shape2D);
  44702. BABYLON.Ellipse2D = Ellipse2D;
  44703. })(BABYLON || (BABYLON = {}));
  44704. var BABYLON;
  44705. (function (BABYLON) {
  44706. var Sprite2DRenderCache = (function (_super) {
  44707. __extends(Sprite2DRenderCache, _super);
  44708. function Sprite2DRenderCache() {
  44709. _super.apply(this, arguments);
  44710. this.effectsReady = false;
  44711. this.vb = null;
  44712. this.ib = null;
  44713. this.instancingAttributes = null;
  44714. this.texture = null;
  44715. this.effect = null;
  44716. this.effectInstanced = null;
  44717. }
  44718. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  44719. // Do nothing if the shader is still loading/preparing
  44720. if (!this.effectsReady) {
  44721. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  44722. return false;
  44723. }
  44724. this.effectsReady = true;
  44725. }
  44726. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  44727. var canvas = instanceInfo.owner.owner;
  44728. var engine = canvas.engine;
  44729. var cur = engine.getAlphaMode();
  44730. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  44731. engine.enableEffect(effect);
  44732. effect.setTexture("diffuseSampler", this.texture);
  44733. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  44734. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44735. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  44736. }
  44737. var pid = context.groupInfoPartData[0];
  44738. if (context.useInstancing) {
  44739. if (!this.instancingAttributes) {
  44740. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
  44741. }
  44742. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  44743. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44744. canvas._addDrawCallCount(1, context.renderMode);
  44745. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  44746. engine.draw(true, 0, 6, count);
  44747. engine.unbindInstanceAttributes();
  44748. }
  44749. else {
  44750. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44751. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44752. this.setupUniforms(effect, 0, pid._partData, i);
  44753. engine.draw(true, 0, 6);
  44754. }
  44755. }
  44756. engine.setAlphaMode(cur, true);
  44757. return true;
  44758. };
  44759. Sprite2DRenderCache.prototype.dispose = function () {
  44760. if (!_super.prototype.dispose.call(this)) {
  44761. return false;
  44762. }
  44763. if (this.vb) {
  44764. this._engine._releaseBuffer(this.vb);
  44765. this.vb = null;
  44766. }
  44767. if (this.ib) {
  44768. this._engine._releaseBuffer(this.ib);
  44769. this.ib = null;
  44770. }
  44771. if (this.texture) {
  44772. this.texture.dispose();
  44773. this.texture = null;
  44774. }
  44775. this.effect = null;
  44776. this.effectInstanced = null;
  44777. return true;
  44778. };
  44779. return Sprite2DRenderCache;
  44780. })(BABYLON.ModelRenderCache);
  44781. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  44782. var Sprite2DInstanceData = (function (_super) {
  44783. __extends(Sprite2DInstanceData, _super);
  44784. function Sprite2DInstanceData(partId) {
  44785. _super.call(this, partId, 1);
  44786. }
  44787. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  44788. get: function () {
  44789. return null;
  44790. },
  44791. enumerable: true,
  44792. configurable: true
  44793. });
  44794. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  44795. get: function () {
  44796. return null;
  44797. },
  44798. enumerable: true,
  44799. configurable: true
  44800. });
  44801. Object.defineProperty(Sprite2DInstanceData.prototype, "scaleFactor", {
  44802. get: function () {
  44803. return null;
  44804. },
  44805. enumerable: true,
  44806. configurable: true
  44807. });
  44808. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  44809. get: function () {
  44810. return null;
  44811. },
  44812. enumerable: true,
  44813. configurable: true
  44814. });
  44815. Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
  44816. // 3 floats being:
  44817. // - x: frame number to display
  44818. // - y: invertY setting
  44819. // - z: alignToPixel setting
  44820. get: function () {
  44821. return null;
  44822. },
  44823. enumerable: true,
  44824. configurable: true
  44825. });
  44826. __decorate([
  44827. BABYLON.instanceData()
  44828. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  44829. __decorate([
  44830. BABYLON.instanceData()
  44831. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  44832. __decorate([
  44833. BABYLON.instanceData()
  44834. ], Sprite2DInstanceData.prototype, "scaleFactor", null);
  44835. __decorate([
  44836. BABYLON.instanceData()
  44837. ], Sprite2DInstanceData.prototype, "textureSize", null);
  44838. __decorate([
  44839. BABYLON.instanceData()
  44840. ], Sprite2DInstanceData.prototype, "properties", null);
  44841. return Sprite2DInstanceData;
  44842. })(BABYLON.InstanceDataBase);
  44843. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  44844. var Sprite2D = (function (_super) {
  44845. __extends(Sprite2D, _super);
  44846. /**
  44847. * Create an 2D Sprite primitive
  44848. * @param texture the texture that stores the sprite to render
  44849. * @param settings a combination of settings, possible ones are
  44850. * - 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)
  44851. * - children: an array of direct children
  44852. * - id a text identifier, for information purpose
  44853. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  44854. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  44855. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  44856. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  44857. * - zOrder: override the zOrder with the specified value
  44858. * - origin: define the normalized origin point location, default [0.5;0.5]
  44859. * - spriteSize: the size of the sprite (in pixels), if null the size of the given texture will be used, default is null.
  44860. * - spriteLocation: the location (in pixels) in the texture of the top/left corner of the Sprite to display, default is null (0,0)
  44861. * - 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.
  44862. * - invertY: if true the texture Y will be inverted, default is false.
  44863. * - 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.
  44864. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  44865. * - 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!
  44866. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44867. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44868. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44869. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44870. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  44871. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  44872. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  44873. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  44874. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44875. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44876. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44877. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44878. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  44879. */
  44880. function Sprite2D(texture, settings) {
  44881. var _this = this;
  44882. if (!settings) {
  44883. settings = {};
  44884. }
  44885. _super.call(this, settings);
  44886. this.texture = texture;
  44887. this.texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44888. this.texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44889. this.size = settings.spriteSize;
  44890. this.spriteLocation = settings.spriteLocation || new BABYLON.Vector2(0, 0);
  44891. this.spriteScaleFactor = settings.spriteScaleFactor || new BABYLON.Vector2(1, 1);
  44892. this.spriteFrame = 0;
  44893. this.invertY = (settings.invertY == null) ? false : settings.invertY;
  44894. this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  44895. this.isTransparent = true;
  44896. if (settings.spriteSize == null || !texture.isReady()) {
  44897. if (texture.isReady()) {
  44898. this.size = texture.getBaseSize();
  44899. }
  44900. else {
  44901. texture.onLoadObservable.add(function () {
  44902. if (settings.spriteSize == null) {
  44903. _this.size = texture.getBaseSize();
  44904. }
  44905. _this._positioningDirty();
  44906. _this._instanceDirtyFlags |= Sprite2D.textureProperty.flagId; // To make sure the sprite is issued again for render
  44907. });
  44908. }
  44909. }
  44910. }
  44911. Object.defineProperty(Sprite2D.prototype, "texture", {
  44912. get: function () {
  44913. return this._texture;
  44914. },
  44915. set: function (value) {
  44916. this._texture = value;
  44917. },
  44918. enumerable: true,
  44919. configurable: true
  44920. });
  44921. Object.defineProperty(Sprite2D.prototype, "actualSize", {
  44922. get: function () {
  44923. if (this._actualSize) {
  44924. return this._actualSize;
  44925. }
  44926. return this.size;
  44927. },
  44928. set: function (value) {
  44929. this._actualSize = value;
  44930. },
  44931. enumerable: true,
  44932. configurable: true
  44933. });
  44934. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  44935. get: function () {
  44936. return this._location;
  44937. },
  44938. set: function (value) {
  44939. this._location = value;
  44940. },
  44941. enumerable: true,
  44942. configurable: true
  44943. });
  44944. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  44945. get: function () {
  44946. return this._spriteFrame;
  44947. },
  44948. set: function (value) {
  44949. this._spriteFrame = value;
  44950. },
  44951. enumerable: true,
  44952. configurable: true
  44953. });
  44954. Object.defineProperty(Sprite2D.prototype, "invertY", {
  44955. get: function () {
  44956. return this._invertY;
  44957. },
  44958. set: function (value) {
  44959. this._invertY = value;
  44960. },
  44961. enumerable: true,
  44962. configurable: true
  44963. });
  44964. Object.defineProperty(Sprite2D.prototype, "spriteScaleFactor", {
  44965. get: function () {
  44966. return this._spriteScaleFactor;
  44967. },
  44968. set: function (value) {
  44969. this._spriteScaleFactor = value;
  44970. },
  44971. enumerable: true,
  44972. configurable: true
  44973. });
  44974. Object.defineProperty(Sprite2D.prototype, "alignToPixel", {
  44975. /**
  44976. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  44977. */
  44978. get: function () {
  44979. return this._alignToPixel;
  44980. },
  44981. set: function (value) {
  44982. this._alignToPixel = value;
  44983. },
  44984. enumerable: true,
  44985. configurable: true
  44986. });
  44987. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  44988. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
  44989. };
  44990. /**
  44991. * Get the animatable array (see http://doc.babylonjs.com/tutorials/Animations)
  44992. */
  44993. Sprite2D.prototype.getAnimatables = function () {
  44994. var res = new Array();
  44995. if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
  44996. res.push(this.texture);
  44997. }
  44998. return res;
  44999. };
  45000. Sprite2D.prototype.levelIntersect = function (intersectInfo) {
  45001. // 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
  45002. return true;
  45003. };
  45004. Sprite2D._createCachedCanvasSprite = function (owner, texture, size, pos) {
  45005. var sprite = new Sprite2D(texture, { parent: owner, id: "__cachedCanvasSprite__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), spriteSize: size, spriteLocation: pos, alignToPixel: true });
  45006. return sprite;
  45007. };
  45008. Sprite2D.prototype.createModelRenderCache = function (modelKey) {
  45009. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
  45010. return renderCache;
  45011. };
  45012. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  45013. var renderCache = modelRenderCache;
  45014. var engine = this.owner.engine;
  45015. var vb = new Float32Array(4);
  45016. for (var i = 0; i < 4; i++) {
  45017. vb[i] = i;
  45018. }
  45019. renderCache.vb = engine.createVertexBuffer(vb);
  45020. var ib = new Float32Array(6);
  45021. ib[0] = 0;
  45022. ib[1] = 2;
  45023. ib[2] = 1;
  45024. ib[3] = 0;
  45025. ib[4] = 3;
  45026. ib[5] = 2;
  45027. renderCache.ib = engine.createIndexBuffer(ib);
  45028. renderCache.texture = this.texture;
  45029. // 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
  45030. var ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], true);
  45031. if (ei) {
  45032. renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  45033. }
  45034. ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], false);
  45035. renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  45036. return renderCache;
  45037. };
  45038. Sprite2D.prototype.createInstanceDataParts = function () {
  45039. return [new Sprite2DInstanceData(Sprite2D.SPRITE2D_MAINPARTID)];
  45040. };
  45041. Sprite2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  45042. Sprite2D.layoutConstructMode = true;
  45043. };
  45044. // if obj contains something, we restore the _text property
  45045. Sprite2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  45046. Sprite2D.layoutConstructMode = false;
  45047. };
  45048. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  45049. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  45050. return false;
  45051. }
  45052. if (!this.texture.isReady() && !Sprite2D.layoutConstructMode) {
  45053. return false;
  45054. }
  45055. if (part.id === Sprite2D.SPRITE2D_MAINPARTID) {
  45056. var d = this._instanceDataParts[0];
  45057. if (Sprite2D.layoutConstructMode) {
  45058. d.topLeftUV = BABYLON.Vector2.Zero();
  45059. d.sizeUV = BABYLON.Vector2.Zero();
  45060. d.properties = BABYLON.Vector3.Zero();
  45061. d.textureSize = BABYLON.Vector2.Zero();
  45062. d.scaleFactor = BABYLON.Vector2.Zero();
  45063. }
  45064. else {
  45065. var ts = this.texture.getBaseSize();
  45066. var sl = this.spriteLocation;
  45067. var ss = this.actualSize;
  45068. var ssf = this.spriteScaleFactor;
  45069. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  45070. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  45071. d.sizeUV = suv;
  45072. d.scaleFactor = ssf;
  45073. Sprite2D._prop.x = this.spriteFrame;
  45074. Sprite2D._prop.y = this.invertY ? 1 : 0;
  45075. Sprite2D._prop.z = this.alignToPixel ? 1 : 0;
  45076. d.properties = Sprite2D._prop;
  45077. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  45078. }
  45079. }
  45080. return true;
  45081. };
  45082. Sprite2D.SPRITE2D_MAINPARTID = 1;
  45083. Sprite2D._prop = BABYLON.Vector3.Zero();
  45084. Sprite2D.layoutConstructMode = false;
  45085. __decorate([
  45086. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D.textureProperty = pi; })
  45087. ], Sprite2D.prototype, "texture", null);
  45088. __decorate([
  45089. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D.actualSizeProperty = pi; }, false, true)
  45090. ], Sprite2D.prototype, "actualSize", null);
  45091. __decorate([
  45092. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Sprite2D.spriteLocationProperty = pi; })
  45093. ], Sprite2D.prototype, "spriteLocation", null);
  45094. __decorate([
  45095. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D.spriteFrameProperty = pi; })
  45096. ], Sprite2D.prototype, "spriteFrame", null);
  45097. __decorate([
  45098. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D.invertYProperty = pi; })
  45099. ], Sprite2D.prototype, "invertY", null);
  45100. __decorate([
  45101. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Sprite2D.spriteScaleFactorProperty = pi; })
  45102. ], Sprite2D.prototype, "spriteScaleFactor", null);
  45103. Sprite2D = __decorate([
  45104. BABYLON.className("Sprite2D")
  45105. ], Sprite2D);
  45106. return Sprite2D;
  45107. })(BABYLON.RenderablePrim2D);
  45108. BABYLON.Sprite2D = Sprite2D;
  45109. })(BABYLON || (BABYLON = {}));
  45110. var BABYLON;
  45111. (function (BABYLON) {
  45112. var Text2DRenderCache = (function (_super) {
  45113. __extends(Text2DRenderCache, _super);
  45114. function Text2DRenderCache() {
  45115. _super.apply(this, arguments);
  45116. this.effectsReady = false;
  45117. this.vb = null;
  45118. this.ib = null;
  45119. this.instancingAttributes = null;
  45120. this.fontTexture = null;
  45121. this.effect = null;
  45122. this.effectInstanced = null;
  45123. }
  45124. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  45125. // Do nothing if the shader is still loading/preparing
  45126. if (!this.effectsReady) {
  45127. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  45128. return false;
  45129. }
  45130. this.effectsReady = true;
  45131. }
  45132. var canvas = instanceInfo.owner.owner;
  45133. var engine = canvas.engine;
  45134. this.fontTexture.update();
  45135. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  45136. engine.enableEffect(effect);
  45137. effect.setTexture("diffuseSampler", this.fontTexture);
  45138. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  45139. var curAlphaMode = engine.getAlphaMode();
  45140. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45141. var pid = context.groupInfoPartData[0];
  45142. if (context.useInstancing) {
  45143. if (!this.instancingAttributes) {
  45144. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
  45145. }
  45146. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  45147. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45148. canvas._addDrawCallCount(1, context.renderMode);
  45149. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  45150. engine.draw(true, 0, 6, count);
  45151. engine.unbindInstanceAttributes();
  45152. }
  45153. else {
  45154. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45155. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45156. this.setupUniforms(effect, 0, pid._partData, i);
  45157. engine.draw(true, 0, 6);
  45158. }
  45159. }
  45160. engine.setAlphaMode(curAlphaMode, true);
  45161. return true;
  45162. };
  45163. Text2DRenderCache.prototype.dispose = function () {
  45164. if (!_super.prototype.dispose.call(this)) {
  45165. return false;
  45166. }
  45167. if (this.vb) {
  45168. this._engine._releaseBuffer(this.vb);
  45169. this.vb = null;
  45170. }
  45171. if (this.ib) {
  45172. this._engine._releaseBuffer(this.ib);
  45173. this.ib = null;
  45174. }
  45175. if (this.fontTexture) {
  45176. this.fontTexture.decCachedFontTextureCounter();
  45177. this.fontTexture = null;
  45178. }
  45179. this.effect = null;
  45180. this.effectInstanced = null;
  45181. return true;
  45182. };
  45183. return Text2DRenderCache;
  45184. })(BABYLON.ModelRenderCache);
  45185. BABYLON.Text2DRenderCache = Text2DRenderCache;
  45186. var Text2DInstanceData = (function (_super) {
  45187. __extends(Text2DInstanceData, _super);
  45188. function Text2DInstanceData(partId, dataElementCount) {
  45189. _super.call(this, partId, dataElementCount);
  45190. }
  45191. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  45192. get: function () {
  45193. return null;
  45194. },
  45195. enumerable: true,
  45196. configurable: true
  45197. });
  45198. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  45199. get: function () {
  45200. return null;
  45201. },
  45202. enumerable: true,
  45203. configurable: true
  45204. });
  45205. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  45206. get: function () {
  45207. return null;
  45208. },
  45209. enumerable: true,
  45210. configurable: true
  45211. });
  45212. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  45213. get: function () {
  45214. return null;
  45215. },
  45216. enumerable: true,
  45217. configurable: true
  45218. });
  45219. Object.defineProperty(Text2DInstanceData.prototype, "superSampleFactor", {
  45220. get: function () {
  45221. return null;
  45222. },
  45223. enumerable: true,
  45224. configurable: true
  45225. });
  45226. __decorate([
  45227. BABYLON.instanceData()
  45228. ], Text2DInstanceData.prototype, "topLeftUV", null);
  45229. __decorate([
  45230. BABYLON.instanceData()
  45231. ], Text2DInstanceData.prototype, "sizeUV", null);
  45232. __decorate([
  45233. BABYLON.instanceData()
  45234. ], Text2DInstanceData.prototype, "textureSize", null);
  45235. __decorate([
  45236. BABYLON.instanceData()
  45237. ], Text2DInstanceData.prototype, "color", null);
  45238. __decorate([
  45239. BABYLON.instanceData()
  45240. ], Text2DInstanceData.prototype, "superSampleFactor", null);
  45241. return Text2DInstanceData;
  45242. })(BABYLON.InstanceDataBase);
  45243. BABYLON.Text2DInstanceData = Text2DInstanceData;
  45244. var Text2D = (function (_super) {
  45245. __extends(Text2D, _super);
  45246. /**
  45247. * Create a Text primitive
  45248. * @param text the text to display
  45249. * @param settings a combination of settings, possible ones are
  45250. * - 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)
  45251. * - children: an array of direct children
  45252. * - id a text identifier, for information purpose
  45253. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  45254. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  45255. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  45256. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  45257. * - zOrder: override the zOrder with the specified value
  45258. * - origin: define the normalized origin point location, default [0.5;0.5]
  45259. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  45260. * - 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.
  45261. * - defaultColor: the color by default to apply on each letter of the text to display, default is plain white.
  45262. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  45263. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  45264. * - isVisible: true if the text must be visible, false for hidden. Default is true.
  45265. * - 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!
  45266. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45267. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45268. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45269. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45270. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  45271. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  45272. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  45273. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  45274. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45275. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45276. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45277. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45278. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  45279. */
  45280. function Text2D(text, settings) {
  45281. if (!settings) {
  45282. settings = {};
  45283. }
  45284. _super.call(this, settings);
  45285. this.fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
  45286. this._fontSuperSample = (settings.fontSuperSample != null && settings.fontSuperSample);
  45287. this.defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor;
  45288. this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
  45289. this._textSize = null;
  45290. this.text = text;
  45291. this.size = (settings.size == null) ? null : settings.size;
  45292. this.isTransparent = true;
  45293. }
  45294. Object.defineProperty(Text2D.prototype, "fontName", {
  45295. get: function () {
  45296. return this._fontName;
  45297. },
  45298. set: function (value) {
  45299. if (this._fontName) {
  45300. throw new Error("Font Name change is not supported right now.");
  45301. }
  45302. this._fontName = value;
  45303. },
  45304. enumerable: true,
  45305. configurable: true
  45306. });
  45307. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  45308. get: function () {
  45309. return this._defaultFontColor;
  45310. },
  45311. set: function (value) {
  45312. this._defaultFontColor = value;
  45313. },
  45314. enumerable: true,
  45315. configurable: true
  45316. });
  45317. Object.defineProperty(Text2D.prototype, "text", {
  45318. get: function () {
  45319. return this._text;
  45320. },
  45321. set: function (value) {
  45322. this._text = value;
  45323. this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
  45324. this._size = null;
  45325. this._updateCharCount();
  45326. // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
  45327. var s = this.textSize;
  45328. },
  45329. enumerable: true,
  45330. configurable: true
  45331. });
  45332. Object.defineProperty(Text2D.prototype, "size", {
  45333. get: function () {
  45334. if (this._size != null) {
  45335. return this._size;
  45336. }
  45337. return this.textSize;
  45338. },
  45339. set: function (value) {
  45340. this._size = value;
  45341. },
  45342. enumerable: true,
  45343. configurable: true
  45344. });
  45345. Object.defineProperty(Text2D.prototype, "actualSize", {
  45346. /**
  45347. * Get the actual size of the Text2D primitive
  45348. */
  45349. get: function () {
  45350. if (this._actualSize) {
  45351. return this._actualSize;
  45352. }
  45353. return this.size;
  45354. },
  45355. enumerable: true,
  45356. configurable: true
  45357. });
  45358. Object.defineProperty(Text2D.prototype, "textSize", {
  45359. /**
  45360. * Get the area that bounds the text associated to the primitive
  45361. */
  45362. get: function () {
  45363. if (!this._textSize) {
  45364. if (this.owner) {
  45365. var newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  45366. if (!newSize.equals(this._textSize)) {
  45367. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  45368. this._positioningDirty();
  45369. }
  45370. this._textSize = newSize;
  45371. }
  45372. else {
  45373. return Text2D.nullSize;
  45374. }
  45375. }
  45376. return this._textSize;
  45377. },
  45378. enumerable: true,
  45379. configurable: true
  45380. });
  45381. Object.defineProperty(Text2D.prototype, "fontTexture", {
  45382. get: function () {
  45383. if (this._fontTexture) {
  45384. return this._fontTexture;
  45385. }
  45386. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  45387. return this._fontTexture;
  45388. },
  45389. enumerable: true,
  45390. configurable: true
  45391. });
  45392. /**
  45393. * Dispose the primitive, remove it from its parent
  45394. */
  45395. Text2D.prototype.dispose = function () {
  45396. if (!_super.prototype.dispose.call(this)) {
  45397. return false;
  45398. }
  45399. if (this._fontTexture) {
  45400. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  45401. this._fontTexture = null;
  45402. }
  45403. return true;
  45404. };
  45405. Text2D.prototype.updateLevelBoundingInfo = function () {
  45406. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  45407. };
  45408. Text2D.prototype.levelIntersect = function (intersectInfo) {
  45409. // 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...
  45410. return true;
  45411. };
  45412. Text2D.prototype.createModelRenderCache = function (modelKey) {
  45413. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
  45414. return renderCache;
  45415. };
  45416. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  45417. var renderCache = modelRenderCache;
  45418. var engine = this.owner.engine;
  45419. renderCache.fontTexture = this.fontTexture;
  45420. renderCache.fontTexture.incCachedFontTextureCounter();
  45421. var vb = new Float32Array(4);
  45422. for (var i = 0; i < 4; i++) {
  45423. vb[i] = i;
  45424. }
  45425. renderCache.vb = engine.createVertexBuffer(vb);
  45426. var ib = new Float32Array(6);
  45427. ib[0] = 0;
  45428. ib[1] = 2;
  45429. ib[2] = 1;
  45430. ib[3] = 0;
  45431. ib[4] = 3;
  45432. ib[5] = 2;
  45433. renderCache.ib = engine.createIndexBuffer(ib);
  45434. // 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
  45435. var ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], true);
  45436. if (ei) {
  45437. renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  45438. }
  45439. ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], false);
  45440. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  45441. return renderCache;
  45442. };
  45443. Text2D.prototype.createInstanceDataParts = function () {
  45444. return [new Text2DInstanceData(Text2D.TEXT2D_MAINPARTID, this._charCount)];
  45445. };
  45446. // Looks like a hack!? Yes! Because that's what it is!
  45447. // 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
  45448. // 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)
  45449. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  45450. if (!this._charCount) {
  45451. var curText = this._text;
  45452. this.text = "A";
  45453. return curText;
  45454. }
  45455. };
  45456. // if obj contains something, we restore the _text property
  45457. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  45458. if (obj !== undefined) {
  45459. this.text = obj;
  45460. }
  45461. };
  45462. Text2D.prototype.refreshInstanceDataPart = function (part) {
  45463. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  45464. return false;
  45465. }
  45466. if (part.id === Text2D.TEXT2D_MAINPARTID) {
  45467. var d = part;
  45468. var texture = this.fontTexture;
  45469. var superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
  45470. var ts = texture.getSize();
  45471. var offset = BABYLON.Vector2.Zero();
  45472. var lh = this.fontTexture.lineHeight;
  45473. 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
  45474. var charxpos = 0;
  45475. d.dataElementCount = this._charCount;
  45476. d.curElement = 0;
  45477. for (var _i = 0, _a = this.text; _i < _a.length; _i++) {
  45478. var char = _a[_i];
  45479. // Line feed
  45480. if (char === "\n") {
  45481. offset.x = 0;
  45482. offset.y -= texture.lineHeight;
  45483. }
  45484. // Tabulation ?
  45485. if (char === "\t") {
  45486. var nextPos = charxpos + this._tabulationSize;
  45487. nextPos = nextPos - (nextPos % this._tabulationSize);
  45488. offset.x += (nextPos - charxpos) * texture.spaceWidth;
  45489. charxpos = nextPos;
  45490. continue;
  45491. }
  45492. if (char < " ") {
  45493. continue;
  45494. }
  45495. this.updateInstanceDataPart(d, offset);
  45496. var ci = texture.getChar(char);
  45497. offset.x += ci.charWidth;
  45498. d.topLeftUV = ci.topLeftUV;
  45499. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  45500. d.sizeUV = suv;
  45501. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  45502. d.color = this.defaultFontColor;
  45503. d.superSampleFactor = superSampleFactor;
  45504. ++d.curElement;
  45505. }
  45506. }
  45507. return true;
  45508. };
  45509. Text2D.prototype._updateCharCount = function () {
  45510. var count = 0;
  45511. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  45512. var char = _a[_i];
  45513. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  45514. continue;
  45515. }
  45516. ++count;
  45517. }
  45518. this._charCount = count;
  45519. };
  45520. Text2D.TEXT2D_MAINPARTID = 1;
  45521. __decorate([
  45522. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D.fontProperty = pi; }, false, true)
  45523. ], Text2D.prototype, "fontName", null);
  45524. __decorate([
  45525. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D.defaultFontColorProperty = pi; })
  45526. ], Text2D.prototype, "defaultFontColor", null);
  45527. __decorate([
  45528. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D.textProperty = pi; }, false, true)
  45529. ], Text2D.prototype, "text", null);
  45530. __decorate([
  45531. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D.sizeProperty = pi; })
  45532. ], Text2D.prototype, "size", null);
  45533. Text2D = __decorate([
  45534. BABYLON.className("Text2D")
  45535. ], Text2D);
  45536. return Text2D;
  45537. })(BABYLON.RenderablePrim2D);
  45538. BABYLON.Text2D = Text2D;
  45539. })(BABYLON || (BABYLON = {}));
  45540. var BABYLON;
  45541. (function (BABYLON) {
  45542. var Lines2DRenderCache = (function (_super) {
  45543. __extends(Lines2DRenderCache, _super);
  45544. function Lines2DRenderCache(engine, modelKey) {
  45545. _super.call(this, engine, modelKey);
  45546. this.effectsReady = false;
  45547. this.fillVB = null;
  45548. this.fillIB = null;
  45549. this.fillIndicesCount = 0;
  45550. this.instancingFillAttributes = null;
  45551. this.effectFill = null;
  45552. this.effectFillInstanced = null;
  45553. this.borderVB = null;
  45554. this.borderIB = null;
  45555. this.borderIndicesCount = 0;
  45556. this.instancingBorderAttributes = null;
  45557. this.effectBorder = null;
  45558. this.effectBorderInstanced = null;
  45559. }
  45560. Lines2DRenderCache.prototype.render = function (instanceInfo, context) {
  45561. // Do nothing if the shader is still loading/preparing
  45562. if (!this.effectsReady) {
  45563. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  45564. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  45565. return false;
  45566. }
  45567. this.effectsReady = true;
  45568. }
  45569. var canvas = instanceInfo.owner.owner;
  45570. var engine = canvas.engine;
  45571. var depthFunction = 0;
  45572. if (this.effectFill && this.effectBorder) {
  45573. depthFunction = engine.getDepthFunction();
  45574. engine.setDepthFunctionToLessOrEqual();
  45575. }
  45576. var curAlphaMode = engine.getAlphaMode();
  45577. if (this.effectFill) {
  45578. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  45579. var pid = context.groupInfoPartData[partIndex];
  45580. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45581. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45582. }
  45583. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  45584. engine.enableEffect(effect);
  45585. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [2], 2 * 4, effect);
  45586. if (context.useInstancing) {
  45587. if (!this.instancingFillAttributes) {
  45588. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  45589. }
  45590. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  45591. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45592. canvas._addDrawCallCount(1, context.renderMode);
  45593. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  45594. engine.draw(true, 0, this.fillIndicesCount, count);
  45595. engine.unbindInstanceAttributes();
  45596. }
  45597. else {
  45598. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45599. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45600. this.setupUniforms(effect, partIndex, pid._partData, i);
  45601. engine.draw(true, 0, this.fillIndicesCount);
  45602. }
  45603. }
  45604. }
  45605. if (this.effectBorder) {
  45606. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  45607. var pid = context.groupInfoPartData[partIndex];
  45608. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45609. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45610. }
  45611. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  45612. engine.enableEffect(effect);
  45613. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [2], 2 * 4, effect);
  45614. if (context.useInstancing) {
  45615. if (!this.instancingBorderAttributes) {
  45616. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  45617. }
  45618. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  45619. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45620. canvas._addDrawCallCount(1, context.renderMode);
  45621. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  45622. engine.draw(true, 0, this.borderIndicesCount, count);
  45623. engine.unbindInstanceAttributes();
  45624. }
  45625. else {
  45626. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45627. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45628. this.setupUniforms(effect, partIndex, pid._partData, i);
  45629. engine.draw(true, 0, this.borderIndicesCount);
  45630. }
  45631. }
  45632. }
  45633. engine.setAlphaMode(curAlphaMode, true);
  45634. if (this.effectFill && this.effectBorder) {
  45635. engine.setDepthFunction(depthFunction);
  45636. }
  45637. return true;
  45638. };
  45639. Lines2DRenderCache.prototype.dispose = function () {
  45640. if (!_super.prototype.dispose.call(this)) {
  45641. return false;
  45642. }
  45643. if (this.fillVB) {
  45644. this._engine._releaseBuffer(this.fillVB);
  45645. this.fillVB = null;
  45646. }
  45647. if (this.fillIB) {
  45648. this._engine._releaseBuffer(this.fillIB);
  45649. this.fillIB = null;
  45650. }
  45651. this.effectFill = null;
  45652. this.effectFillInstanced = null;
  45653. this.effectBorder = null;
  45654. this.effectBorderInstanced = null;
  45655. if (this.borderVB) {
  45656. this._engine._releaseBuffer(this.borderVB);
  45657. this.borderVB = null;
  45658. }
  45659. if (this.borderIB) {
  45660. this._engine._releaseBuffer(this.borderIB);
  45661. this.borderIB = null;
  45662. }
  45663. return true;
  45664. };
  45665. return Lines2DRenderCache;
  45666. })(BABYLON.ModelRenderCache);
  45667. BABYLON.Lines2DRenderCache = Lines2DRenderCache;
  45668. var Lines2DInstanceData = (function (_super) {
  45669. __extends(Lines2DInstanceData, _super);
  45670. function Lines2DInstanceData(partId) {
  45671. _super.call(this, partId, 1);
  45672. }
  45673. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMin", {
  45674. get: function () {
  45675. return null;
  45676. },
  45677. enumerable: true,
  45678. configurable: true
  45679. });
  45680. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMax", {
  45681. get: function () {
  45682. return null;
  45683. },
  45684. enumerable: true,
  45685. configurable: true
  45686. });
  45687. __decorate([
  45688. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  45689. ], Lines2DInstanceData.prototype, "boundingMin", null);
  45690. __decorate([
  45691. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  45692. ], Lines2DInstanceData.prototype, "boundingMax", null);
  45693. return Lines2DInstanceData;
  45694. })(BABYLON.Shape2DInstanceData);
  45695. BABYLON.Lines2DInstanceData = Lines2DInstanceData;
  45696. var Lines2D = (function (_super) {
  45697. __extends(Lines2D, _super);
  45698. /**
  45699. * Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below)
  45700. * @param points an array that describe the points to use to draw the line, must contain at least two entries.
  45701. * @param settings a combination of settings, possible ones are
  45702. * - 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)
  45703. * - children: an array of direct children
  45704. * - id a text identifier, for information purpose
  45705. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  45706. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  45707. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  45708. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  45709. * - zOrder: override the zOrder with the specified value
  45710. * - origin: define the normalized origin point location, default [0.5;0.5]
  45711. * - 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.
  45712. * - 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.
  45713. * - 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.
  45714. * - 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.
  45715. * - 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)
  45716. * - 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)
  45717. * - borderThickness: the thickness of the drawn border, default is 1.
  45718. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  45719. * - 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!
  45720. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45721. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45722. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45723. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45724. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  45725. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  45726. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  45727. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  45728. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45729. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45730. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45731. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45732. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  45733. */
  45734. function Lines2D(points, settings) {
  45735. if (!settings) {
  45736. settings = {};
  45737. }
  45738. _super.call(this, settings);
  45739. this._fillVB = null;
  45740. this._fillIB = null;
  45741. this._borderVB = null;
  45742. this._borderIB = null;
  45743. this._size = BABYLON.Size.Zero();
  45744. this._boundingMin = null;
  45745. this._boundingMax = null;
  45746. var fillThickness = (settings.fillThickness == null) ? 1 : settings.fillThickness;
  45747. var startCap = (settings.startCap == null) ? 0 : settings.startCap;
  45748. var endCap = (settings.endCap == null) ? 0 : settings.endCap;
  45749. var closed = (settings.closed == null) ? false : settings.closed;
  45750. this.points = points;
  45751. this.fillThickness = fillThickness;
  45752. this.startCap = startCap;
  45753. this.endCap = endCap;
  45754. this.closed = closed;
  45755. }
  45756. Object.defineProperty(Lines2D, "NoCap", {
  45757. /**
  45758. * No Cap to apply on the extremity
  45759. */
  45760. get: function () { return Lines2D._noCap; },
  45761. enumerable: true,
  45762. configurable: true
  45763. });
  45764. Object.defineProperty(Lines2D, "RoundCap", {
  45765. /**
  45766. * A round cap, will use the line thickness as diameter
  45767. */
  45768. get: function () { return Lines2D._roundCap; },
  45769. enumerable: true,
  45770. configurable: true
  45771. });
  45772. Object.defineProperty(Lines2D, "TriangleCap", {
  45773. /**
  45774. * Creates a triangle at the extremity.
  45775. */
  45776. get: function () { return Lines2D._triangleCap; },
  45777. enumerable: true,
  45778. configurable: true
  45779. });
  45780. Object.defineProperty(Lines2D, "SquareAnchorCap", {
  45781. /**
  45782. * Creates a Square anchor at the extremity, the square size is twice the thickness of the line
  45783. */
  45784. get: function () { return Lines2D._squareAnchorCap; },
  45785. enumerable: true,
  45786. configurable: true
  45787. });
  45788. Object.defineProperty(Lines2D, "RoundAnchorCap", {
  45789. /**
  45790. * Creates a round anchor at the extremity, the diameter is twice the thickness of the line
  45791. */
  45792. get: function () { return Lines2D._roundAnchorCap; },
  45793. enumerable: true,
  45794. configurable: true
  45795. });
  45796. Object.defineProperty(Lines2D, "DiamondAnchorCap", {
  45797. /**
  45798. * Creates a diamond anchor at the extremity.
  45799. */
  45800. get: function () { return Lines2D._diamondAnchorCap; },
  45801. enumerable: true,
  45802. configurable: true
  45803. });
  45804. Object.defineProperty(Lines2D, "ArrowCap", {
  45805. /**
  45806. * Creates an arrow anchor at the extremity. the arrow base size is twice the thickness of the line
  45807. */
  45808. get: function () { return Lines2D._arrowCap; },
  45809. enumerable: true,
  45810. configurable: true
  45811. });
  45812. Object.defineProperty(Lines2D.prototype, "points", {
  45813. get: function () {
  45814. return this._points;
  45815. },
  45816. set: function (value) {
  45817. this._points = value;
  45818. this._contour = null;
  45819. this._boundingBoxDirty();
  45820. },
  45821. enumerable: true,
  45822. configurable: true
  45823. });
  45824. Object.defineProperty(Lines2D.prototype, "fillThickness", {
  45825. get: function () {
  45826. return this._fillThickness;
  45827. },
  45828. set: function (value) {
  45829. this._fillThickness = value;
  45830. },
  45831. enumerable: true,
  45832. configurable: true
  45833. });
  45834. Object.defineProperty(Lines2D.prototype, "closed", {
  45835. get: function () {
  45836. return this._closed;
  45837. },
  45838. set: function (value) {
  45839. this._closed = value;
  45840. },
  45841. enumerable: true,
  45842. configurable: true
  45843. });
  45844. Object.defineProperty(Lines2D.prototype, "startCap", {
  45845. get: function () {
  45846. return this._startCap;
  45847. },
  45848. set: function (value) {
  45849. this._startCap = value;
  45850. },
  45851. enumerable: true,
  45852. configurable: true
  45853. });
  45854. Object.defineProperty(Lines2D.prototype, "endCap", {
  45855. get: function () {
  45856. return this._endCap;
  45857. },
  45858. set: function (value) {
  45859. this._endCap = value;
  45860. },
  45861. enumerable: true,
  45862. configurable: true
  45863. });
  45864. Lines2D.prototype.levelIntersect = function (intersectInfo) {
  45865. var _this = this;
  45866. if (this._contour == null) {
  45867. this._computeLines2D();
  45868. }
  45869. var pl = this.points.length;
  45870. var l = this.closed ? pl + 1 : pl;
  45871. var p = intersectInfo._localPickPosition;
  45872. this.transformPointWithOriginToRef(this._contour[0], null, Lines2D._prevA);
  45873. this.transformPointWithOriginToRef(this._contour[1], null, Lines2D._prevB);
  45874. for (var i = 1; i < l; i++) {
  45875. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 0], null, Lines2D._curA);
  45876. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 1], null, Lines2D._curB);
  45877. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curA)) {
  45878. return true;
  45879. }
  45880. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._curA, Lines2D._prevB, Lines2D._curB)) {
  45881. return true;
  45882. }
  45883. Lines2D._prevA.x = Lines2D._curA.x;
  45884. Lines2D._prevA.y = Lines2D._curA.y;
  45885. Lines2D._prevB.x = Lines2D._curB.x;
  45886. Lines2D._prevB.y = Lines2D._curB.y;
  45887. }
  45888. var capIntersect = function (tri, points) {
  45889. var l = tri.length;
  45890. for (var i = 0; i < l; i += 3) {
  45891. Lines2D._curA.x = points[tri[i + 0] * 2 + 0];
  45892. Lines2D._curA.y = points[tri[i + 0] * 2 + 1];
  45893. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._curB);
  45894. Lines2D._curA.x = points[tri[i + 1] * 2 + 0];
  45895. Lines2D._curA.y = points[tri[i + 1] * 2 + 1];
  45896. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevA);
  45897. Lines2D._curA.x = points[tri[i + 2] * 2 + 0];
  45898. Lines2D._curA.y = points[tri[i + 2] * 2 + 1];
  45899. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevB);
  45900. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curB)) {
  45901. return true;
  45902. }
  45903. }
  45904. return false;
  45905. };
  45906. if (this._startCapTriIndices) {
  45907. if (this._startCapTriIndices && capIntersect(this._startCapTriIndices, this._startCapContour)) {
  45908. return true;
  45909. }
  45910. if (this._endCapTriIndices && capIntersect(this._endCapTriIndices, this._endCapContour)) {
  45911. return true;
  45912. }
  45913. }
  45914. return false;
  45915. };
  45916. Object.defineProperty(Lines2D.prototype, "boundingMin", {
  45917. get: function () {
  45918. if (!this._boundingMin) {
  45919. this._computeLines2D();
  45920. }
  45921. return this._boundingMin;
  45922. },
  45923. enumerable: true,
  45924. configurable: true
  45925. });
  45926. Object.defineProperty(Lines2D.prototype, "boundingMax", {
  45927. get: function () {
  45928. if (!this._boundingMax) {
  45929. this._computeLines2D();
  45930. }
  45931. return this._boundingMax;
  45932. },
  45933. enumerable: true,
  45934. configurable: true
  45935. });
  45936. Lines2D.prototype.getUsedShaderCategories = function (dataPart) {
  45937. var res = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  45938. // Remove the BORDER category, we don't use it in the VertexShader
  45939. var i = res.indexOf(BABYLON.Shape2D.SHAPE2D_CATEGORY_BORDER);
  45940. if (i !== -1) {
  45941. res.splice(i, 1);
  45942. }
  45943. return res;
  45944. };
  45945. Lines2D.prototype.updateLevelBoundingInfo = function () {
  45946. if (!this._boundingMin) {
  45947. this._computeLines2D();
  45948. }
  45949. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(this._boundingMin.x, this._boundingMax.x, this._boundingMin.y, this._boundingMax.y, this._levelBoundingInfo);
  45950. };
  45951. Lines2D.prototype.createModelRenderCache = function (modelKey) {
  45952. var renderCache = new Lines2DRenderCache(this.owner.engine, modelKey);
  45953. return renderCache;
  45954. };
  45955. ///////////////////////////////////////////////////////////////////////////////////
  45956. // Methods for Lines building
  45957. Lines2D.prototype._perp = function (v, res) {
  45958. res.x = v.y;
  45959. res.y = -v.x;
  45960. };
  45961. ;
  45962. Lines2D.prototype._direction = function (a, b, res) {
  45963. a.subtractToRef(b, res);
  45964. res.normalize();
  45965. };
  45966. Lines2D.prototype._computeMiter = function (tangent, miter, a, b) {
  45967. a.addToRef(b, tangent);
  45968. tangent.normalize();
  45969. miter.x = -tangent.y;
  45970. miter.y = tangent.x;
  45971. Lines2D._miterTps.x = -a.y;
  45972. Lines2D._miterTps.y = a.x;
  45973. return 1 / BABYLON.Vector2.Dot(miter, Lines2D._miterTps);
  45974. };
  45975. Lines2D.prototype._intersect = function (x1, y1, x2, y2, x3, y3, x4, y4) {
  45976. var d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  45977. if (d === 0)
  45978. return false;
  45979. var xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; // Intersection point is xi/yi, just in case...
  45980. //let yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; // That's why I left it commented
  45981. if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2))
  45982. return false;
  45983. if (xi < Math.min(x3, x4) || xi > Math.max(x3, x4))
  45984. return false;
  45985. return true;
  45986. };
  45987. Lines2D.prototype._updateMinMax = function (array, offset) {
  45988. if (offset >= array.length) {
  45989. return;
  45990. }
  45991. this._boundingMin.x = Math.min(this._boundingMin.x, array[offset]);
  45992. this._boundingMax.x = Math.max(this._boundingMax.x, array[offset]);
  45993. this._boundingMin.y = Math.min(this._boundingMin.y, array[offset + 1]);
  45994. this._boundingMax.y = Math.max(this._boundingMax.y, array[offset + 1]);
  45995. };
  45996. Lines2D.prototype._store = function (array, contour, index, max, p, n, halfThickness, borderThickness, detectFlip) {
  45997. var borderMode = borderThickness != null && !isNaN(borderThickness);
  45998. var off = index * (borderMode ? 8 : 4);
  45999. // 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)
  46000. if (off >= array.length) {
  46001. return;
  46002. }
  46003. // Store start/end normal, we need it for the cap construction
  46004. if (index === 0) {
  46005. this._perp(n, Lines2D._startDir);
  46006. }
  46007. else if (index === max - 1) {
  46008. this._perp(n, Lines2D._endDir);
  46009. Lines2D._endDir.x *= -1;
  46010. Lines2D._endDir.y *= -1;
  46011. }
  46012. var swap = false;
  46013. array[off + 0] = p.x + n.x * halfThickness;
  46014. array[off + 1] = p.y + n.y * halfThickness;
  46015. array[off + 2] = p.x + n.x * -halfThickness;
  46016. array[off + 3] = p.y + n.y * -halfThickness;
  46017. this._updateMinMax(array, off);
  46018. this._updateMinMax(array, off + 2);
  46019. // If an index is given we check if the two segments formed between [index+0;detectFlip+0] and [index+2;detectFlip+2] intersect themselves.
  46020. // 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
  46021. if (detectFlip !== undefined) {
  46022. // Flip if intersect
  46023. var flipOff = detectFlip * (borderMode ? 8 : 4);
  46024. 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])) {
  46025. swap = true;
  46026. var tps = array[off + 0];
  46027. array[off + 0] = array[off + 2];
  46028. array[off + 2] = tps;
  46029. tps = array[off + 1];
  46030. array[off + 1] = array[off + 3];
  46031. array[off + 3] = tps;
  46032. }
  46033. }
  46034. if (borderMode) {
  46035. var t = halfThickness + borderThickness;
  46036. array[off + 4] = p.x + n.x * (swap ? -t : t);
  46037. array[off + 5] = p.y + n.y * (swap ? -t : t);
  46038. array[off + 6] = p.x + n.x * (swap ? t : -t);
  46039. array[off + 7] = p.y + n.y * (swap ? t : -t);
  46040. this._updateMinMax(array, off + 4);
  46041. this._updateMinMax(array, off + 6);
  46042. }
  46043. if (contour) {
  46044. off += borderMode ? 4 : 0;
  46045. contour.push(new BABYLON.Vector2(array[off + 0], array[off + 1]));
  46046. contour.push(new BABYLON.Vector2(array[off + 2], array[off + 3]));
  46047. }
  46048. };
  46049. Lines2D.prototype._getCapSize = function (type, border) {
  46050. if (border === void 0) { border = false; }
  46051. var sd = Lines2D._roundCapSubDiv;
  46052. // If no array given, we call this to get the size
  46053. var vbsize = 0, ibsize = 0;
  46054. switch (type) {
  46055. case Lines2D.NoCap:
  46056. {
  46057. // If the line is not close and we're computing border, we add the size to generate the edge border
  46058. if (!this.closed && border) {
  46059. vbsize = 4;
  46060. ibsize = 6;
  46061. }
  46062. else {
  46063. vbsize = ibsize = 0;
  46064. }
  46065. break;
  46066. }
  46067. case Lines2D.RoundCap:
  46068. {
  46069. if (border) {
  46070. vbsize = sd;
  46071. ibsize = (sd - 2) * 3;
  46072. }
  46073. else {
  46074. vbsize = (sd / 2) + 1;
  46075. ibsize = (sd / 2) * 3;
  46076. }
  46077. break;
  46078. }
  46079. case Lines2D.ArrowCap:
  46080. {
  46081. if (border) {
  46082. vbsize = 12;
  46083. ibsize = 24;
  46084. }
  46085. else {
  46086. vbsize = 3;
  46087. ibsize = 3;
  46088. }
  46089. break;
  46090. }
  46091. case Lines2D.TriangleCap:
  46092. {
  46093. if (border) {
  46094. vbsize = 6;
  46095. ibsize = 12;
  46096. }
  46097. else {
  46098. vbsize = 3;
  46099. ibsize = 3;
  46100. }
  46101. break;
  46102. }
  46103. case Lines2D.DiamondAnchorCap:
  46104. {
  46105. if (border) {
  46106. vbsize = 10;
  46107. ibsize = 24;
  46108. }
  46109. else {
  46110. vbsize = 5;
  46111. ibsize = 9;
  46112. }
  46113. break;
  46114. }
  46115. case Lines2D.SquareAnchorCap:
  46116. {
  46117. if (border) {
  46118. vbsize = 12;
  46119. ibsize = 30;
  46120. }
  46121. else {
  46122. vbsize = 4;
  46123. ibsize = 6;
  46124. }
  46125. break;
  46126. }
  46127. case Lines2D.RoundAnchorCap:
  46128. {
  46129. if (border) {
  46130. vbsize = sd * 2;
  46131. ibsize = (sd - 1) * 6;
  46132. }
  46133. else {
  46134. vbsize = sd + 1;
  46135. ibsize = (sd + 1) * 3;
  46136. }
  46137. break;
  46138. }
  46139. }
  46140. return { vbsize: vbsize * 2, ibsize: ibsize };
  46141. };
  46142. Lines2D.prototype._storeVertex = function (vb, baseOffset, index, basePos, rotation, vertex, contour) {
  46143. var c = Math.cos(rotation);
  46144. var s = Math.sin(rotation);
  46145. Lines2D._tpsV.x = (c * vertex.x) + (-s * vertex.y) + basePos.x;
  46146. Lines2D._tpsV.y = (s * vertex.x) + (c * vertex.y) + basePos.y;
  46147. var offset = baseOffset + (index * 2);
  46148. vb[offset + 0] = Lines2D._tpsV.x;
  46149. vb[offset + 1] = Lines2D._tpsV.y;
  46150. if (contour) {
  46151. contour.push(Lines2D._tpsV.x);
  46152. contour.push(Lines2D._tpsV.y);
  46153. }
  46154. this._updateMinMax(vb, offset);
  46155. return (baseOffset + index * 2) / 2;
  46156. };
  46157. Lines2D.prototype._storeIndex = function (ib, baseOffset, index, vertexIndex) {
  46158. ib[baseOffset + index] = vertexIndex;
  46159. };
  46160. Lines2D.prototype._buildCap = function (vb, vbi, ib, ibi, pos, thickness, borderThickness, type, capDir, contour) {
  46161. // 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
  46162. var sd = Lines2D._roundCapSubDiv;
  46163. var dir = new BABYLON.Vector2(1, 0);
  46164. var angle = Math.atan2(capDir.y, capDir.x) - Math.atan2(dir.y, dir.x);
  46165. var ht = thickness / 2;
  46166. var t = thickness;
  46167. var borderMode = borderThickness != null;
  46168. var bt = borderThickness;
  46169. switch (type) {
  46170. case Lines2D.NoCap:
  46171. if (borderMode && !this.closed) {
  46172. var vi = 0;
  46173. var ii = 0;
  46174. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), contour);
  46175. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, ht + bt), contour);
  46176. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, -(ht + bt)), contour);
  46177. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), contour);
  46178. this._storeIndex(ib, ibi, ii++, v1);
  46179. this._storeIndex(ib, ibi, ii++, v2);
  46180. this._storeIndex(ib, ibi, ii++, v3);
  46181. this._storeIndex(ib, ibi, ii++, v1);
  46182. this._storeIndex(ib, ibi, ii++, v3);
  46183. this._storeIndex(ib, ibi, ii++, v4);
  46184. }
  46185. break;
  46186. case Lines2D.ArrowCap:
  46187. ht *= 2;
  46188. case Lines2D.TriangleCap:
  46189. {
  46190. if (borderMode) {
  46191. var f = type === Lines2D.TriangleCap ? bt : Math.sqrt(bt * bt * 2);
  46192. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), null);
  46193. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), null);
  46194. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), null);
  46195. var v4 = this._storeVertex(vb, vbi, 3, pos, angle, new BABYLON.Vector2(0, ht + f), contour);
  46196. var v5 = this._storeVertex(vb, vbi, 4, pos, angle, new BABYLON.Vector2(ht + f, 0), contour);
  46197. var v6 = this._storeVertex(vb, vbi, 5, pos, angle, new BABYLON.Vector2(0, -(ht + f)), contour);
  46198. var ii = 0;
  46199. this._storeIndex(ib, ibi, ii++, v1);
  46200. this._storeIndex(ib, ibi, ii++, v4);
  46201. this._storeIndex(ib, ibi, ii++, v5);
  46202. this._storeIndex(ib, ibi, ii++, v1);
  46203. this._storeIndex(ib, ibi, ii++, v5);
  46204. this._storeIndex(ib, ibi, ii++, v2);
  46205. this._storeIndex(ib, ibi, ii++, v6);
  46206. this._storeIndex(ib, ibi, ii++, v3);
  46207. this._storeIndex(ib, ibi, ii++, v2);
  46208. this._storeIndex(ib, ibi, ii++, v6);
  46209. this._storeIndex(ib, ibi, ii++, v2);
  46210. this._storeIndex(ib, ibi, ii++, v5);
  46211. if (type === Lines2D.ArrowCap) {
  46212. var rht = thickness / 2;
  46213. var v10 = this._storeVertex(vb, vbi, 9, pos, angle, new BABYLON.Vector2(0, -(rht + bt)), null);
  46214. var v12 = this._storeVertex(vb, vbi, 11, pos, angle, new BABYLON.Vector2(-bt, -(ht + f)), contour);
  46215. var v11 = this._storeVertex(vb, vbi, 10, pos, angle, new BABYLON.Vector2(-bt, -(rht + bt)), contour);
  46216. var v7 = this._storeVertex(vb, vbi, 6, pos, angle, new BABYLON.Vector2(0, rht + bt), null);
  46217. var v8 = this._storeVertex(vb, vbi, 7, pos, angle, new BABYLON.Vector2(-bt, rht + bt), contour);
  46218. var v9 = this._storeVertex(vb, vbi, 8, pos, angle, new BABYLON.Vector2(-bt, ht + f), contour);
  46219. this._storeIndex(ib, ibi, ii++, v7);
  46220. this._storeIndex(ib, ibi, ii++, v8);
  46221. this._storeIndex(ib, ibi, ii++, v9);
  46222. this._storeIndex(ib, ibi, ii++, v7);
  46223. this._storeIndex(ib, ibi, ii++, v9);
  46224. this._storeIndex(ib, ibi, ii++, v4);
  46225. this._storeIndex(ib, ibi, ii++, v10);
  46226. this._storeIndex(ib, ibi, ii++, v12);
  46227. this._storeIndex(ib, ibi, ii++, v11);
  46228. this._storeIndex(ib, ibi, ii++, v10);
  46229. this._storeIndex(ib, ibi, ii++, v6);
  46230. this._storeIndex(ib, ibi, ii++, v12);
  46231. }
  46232. }
  46233. else {
  46234. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), contour);
  46235. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), contour);
  46236. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), contour);
  46237. this._storeIndex(ib, ibi, 0, v1);
  46238. this._storeIndex(ib, ibi, 1, v2);
  46239. this._storeIndex(ib, ibi, 2, v3);
  46240. }
  46241. break;
  46242. }
  46243. case Lines2D.RoundCap:
  46244. {
  46245. if (borderMode) {
  46246. var curA = -Math.PI / 2;
  46247. var incA = Math.PI / (sd / 2 - 1);
  46248. var ii = 0;
  46249. for (var i = 0; i < (sd / 2); i++) {
  46250. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  46251. 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);
  46252. if (i > 0) {
  46253. this._storeIndex(ib, ibi, ii++, v1 - 2);
  46254. this._storeIndex(ib, ibi, ii++, v2 - 2);
  46255. this._storeIndex(ib, ibi, ii++, v2);
  46256. this._storeIndex(ib, ibi, ii++, v1 - 2);
  46257. this._storeIndex(ib, ibi, ii++, v2);
  46258. this._storeIndex(ib, ibi, ii++, v1);
  46259. }
  46260. curA += incA;
  46261. }
  46262. }
  46263. else {
  46264. var c = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, 0), null);
  46265. var curA = -Math.PI / 2;
  46266. var incA = Math.PI / (sd / 2 - 1);
  46267. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  46268. curA += incA;
  46269. for (var i = 1; i < (sd / 2); i++) {
  46270. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), contour);
  46271. this._storeIndex(ib, ibi, i * 3 + 0, c);
  46272. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  46273. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  46274. curA += incA;
  46275. }
  46276. }
  46277. break;
  46278. }
  46279. case Lines2D.SquareAnchorCap:
  46280. {
  46281. var vi = 0;
  46282. var c = borderMode ? null : contour;
  46283. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, t), c);
  46284. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, t), c);
  46285. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, -t), c);
  46286. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -t), c);
  46287. if (borderMode) {
  46288. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), null);
  46289. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, ht + bt), contour);
  46290. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, t + bt), contour);
  46291. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, t + bt), contour);
  46292. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, -(t + bt)), contour);
  46293. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(t + bt)), contour);
  46294. var v11 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(ht + bt)), contour);
  46295. var v12 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), null);
  46296. var ii = 0;
  46297. this._storeIndex(ib, ibi, ii++, v6);
  46298. this._storeIndex(ib, ibi, ii++, v1);
  46299. this._storeIndex(ib, ibi, ii++, v5);
  46300. this._storeIndex(ib, ibi, ii++, v6);
  46301. this._storeIndex(ib, ibi, ii++, v7);
  46302. this._storeIndex(ib, ibi, ii++, v1);
  46303. this._storeIndex(ib, ibi, ii++, v1);
  46304. this._storeIndex(ib, ibi, ii++, v7);
  46305. this._storeIndex(ib, ibi, ii++, v8);
  46306. this._storeIndex(ib, ibi, ii++, v1);
  46307. this._storeIndex(ib, ibi, ii++, v8);
  46308. this._storeIndex(ib, ibi, ii++, v2);
  46309. this._storeIndex(ib, ibi, ii++, v2);
  46310. this._storeIndex(ib, ibi, ii++, v8);
  46311. this._storeIndex(ib, ibi, ii++, v9);
  46312. this._storeIndex(ib, ibi, ii++, v2);
  46313. this._storeIndex(ib, ibi, ii++, v9);
  46314. this._storeIndex(ib, ibi, ii++, v3);
  46315. this._storeIndex(ib, ibi, ii++, v3);
  46316. this._storeIndex(ib, ibi, ii++, v9);
  46317. this._storeIndex(ib, ibi, ii++, v10);
  46318. this._storeIndex(ib, ibi, ii++, v3);
  46319. this._storeIndex(ib, ibi, ii++, v10);
  46320. this._storeIndex(ib, ibi, ii++, v4);
  46321. this._storeIndex(ib, ibi, ii++, v10);
  46322. this._storeIndex(ib, ibi, ii++, v11);
  46323. this._storeIndex(ib, ibi, ii++, v4);
  46324. this._storeIndex(ib, ibi, ii++, v11);
  46325. this._storeIndex(ib, ibi, ii++, v12);
  46326. this._storeIndex(ib, ibi, ii++, v4);
  46327. }
  46328. else {
  46329. this._storeIndex(ib, ibi, 0, v1);
  46330. this._storeIndex(ib, ibi, 1, v2);
  46331. this._storeIndex(ib, ibi, 2, v3);
  46332. this._storeIndex(ib, ibi, 3, v1);
  46333. this._storeIndex(ib, ibi, 4, v3);
  46334. this._storeIndex(ib, ibi, 5, v4);
  46335. }
  46336. break;
  46337. }
  46338. case Lines2D.RoundAnchorCap:
  46339. {
  46340. var cpos = Math.sqrt(t * t - ht * ht);
  46341. var center = new BABYLON.Vector2(cpos, 0);
  46342. var curA = BABYLON.Tools.ToRadians(-150);
  46343. var incA = BABYLON.Tools.ToRadians(300) / (sd - 1);
  46344. if (borderMode) {
  46345. var ii = 0;
  46346. for (var i = 0; i < sd; i++) {
  46347. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  46348. 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);
  46349. if (i > 0) {
  46350. this._storeIndex(ib, ibi, ii++, v1 - 2);
  46351. this._storeIndex(ib, ibi, ii++, v2 - 2);
  46352. this._storeIndex(ib, ibi, ii++, v2);
  46353. this._storeIndex(ib, ibi, ii++, v1 - 2);
  46354. this._storeIndex(ib, ibi, ii++, v2);
  46355. this._storeIndex(ib, ibi, ii++, v1);
  46356. }
  46357. curA += incA;
  46358. }
  46359. }
  46360. else {
  46361. var c = this._storeVertex(vb, vbi, 0, pos, angle, center, null);
  46362. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  46363. curA += incA;
  46364. for (var i = 1; i < sd; i++) {
  46365. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), contour);
  46366. this._storeIndex(ib, ibi, i * 3 + 0, c);
  46367. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  46368. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  46369. curA += incA;
  46370. }
  46371. this._storeIndex(ib, ibi, sd * 3 + 0, c);
  46372. this._storeIndex(ib, ibi, sd * 3 + 1, c + 1);
  46373. this._storeIndex(ib, ibi, sd * 3 + 2, c + sd);
  46374. }
  46375. break;
  46376. }
  46377. case Lines2D.DiamondAnchorCap:
  46378. {
  46379. var vi = 0;
  46380. var c = borderMode ? null : contour;
  46381. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht), c);
  46382. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t), c);
  46383. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3, 0), c);
  46384. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -t), c);
  46385. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -ht), c);
  46386. if (borderMode) {
  46387. var f = Math.sqrt(bt * bt * 2);
  46388. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, ht), contour);
  46389. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t + f), contour);
  46390. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3 + f, 0), contour);
  46391. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -(t + f)), contour);
  46392. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, -ht), contour);
  46393. var ii = 0;
  46394. this._storeIndex(ib, ibi, ii++, v6);
  46395. this._storeIndex(ib, ibi, ii++, v7);
  46396. this._storeIndex(ib, ibi, ii++, v1);
  46397. this._storeIndex(ib, ibi, ii++, v1);
  46398. this._storeIndex(ib, ibi, ii++, v7);
  46399. this._storeIndex(ib, ibi, ii++, v2);
  46400. this._storeIndex(ib, ibi, ii++, v2);
  46401. this._storeIndex(ib, ibi, ii++, v7);
  46402. this._storeIndex(ib, ibi, ii++, v8);
  46403. this._storeIndex(ib, ibi, ii++, v2);
  46404. this._storeIndex(ib, ibi, ii++, v8);
  46405. this._storeIndex(ib, ibi, ii++, v3);
  46406. this._storeIndex(ib, ibi, ii++, v3);
  46407. this._storeIndex(ib, ibi, ii++, v8);
  46408. this._storeIndex(ib, ibi, ii++, v9);
  46409. this._storeIndex(ib, ibi, ii++, v3);
  46410. this._storeIndex(ib, ibi, ii++, v9);
  46411. this._storeIndex(ib, ibi, ii++, v4);
  46412. this._storeIndex(ib, ibi, ii++, v4);
  46413. this._storeIndex(ib, ibi, ii++, v9);
  46414. this._storeIndex(ib, ibi, ii++, v10);
  46415. this._storeIndex(ib, ibi, ii++, v4);
  46416. this._storeIndex(ib, ibi, ii++, v10);
  46417. this._storeIndex(ib, ibi, ii++, v5);
  46418. }
  46419. else {
  46420. this._storeIndex(ib, ibi, 0, v1);
  46421. this._storeIndex(ib, ibi, 1, v2);
  46422. this._storeIndex(ib, ibi, 2, v3);
  46423. this._storeIndex(ib, ibi, 3, v1);
  46424. this._storeIndex(ib, ibi, 4, v3);
  46425. this._storeIndex(ib, ibi, 5, v5);
  46426. this._storeIndex(ib, ibi, 6, v5);
  46427. this._storeIndex(ib, ibi, 7, v3);
  46428. this._storeIndex(ib, ibi, 8, v4);
  46429. }
  46430. break;
  46431. }
  46432. }
  46433. return null;
  46434. };
  46435. Lines2D.prototype._buildLine = function (vb, contour, ht, bt) {
  46436. var lineA = BABYLON.Vector2.Zero();
  46437. var lineB = BABYLON.Vector2.Zero();
  46438. var tangent = BABYLON.Vector2.Zero();
  46439. var miter = BABYLON.Vector2.Zero();
  46440. var curNormal = null;
  46441. if (this.closed) {
  46442. this.points.push(this.points[0]);
  46443. }
  46444. var total = this.points.length;
  46445. for (var i = 1; i < total; i++) {
  46446. var last = this.points[i - 1];
  46447. var cur = this.points[i];
  46448. var next = (i < (this.points.length - 1)) ? this.points[i + 1] : null;
  46449. this._direction(cur, last, lineA);
  46450. if (!curNormal) {
  46451. curNormal = BABYLON.Vector2.Zero();
  46452. this._perp(lineA, curNormal);
  46453. }
  46454. if (i === 1) {
  46455. this._store(vb, contour, 0, total, this.points[0], curNormal, ht, bt);
  46456. }
  46457. if (!next) {
  46458. this._perp(lineA, curNormal);
  46459. this._store(vb, contour, i, total, this.points[i], curNormal, ht, bt, i - 1);
  46460. }
  46461. else {
  46462. this._direction(next, cur, lineB);
  46463. var miterLen = this._computeMiter(tangent, miter, lineA, lineB);
  46464. this._store(vb, contour, i, total, this.points[i], miter, miterLen * ht, miterLen * bt, i - 1);
  46465. }
  46466. }
  46467. if (this.points.length > 2 && this.closed) {
  46468. var last2 = this.points[total - 2];
  46469. var cur2 = this.points[0];
  46470. var next2 = this.points[1];
  46471. this._direction(cur2, last2, lineA);
  46472. this._direction(next2, cur2, lineB);
  46473. this._perp(lineA, curNormal);
  46474. var miterLen2 = this._computeMiter(tangent, miter, lineA, lineB);
  46475. this._store(vb, null, 0, total, this.points[0], miter, miterLen2 * ht, miterLen2 * bt, 1);
  46476. // Patch contour
  46477. if (contour) {
  46478. var off = (bt == null) ? 0 : 4;
  46479. contour[0].x = vb[off + 0];
  46480. contour[0].y = vb[off + 1];
  46481. contour[1].x = vb[off + 2];
  46482. contour[1].y = vb[off + 3];
  46483. }
  46484. }
  46485. // Remove the point we added at the beginning
  46486. if (this.closed) {
  46487. this.points.splice(total - 1);
  46488. }
  46489. };
  46490. // Methods for Lines building
  46491. ///////////////////////////////////////////////////////////////////////////////////
  46492. Lines2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  46493. var renderCache = modelRenderCache;
  46494. var engine = this.owner.engine;
  46495. if (this._fillVB === null) {
  46496. this._computeLines2D();
  46497. }
  46498. // Need to create WebGL resources for fill part?
  46499. if (this.fill) {
  46500. renderCache.fillVB = engine.createVertexBuffer(this._fillVB);
  46501. renderCache.fillIB = engine.createIndexBuffer(this._fillIB);
  46502. renderCache.fillIndicesCount = this._fillIB.length;
  46503. // 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
  46504. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], true);
  46505. if (ei) {
  46506. renderCache.effectFillInstanced = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  46507. }
  46508. // Get the non instanced version
  46509. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], false);
  46510. renderCache.effectFill = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  46511. }
  46512. // Need to create WebGL resources for border part?
  46513. if (this.border) {
  46514. renderCache.borderVB = engine.createVertexBuffer(this._borderVB);
  46515. renderCache.borderIB = engine.createIndexBuffer(this._borderIB);
  46516. renderCache.borderIndicesCount = this._borderIB.length;
  46517. // 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
  46518. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], true);
  46519. if (ei) {
  46520. renderCache.effectBorderInstanced = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  46521. }
  46522. // Get the non instanced version
  46523. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], false);
  46524. renderCache.effectBorder = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  46525. }
  46526. this._fillVB = null;
  46527. this._fillIB = null;
  46528. this._borderVB = null;
  46529. this._borderIB = null;
  46530. return renderCache;
  46531. };
  46532. Lines2D.prototype._computeLines2D = function () {
  46533. // Init min/max because their being computed here
  46534. this._boundingMin = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  46535. this._boundingMax = new BABYLON.Vector2(Number.MIN_VALUE, Number.MIN_VALUE);
  46536. var contour = new Array();
  46537. var startCapContour = new Array();
  46538. var endCapContour = new Array();
  46539. // Need to create WebGL resources for fill part?
  46540. if (this.fill) {
  46541. var startCapInfo = this._getCapSize(this.startCap);
  46542. var endCapInfo = this._getCapSize(this.endCap);
  46543. var count = this.points.length;
  46544. var vbSize = (count * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  46545. this._fillVB = new Float32Array(vbSize);
  46546. var vb = this._fillVB;
  46547. var ht = this.fillThickness / 2;
  46548. var total = this.points.length;
  46549. this._buildLine(vb, this.border ? null : contour, ht);
  46550. var max = total * 2;
  46551. var triCount = (count - (this.closed ? 0 : 1)) * 2;
  46552. this._fillIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  46553. var ib = this._fillIB;
  46554. for (var i = 0; i < triCount; i += 2) {
  46555. ib[i * 3 + 0] = i + 0;
  46556. ib[i * 3 + 1] = i + 1;
  46557. ib[i * 3 + 2] = (i + 2) % max;
  46558. ib[i * 3 + 3] = i + 1;
  46559. ib[i * 3 + 4] = (i + 3) % max;
  46560. ib[i * 3 + 5] = (i + 2) % max;
  46561. }
  46562. this._buildCap(vb, count * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, null, this.startCap, Lines2D._startDir, this.border ? null : startCapContour);
  46563. 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);
  46564. }
  46565. // Need to create WebGL resources for border part?
  46566. if (this.border) {
  46567. var startCapInfo = this._getCapSize(this.startCap, true);
  46568. var endCapInfo = this._getCapSize(this.endCap, true);
  46569. var count = this.points.length;
  46570. var vbSize = (count * 2 * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  46571. this._borderVB = new Float32Array(vbSize);
  46572. var vb = this._borderVB;
  46573. var ht = this.fillThickness / 2;
  46574. var bt = this.borderThickness;
  46575. var total = this.points.length;
  46576. this._buildLine(vb, contour, ht, bt);
  46577. var max = total * 2 * 2;
  46578. var triCount = (count - (this.closed ? 0 : 1)) * 2 * 2;
  46579. this._borderIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  46580. var ib = this._borderIB;
  46581. for (var i = 0; i < triCount; i += 4) {
  46582. ib[i * 3 + 0] = i + 0;
  46583. ib[i * 3 + 1] = i + 2;
  46584. ib[i * 3 + 2] = (i + 6) % max;
  46585. ib[i * 3 + 3] = i + 0;
  46586. ib[i * 3 + 4] = (i + 6) % max;
  46587. ib[i * 3 + 5] = (i + 4) % max;
  46588. ib[i * 3 + 6] = i + 3;
  46589. ib[i * 3 + 7] = i + 1;
  46590. ib[i * 3 + 8] = (i + 5) % max;
  46591. ib[i * 3 + 9] = i + 3;
  46592. ib[i * 3 + 10] = (i + 5) % max;
  46593. ib[i * 3 + 11] = (i + 7) % max;
  46594. }
  46595. this._buildCap(vb, count * 2 * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, this.borderThickness, this.startCap, Lines2D._startDir, startCapContour);
  46596. 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);
  46597. }
  46598. this._contour = contour;
  46599. if (startCapContour.length > 0) {
  46600. var startCapTri = Earcut.earcut(startCapContour, null, 2);
  46601. this._startCapTriIndices = startCapTri;
  46602. this._startCapContour = startCapContour;
  46603. }
  46604. else {
  46605. this._startCapTriIndices = null;
  46606. this._startCapContour = null;
  46607. }
  46608. if (endCapContour.length > 0) {
  46609. var endCapTri = Earcut.earcut(endCapContour, null, 2);
  46610. this._endCapContour = endCapContour;
  46611. this._endCapTriIndices = endCapTri;
  46612. }
  46613. else {
  46614. this._endCapContour = null;
  46615. this._endCapTriIndices = null;
  46616. }
  46617. var bs = this._boundingMax.subtract(this._boundingMin);
  46618. this._size.width = bs.x;
  46619. this._size.height = bs.y;
  46620. };
  46621. Object.defineProperty(Lines2D.prototype, "size", {
  46622. get: function () {
  46623. if (this._size == null) {
  46624. this._computeLines2D();
  46625. }
  46626. return this._size;
  46627. },
  46628. enumerable: true,
  46629. configurable: true
  46630. });
  46631. Lines2D.prototype.createInstanceDataParts = function () {
  46632. var res = new Array();
  46633. if (this.border) {
  46634. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  46635. }
  46636. if (this.fill) {
  46637. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  46638. }
  46639. return res;
  46640. };
  46641. Lines2D.prototype.refreshInstanceDataPart = function (part) {
  46642. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  46643. return false;
  46644. }
  46645. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  46646. var d = part;
  46647. if (this.border instanceof BABYLON.GradientColorBrush2D) {
  46648. d.boundingMin = this.boundingMin;
  46649. d.boundingMax = this.boundingMax;
  46650. }
  46651. }
  46652. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  46653. var d = part;
  46654. if (this.fill instanceof BABYLON.GradientColorBrush2D) {
  46655. d.boundingMin = this.boundingMin;
  46656. d.boundingMax = this.boundingMax;
  46657. }
  46658. }
  46659. return true;
  46660. };
  46661. Lines2D._prevA = BABYLON.Vector2.Zero();
  46662. Lines2D._prevB = BABYLON.Vector2.Zero();
  46663. Lines2D._curA = BABYLON.Vector2.Zero();
  46664. Lines2D._curB = BABYLON.Vector2.Zero();
  46665. Lines2D._miterTps = BABYLON.Vector2.Zero();
  46666. Lines2D._startDir = BABYLON.Vector2.Zero();
  46667. Lines2D._endDir = BABYLON.Vector2.Zero();
  46668. Lines2D._tpsV = BABYLON.Vector2.Zero();
  46669. Lines2D._noCap = 0;
  46670. Lines2D._roundCap = 1;
  46671. Lines2D._triangleCap = 2;
  46672. Lines2D._squareAnchorCap = 3;
  46673. Lines2D._roundAnchorCap = 4;
  46674. Lines2D._diamondAnchorCap = 5;
  46675. Lines2D._arrowCap = 6;
  46676. Lines2D._roundCapSubDiv = 36;
  46677. __decorate([
  46678. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Lines2D.pointsProperty = pi; })
  46679. ], Lines2D.prototype, "points", null);
  46680. __decorate([
  46681. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Lines2D.fillThicknessProperty = pi; })
  46682. ], Lines2D.prototype, "fillThickness", null);
  46683. __decorate([
  46684. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Lines2D.closedProperty = pi; })
  46685. ], Lines2D.prototype, "closed", null);
  46686. __decorate([
  46687. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 4, function (pi) { return Lines2D.startCapProperty = pi; })
  46688. ], Lines2D.prototype, "startCap", null);
  46689. __decorate([
  46690. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 5, function (pi) { return Lines2D.endCapProperty = pi; })
  46691. ], Lines2D.prototype, "endCap", null);
  46692. Lines2D = __decorate([
  46693. BABYLON.className("Lines2D")
  46694. ], Lines2D);
  46695. return Lines2D;
  46696. })(BABYLON.Shape2D);
  46697. BABYLON.Lines2D = Lines2D;
  46698. })(BABYLON || (BABYLON = {}));
  46699. var BABYLON;
  46700. (function (BABYLON) {
  46701. // This class contains data that lifetime is bounding to the Babylon Engine object
  46702. var Canvas2DEngineBoundData = (function () {
  46703. function Canvas2DEngineBoundData() {
  46704. this._modelCache = new BABYLON.StringDictionary();
  46705. }
  46706. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  46707. return this._modelCache.getOrAddWithFactory(key, factory);
  46708. };
  46709. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  46710. if (!modelRenderCache.isDisposed) {
  46711. return false;
  46712. }
  46713. this._modelCache.remove(modelRenderCache.modelKey);
  46714. return true;
  46715. };
  46716. return Canvas2DEngineBoundData;
  46717. })();
  46718. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  46719. var Canvas2D = (function (_super) {
  46720. __extends(Canvas2D, _super);
  46721. function Canvas2D(scene, settings) {
  46722. var _this = this;
  46723. _super.call(this, settings);
  46724. /**
  46725. * 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.
  46726. * Beware that you have to take under consideration the origin in your calculations! Good luck!
  46727. */
  46728. this.worldSpaceToNodeLocal = function (worldPos) {
  46729. var node = _this._worldSpaceNode;
  46730. if (!node) {
  46731. return;
  46732. }
  46733. var mtx = node.getWorldMatrix().clone();
  46734. mtx.invert();
  46735. var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
  46736. var res = new BABYLON.Vector2(v.x, v.y);
  46737. var size = _this.actualSize;
  46738. res.x += size.width * 0.5; // res is centered, make it relative to bottom/left
  46739. res.y += size.height * 0.5;
  46740. return res;
  46741. };
  46742. /**
  46743. * 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
  46744. */
  46745. this.worldSpaceCacheChanged = function () {
  46746. var plane = _this.worldSpaceCanvasNode;
  46747. var vd = BABYLON.VertexData.ExtractFromMesh(plane); //new VertexData();
  46748. vd.uvs = new Float32Array(8);
  46749. var material = plane.material;
  46750. var tex = _this._renderableData._cacheTexture;
  46751. if (material.diffuseTexture !== tex) {
  46752. material.diffuseTexture = tex;
  46753. tex.hasAlpha = true;
  46754. }
  46755. var nodeuv = _this._renderableData._cacheNodeUVs;
  46756. for (var i = 0; i < 4; i++) {
  46757. vd.uvs[i * 2 + 0] = nodeuv[i].x;
  46758. vd.uvs[i * 2 + 1] = nodeuv[i].y;
  46759. }
  46760. vd.applyToMesh(plane);
  46761. };
  46762. this._notifDebugMode = false;
  46763. this._mapCounter = 0;
  46764. this._drawCallsOpaqueCounter = new BABYLON.PerfCounter();
  46765. this._drawCallsAlphaTestCounter = new BABYLON.PerfCounter();
  46766. this._drawCallsTransparentCounter = new BABYLON.PerfCounter();
  46767. this._groupRenderCounter = new BABYLON.PerfCounter();
  46768. this._updateTransparentDataCounter = new BABYLON.PerfCounter();
  46769. this._cachedGroupRenderCounter = new BABYLON.PerfCounter();
  46770. this._updateCachedStateCounter = new BABYLON.PerfCounter();
  46771. this._updateLayoutCounter = new BABYLON.PerfCounter();
  46772. this._updatePositioningCounter = new BABYLON.PerfCounter();
  46773. this._updateLocalTransformCounter = new BABYLON.PerfCounter();
  46774. this._updateGlobalTransformCounter = new BABYLON.PerfCounter();
  46775. this._boundingInfoRecomputeCounter = new BABYLON.PerfCounter();
  46776. this._profileInfoText = null;
  46777. BABYLON.Prim2DBase._isCanvasInit = false;
  46778. if (!settings) {
  46779. settings = {};
  46780. }
  46781. if (this._cachingStrategy !== Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  46782. this._background = new BABYLON.Rectangle2D({ parent: this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
  46783. this._background.zOrder = 1.0;
  46784. this._background.isPickable = false;
  46785. this._background.origin = BABYLON.Vector2.Zero();
  46786. this._background.levelVisible = false;
  46787. if (settings.backgroundRoundRadius != null) {
  46788. this.backgroundRoundRadius = settings.backgroundRoundRadius;
  46789. }
  46790. if (settings.backgroundBorder != null) {
  46791. if (typeof (settings.backgroundBorder) === "string") {
  46792. this.backgroundBorder = Canvas2D.GetBrushFromString(settings.backgroundBorder);
  46793. }
  46794. else {
  46795. this.backgroundBorder = settings.backgroundBorder;
  46796. }
  46797. }
  46798. if (settings.backgroundBorderThickNess != null) {
  46799. this.backgroundBorderThickness = settings.backgroundBorderThickNess;
  46800. }
  46801. if (settings.backgroundFill != null) {
  46802. if (typeof (settings.backgroundFill) === "string") {
  46803. this.backgroundFill = Canvas2D.GetBrushFromString(settings.backgroundFill);
  46804. }
  46805. else {
  46806. this.backgroundFill = settings.backgroundFill;
  46807. }
  46808. }
  46809. this._background._patchHierarchy(this);
  46810. }
  46811. var engine = scene.getEngine();
  46812. this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  46813. this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  46814. this._capturedPointers = new BABYLON.StringDictionary();
  46815. this._pickStartingPosition = BABYLON.Vector2.Zero();
  46816. this._hierarchyLevelMaxSiblingCount = 50;
  46817. this._hierarchyDepth = 0;
  46818. this._zOrder = 0;
  46819. this._zMax = 1;
  46820. this._scene = scene;
  46821. this._engine = engine;
  46822. this._renderingSize = new BABYLON.Size(0, 0);
  46823. this._trackedGroups = new Array();
  46824. this._maxAdaptiveWorldSpaceCanvasSize = null;
  46825. this._groupCacheMaps = new BABYLON.StringDictionary();
  46826. this._patchHierarchy(this);
  46827. var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
  46828. this._fitRenderingDevice = !settings.size;
  46829. if (!settings.size) {
  46830. settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  46831. }
  46832. // Register scene dispose to also dispose the canvas when it'll happens
  46833. scene.onDisposeObservable.add(function (d, s) {
  46834. _this.dispose();
  46835. });
  46836. if (this._isScreenSpace) {
  46837. this._afterRenderObserver = this._scene.onAfterRenderObservable.add(function (d, s) {
  46838. _this._engine.clear(null, false, true, true);
  46839. _this._render();
  46840. });
  46841. }
  46842. else {
  46843. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function (d, s) {
  46844. _this._render();
  46845. });
  46846. }
  46847. this._supprtInstancedArray = this._engine.getCaps().instancedArrays !== null;
  46848. //this._supprtInstancedArray = false; // TODO REMOVE!!!
  46849. this._setupInteraction(enableInteraction);
  46850. }
  46851. Object.defineProperty(Canvas2D.prototype, "drawCallsOpaqueCounter", {
  46852. get: function () {
  46853. return this._drawCallsOpaqueCounter;
  46854. },
  46855. enumerable: true,
  46856. configurable: true
  46857. });
  46858. Object.defineProperty(Canvas2D.prototype, "drawCallsAlphaTestCounter", {
  46859. get: function () {
  46860. return this._drawCallsAlphaTestCounter;
  46861. },
  46862. enumerable: true,
  46863. configurable: true
  46864. });
  46865. Object.defineProperty(Canvas2D.prototype, "drawCallsTransparentCounter", {
  46866. get: function () {
  46867. return this._drawCallsTransparentCounter;
  46868. },
  46869. enumerable: true,
  46870. configurable: true
  46871. });
  46872. Object.defineProperty(Canvas2D.prototype, "groupRenderCounter", {
  46873. get: function () {
  46874. return this._groupRenderCounter;
  46875. },
  46876. enumerable: true,
  46877. configurable: true
  46878. });
  46879. Object.defineProperty(Canvas2D.prototype, "updateTransparentDataCounter", {
  46880. get: function () {
  46881. return this._updateTransparentDataCounter;
  46882. },
  46883. enumerable: true,
  46884. configurable: true
  46885. });
  46886. Object.defineProperty(Canvas2D.prototype, "cachedGroupRenderCounter", {
  46887. get: function () {
  46888. return this._cachedGroupRenderCounter;
  46889. },
  46890. enumerable: true,
  46891. configurable: true
  46892. });
  46893. Object.defineProperty(Canvas2D.prototype, "updateCachedStateCounter", {
  46894. get: function () {
  46895. return this._updateCachedStateCounter;
  46896. },
  46897. enumerable: true,
  46898. configurable: true
  46899. });
  46900. Object.defineProperty(Canvas2D.prototype, "updateLayoutCounter", {
  46901. get: function () {
  46902. return this._updateLayoutCounter;
  46903. },
  46904. enumerable: true,
  46905. configurable: true
  46906. });
  46907. Object.defineProperty(Canvas2D.prototype, "updatePositioningCounter", {
  46908. get: function () {
  46909. return this._updatePositioningCounter;
  46910. },
  46911. enumerable: true,
  46912. configurable: true
  46913. });
  46914. Object.defineProperty(Canvas2D.prototype, "updateLocalTransformCounter", {
  46915. get: function () {
  46916. return this._updateLocalTransformCounter;
  46917. },
  46918. enumerable: true,
  46919. configurable: true
  46920. });
  46921. Object.defineProperty(Canvas2D.prototype, "updateGlobalTransformCounter", {
  46922. get: function () {
  46923. return this._updateGlobalTransformCounter;
  46924. },
  46925. enumerable: true,
  46926. configurable: true
  46927. });
  46928. Object.defineProperty(Canvas2D.prototype, "boundingInfoRecomputeCounter", {
  46929. get: function () {
  46930. return this._boundingInfoRecomputeCounter;
  46931. },
  46932. enumerable: true,
  46933. configurable: true
  46934. });
  46935. Canvas2D.prototype._canvasPreInit = function (settings) {
  46936. var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
  46937. this._cachingStrategy = cachingStrategy;
  46938. this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
  46939. };
  46940. Canvas2D.prototype._setupInteraction = function (enable) {
  46941. var _this = this;
  46942. // No change detection
  46943. if (enable === this._interactionEnabled) {
  46944. return;
  46945. }
  46946. // Set the new state
  46947. this._interactionEnabled = enable;
  46948. // ScreenSpace mode
  46949. if (this._isScreenSpace) {
  46950. // Disable interaction
  46951. if (!enable) {
  46952. if (this._scenePrePointerObserver) {
  46953. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  46954. this._scenePrePointerObserver = null;
  46955. }
  46956. return;
  46957. }
  46958. // Enable Interaction
  46959. // Register the observable
  46960. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  46961. var hs = 1 / _this.engine.getHardwareScalingLevel();
  46962. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  46963. _this._handlePointerEventForInteraction(e, localPos, s);
  46964. });
  46965. }
  46966. else {
  46967. var scene = this.scene;
  46968. if (enable) {
  46969. scene.constantlyUpdateMeshUnderPointer = true;
  46970. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  46971. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  46972. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  46973. _this._handlePointerEventForInteraction(e, localPos, s);
  46974. }
  46975. });
  46976. }
  46977. else {
  46978. if (this._scenePointerObserver) {
  46979. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  46980. this._scenePointerObserver = null;
  46981. }
  46982. }
  46983. }
  46984. };
  46985. /**
  46986. * Internal method, you should use the Prim2DBase version instead
  46987. */
  46988. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  46989. if (this.isPointerCaptured(pointerId)) {
  46990. return false;
  46991. }
  46992. // Try to capture the pointer on the HTML side
  46993. try {
  46994. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  46995. }
  46996. catch (e) {
  46997. }
  46998. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  46999. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  47000. this._capturedPointers.add(pointerId.toString(), primitive);
  47001. return true;
  47002. };
  47003. /**
  47004. * Internal method, you should use the Prim2DBase version instead
  47005. */
  47006. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  47007. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  47008. return false;
  47009. }
  47010. // Try to release the pointer on the HTML side
  47011. try {
  47012. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  47013. }
  47014. catch (e) {
  47015. }
  47016. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  47017. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  47018. this._capturedPointers.remove(pointerId.toString());
  47019. return true;
  47020. };
  47021. /**
  47022. * Determine if the given pointer is captured or not
  47023. * @param pointerId the Id of the pointer
  47024. * @return true if it's captured, false otherwise
  47025. */
  47026. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  47027. return this._capturedPointers.contains(pointerId.toString());
  47028. };
  47029. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  47030. // Avoid unnecessary lookup
  47031. if (this._capturedPointers.count === 0) {
  47032. return null;
  47033. }
  47034. return this._capturedPointers.get(pointerId.toString());
  47035. };
  47036. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  47037. // Dispose check
  47038. if (this.isDisposed) {
  47039. return;
  47040. }
  47041. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  47042. this._updatePointerInfo(eventData, localPosition);
  47043. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  47044. // 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.
  47045. // 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.
  47046. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, capturedPrim !== null);
  47047. // 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
  47048. this._updateOverStatus();
  47049. // Check if we have nothing to raise
  47050. if (!this._actualOverPrimitive && !capturedPrim) {
  47051. return;
  47052. }
  47053. // Update the relatedTarget info with the over primitive or the captured one (if any)
  47054. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  47055. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  47056. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  47057. // Analyze the pointer event type and fire proper events on the primitive
  47058. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  47059. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData.event);
  47060. }
  47061. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47062. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData.event);
  47063. }
  47064. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  47065. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData.event);
  47066. }
  47067. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  47068. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData.event);
  47069. }
  47070. };
  47071. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  47072. var pii = this._primPointerInfo;
  47073. if (!pii.canvasPointerPos) {
  47074. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  47075. }
  47076. var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
  47077. var engine = this._scene.getEngine();
  47078. if (this._isScreenSpace) {
  47079. var cameraViewport = camera.viewport;
  47080. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  47081. // Moving coordinates to local viewport world
  47082. var x = localPosition.x - viewport.x;
  47083. var y = localPosition.y - viewport.y;
  47084. pii.canvasPointerPos.x = x - this.actualPosition.x;
  47085. pii.canvasPointerPos.y = engine.getRenderHeight() - y - this.actualPosition.y;
  47086. }
  47087. else {
  47088. pii.canvasPointerPos.x = localPosition.x;
  47089. pii.canvasPointerPos.y = localPosition.y;
  47090. }
  47091. pii.mouseWheelDelta = 0;
  47092. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  47093. var event = eventData.event;
  47094. if (event.wheelDelta) {
  47095. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  47096. }
  47097. else if (event.detail) {
  47098. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  47099. }
  47100. }
  47101. else {
  47102. var pe = eventData.event;
  47103. pii.ctrlKey = pe.ctrlKey;
  47104. pii.altKey = pe.altKey;
  47105. pii.shiftKey = pe.shiftKey;
  47106. pii.metaKey = pe.metaKey;
  47107. pii.button = pe.button;
  47108. pii.buttons = pe.buttons;
  47109. pii.pointerId = pe.pointerId;
  47110. pii.width = pe.width;
  47111. pii.height = pe.height;
  47112. pii.presssure = pe.pressure;
  47113. pii.tilt.x = pe.tiltX;
  47114. pii.tilt.y = pe.tiltY;
  47115. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  47116. }
  47117. };
  47118. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture) {
  47119. if (this.scene.getRenderId() === this._intersectionRenderId) {
  47120. return;
  47121. }
  47122. // 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
  47123. if (!this._globalTransform) {
  47124. this.updateCachedStates(true);
  47125. }
  47126. var ii = Canvas2D._interInfo;
  47127. ii.pickPosition.x = mouseLocalPos.x;
  47128. ii.pickPosition.y = mouseLocalPos.y;
  47129. ii.findFirstOnly = false;
  47130. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  47131. if (!isCapture && !this.levelBoundingInfo.doesIntersect(ii.pickPosition)) {
  47132. this._previousIntersectionList = this._actualIntersectionList;
  47133. this._actualIntersectionList = null;
  47134. this._previousOverPrimitive = this._actualOverPrimitive;
  47135. this._actualOverPrimitive = null;
  47136. return;
  47137. }
  47138. this.intersect(ii);
  47139. this._previousIntersectionList = this._actualIntersectionList;
  47140. this._actualIntersectionList = ii.intersectedPrimitives;
  47141. this._previousOverPrimitive = this._actualOverPrimitive;
  47142. this._actualOverPrimitive = ii.topMostIntersectedPrimitive;
  47143. this._intersectionRenderId = this.scene.getRenderId();
  47144. };
  47145. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  47146. Canvas2D.prototype._updateOverStatus = function () {
  47147. if ((this.scene.getRenderId() === this._hoverStatusRenderId) || !this._previousIntersectionList || !this._actualIntersectionList) {
  47148. return;
  47149. }
  47150. // Detect a change of over
  47151. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  47152. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  47153. if (prevPrim !== actualPrim) {
  47154. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  47155. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  47156. // Notify the previous "over" prim that the pointer is no longer over it
  47157. if ((capturedPrim && capturedPrim === prevPrim) || (!capturedPrim && prevPrim)) {
  47158. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  47159. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  47160. }
  47161. // Notify the new "over" prim that the pointer is over it
  47162. if ((capturedPrim && capturedPrim === actualPrim) || (!capturedPrim && actualPrim)) {
  47163. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  47164. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  47165. }
  47166. }
  47167. this._hoverStatusRenderId = this.scene.getRenderId();
  47168. };
  47169. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  47170. if (this._primPointerInfo.isCaptured) {
  47171. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  47172. }
  47173. else {
  47174. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  47175. var pii = _a[_i];
  47176. if (pii.prim === prim) {
  47177. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  47178. return;
  47179. }
  47180. }
  47181. }
  47182. };
  47183. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  47184. if (!this._notifDebugMode) {
  47185. return;
  47186. }
  47187. var debug = "";
  47188. for (var i = 0; i < prim.hierarchyDepth; i++) {
  47189. debug += " ";
  47190. }
  47191. var pii = this._primPointerInfo;
  47192. 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();
  47193. console.log(debug);
  47194. };
  47195. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  47196. var ppi = this._primPointerInfo;
  47197. // In case of PointerOver/Out we will first notify the parent with PointerEnter/Leave
  47198. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) !== 0) {
  47199. this._notifParents(prim, mask);
  47200. }
  47201. var bubbleCancelled = false;
  47202. var cur = prim;
  47203. while (cur) {
  47204. // Only trigger the observers if the primitive is intersected (except for out)
  47205. if (!bubbleCancelled) {
  47206. this._updatePrimPointerPos(cur);
  47207. // Exec the observers
  47208. this._debugExecObserver(cur, mask);
  47209. cur._pointerEventObservable.notifyObservers(ppi, mask);
  47210. this._triggerActionManager(cur, ppi, mask, eventData);
  47211. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  47212. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  47213. if (ppi.cancelBubble) {
  47214. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) === 0) {
  47215. return;
  47216. }
  47217. // We're dealing with PointerOver/Out, let's keep looping to fire PointerEnter/Leave, but not Over/Out anymore
  47218. bubbleCancelled = true;
  47219. }
  47220. }
  47221. // If bubble is cancel we didn't update the Primitive Pointer Pos yet, let's do it
  47222. if (bubbleCancelled) {
  47223. this._updatePrimPointerPos(cur);
  47224. }
  47225. // Trigger a PointerEnter corresponding to the PointerOver
  47226. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  47227. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerEnter);
  47228. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  47229. }
  47230. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  47231. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerLeave);
  47232. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  47233. }
  47234. // Loop to the parent
  47235. cur = cur.parent;
  47236. }
  47237. };
  47238. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  47239. var _this = this;
  47240. // 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
  47241. if (!this._globalTransform) {
  47242. this.updateCachedStates(true);
  47243. }
  47244. // Process Trigger related to PointerDown
  47245. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  47246. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  47247. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  47248. this._pickStartingTime = new Date().getTime();
  47249. this._pickedDownPrim = null;
  47250. if (prim.actionManager) {
  47251. this._pickedDownPrim = prim;
  47252. if (prim.actionManager.hasPickTriggers) {
  47253. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  47254. switch (eventData.button) {
  47255. case 0:
  47256. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  47257. break;
  47258. case 1:
  47259. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  47260. break;
  47261. case 2:
  47262. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  47263. break;
  47264. }
  47265. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  47266. }
  47267. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  47268. window.setTimeout(function () {
  47269. var ppi = _this._primPointerInfo;
  47270. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  47271. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null);
  47272. var ii = new BABYLON.IntersectInfo2D();
  47273. ii.pickPosition = ppi.canvasPointerPos.clone();
  47274. ii.findFirstOnly = false;
  47275. _this.intersect(ii);
  47276. if (ii.isPrimIntersected(prim) !== null) {
  47277. if (prim.actionManager) {
  47278. 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)) {
  47279. _this._pickStartingTime = 0;
  47280. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  47281. }
  47282. }
  47283. }
  47284. }, BABYLON.ActionManager.LongPressDelay);
  47285. }
  47286. }
  47287. }
  47288. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  47289. this._pickStartingTime = 0;
  47290. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  47291. if (prim.actionManager) {
  47292. // OnPickUpTrigger
  47293. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  47294. // OnPickTrigger
  47295. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  47296. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  47297. }
  47298. }
  47299. // OnPickOutTrigger
  47300. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  47301. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  47302. }
  47303. }
  47304. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  47305. if (prim.actionManager) {
  47306. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  47307. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  47308. }
  47309. }
  47310. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  47311. if (prim.actionManager) {
  47312. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  47313. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  47314. }
  47315. }
  47316. };
  47317. Canvas2D.prototype._notifParents = function (prim, mask) {
  47318. var pii = this._primPointerInfo;
  47319. var curPrim = this;
  47320. while (curPrim) {
  47321. this._updatePrimPointerPos(curPrim);
  47322. // Fire the proper notification
  47323. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  47324. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerEnter);
  47325. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerEnter);
  47326. }
  47327. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  47328. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerLeave);
  47329. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerLeave);
  47330. }
  47331. curPrim = curPrim.parent;
  47332. }
  47333. };
  47334. /**
  47335. * Don't forget to call the dispose method when you're done with the Canvas instance.
  47336. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  47337. */
  47338. Canvas2D.prototype.dispose = function () {
  47339. if (!_super.prototype.dispose.call(this)) {
  47340. return false;
  47341. }
  47342. if (this._profilingCanvas) {
  47343. this._profilingCanvas.dispose();
  47344. this._profilingCanvas = null;
  47345. }
  47346. if (this.interactionEnabled) {
  47347. this._setupInteraction(false);
  47348. }
  47349. if (this._beforeRenderObserver) {
  47350. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  47351. this._beforeRenderObserver = null;
  47352. }
  47353. if (this._afterRenderObserver) {
  47354. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  47355. this._afterRenderObserver = null;
  47356. }
  47357. if (this._groupCacheMaps) {
  47358. this._groupCacheMaps.forEach(function (k, m) { return m.forEach(function (e) { return e.dispose(); }); });
  47359. this._groupCacheMaps = null;
  47360. }
  47361. };
  47362. Object.defineProperty(Canvas2D.prototype, "scene", {
  47363. /**
  47364. * Accessor to the Scene that owns the Canvas
  47365. * @returns The instance of the Scene object
  47366. */
  47367. get: function () {
  47368. return this._scene;
  47369. },
  47370. enumerable: true,
  47371. configurable: true
  47372. });
  47373. Object.defineProperty(Canvas2D.prototype, "engine", {
  47374. /**
  47375. * Accessor to the Engine that drives the Scene used by this Canvas
  47376. * @returns The instance of the Engine object
  47377. */
  47378. get: function () {
  47379. return this._engine;
  47380. },
  47381. enumerable: true,
  47382. configurable: true
  47383. });
  47384. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  47385. /**
  47386. * Accessor of the Caching Strategy used by this Canvas.
  47387. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  47388. * @returns the value corresponding to the used strategy.
  47389. */
  47390. get: function () {
  47391. return this._cachingStrategy;
  47392. },
  47393. enumerable: true,
  47394. configurable: true
  47395. });
  47396. Object.defineProperty(Canvas2D.prototype, "isScreenSpace", {
  47397. /**
  47398. * Return true if the Canvas is a Screen Space one, false if it's a World Space one.
  47399. * @returns {}
  47400. */
  47401. get: function () {
  47402. return this._isScreenSpace;
  47403. },
  47404. enumerable: true,
  47405. configurable: true
  47406. });
  47407. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  47408. /**
  47409. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  47410. */
  47411. get: function () {
  47412. return this._worldSpaceNode;
  47413. },
  47414. set: function (val) {
  47415. this._worldSpaceNode = val;
  47416. },
  47417. enumerable: true,
  47418. configurable: true
  47419. });
  47420. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  47421. /**
  47422. * Check if the WebGL Instanced Array extension is supported or not
  47423. */
  47424. get: function () {
  47425. return this._supprtInstancedArray;
  47426. },
  47427. enumerable: true,
  47428. configurable: true
  47429. });
  47430. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  47431. /**
  47432. * Property that defines the fill object used to draw the background of the Canvas.
  47433. * Note that Canvas with a Caching Strategy of
  47434. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  47435. */
  47436. get: function () {
  47437. if (!this._background || !this._background.isVisible) {
  47438. return null;
  47439. }
  47440. return this._background.fill;
  47441. },
  47442. set: function (value) {
  47443. this.checkBackgroundAvailability();
  47444. if (value === this._background.fill) {
  47445. return;
  47446. }
  47447. this._background.fill = value;
  47448. this._background.levelVisible = true;
  47449. },
  47450. enumerable: true,
  47451. configurable: true
  47452. });
  47453. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  47454. /**
  47455. * Property that defines the border object used to draw the background of the Canvas.
  47456. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  47457. */
  47458. get: function () {
  47459. if (!this._background || !this._background.isVisible) {
  47460. return null;
  47461. }
  47462. return this._background.border;
  47463. },
  47464. set: function (value) {
  47465. this.checkBackgroundAvailability();
  47466. if (value === this._background.border) {
  47467. return;
  47468. }
  47469. this._background.border = value;
  47470. this._background.levelVisible = true;
  47471. },
  47472. enumerable: true,
  47473. configurable: true
  47474. });
  47475. Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
  47476. /**
  47477. * Property that defines the thickness of the border object used to draw the background of the Canvas.
  47478. * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
  47479. */
  47480. get: function () {
  47481. if (!this._background || !this._background.isVisible) {
  47482. return null;
  47483. }
  47484. return this._background.borderThickness;
  47485. },
  47486. set: function (value) {
  47487. this.checkBackgroundAvailability();
  47488. if (value === this._background.borderThickness) {
  47489. return;
  47490. }
  47491. this._background.borderThickness = value;
  47492. },
  47493. enumerable: true,
  47494. configurable: true
  47495. });
  47496. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  47497. /**
  47498. * You can set the roundRadius of the background
  47499. * @returns The current roundRadius
  47500. */
  47501. get: function () {
  47502. if (!this._background || !this._background.isVisible) {
  47503. return null;
  47504. }
  47505. return this._background.roundRadius;
  47506. },
  47507. set: function (value) {
  47508. this.checkBackgroundAvailability();
  47509. if (value === this._background.roundRadius) {
  47510. return;
  47511. }
  47512. this._background.roundRadius = value;
  47513. this._background.levelVisible = true;
  47514. },
  47515. enumerable: true,
  47516. configurable: true
  47517. });
  47518. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  47519. /**
  47520. * Enable/Disable interaction for this Canvas
  47521. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  47522. */
  47523. get: function () {
  47524. return this._interactionEnabled;
  47525. },
  47526. set: function (enable) {
  47527. this._setupInteraction(enable);
  47528. },
  47529. enumerable: true,
  47530. configurable: true
  47531. });
  47532. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  47533. /**
  47534. * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
  47535. * @returns {}
  47536. */
  47537. get: function () {
  47538. return this.__engineData;
  47539. },
  47540. enumerable: true,
  47541. configurable: true
  47542. });
  47543. Canvas2D.prototype.createCanvasProfileInfoCanvas = function () {
  47544. if (this._profilingCanvas) {
  47545. return this._profilingCanvas;
  47546. }
  47547. var canvas = new ScreenSpaceCanvas2D(this.scene, {
  47548. id: "ProfileInfoCanvas", cachingStrategy: Canvas2D.CACHESTRATEGY_DONTCACHE, children: [
  47549. new BABYLON.Rectangle2D({
  47550. id: "ProfileBorder", border: "#FFFFFFFF", borderThickness: 2, roundRadius: 5, fill: "#C04040C0", marginAlignment: "h: left, v: top", margin: "10", padding: "10", children: [
  47551. new BABYLON.Text2D("Stats", { id: "ProfileInfoText", marginAlignment: "h: left, v: top", fontName: "10pt Lucida Console" })
  47552. ]
  47553. })
  47554. ]
  47555. });
  47556. this._profileInfoText = canvas.findById("ProfileInfoText");
  47557. this._profilingCanvas = canvas;
  47558. return canvas;
  47559. };
  47560. Canvas2D.prototype.checkBackgroundAvailability = function () {
  47561. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  47562. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  47563. }
  47564. };
  47565. Canvas2D.prototype._initPerfMetrics = function () {
  47566. this._drawCallsOpaqueCounter.fetchNewFrame();
  47567. this._drawCallsAlphaTestCounter.fetchNewFrame();
  47568. this._drawCallsTransparentCounter.fetchNewFrame();
  47569. this._groupRenderCounter.fetchNewFrame();
  47570. this._updateTransparentDataCounter.fetchNewFrame();
  47571. this._cachedGroupRenderCounter.fetchNewFrame();
  47572. this._updateCachedStateCounter.fetchNewFrame();
  47573. this._updateLayoutCounter.fetchNewFrame();
  47574. this._updatePositioningCounter.fetchNewFrame();
  47575. this._updateLocalTransformCounter.fetchNewFrame();
  47576. this._updateGlobalTransformCounter.fetchNewFrame();
  47577. this._boundingInfoRecomputeCounter.fetchNewFrame();
  47578. };
  47579. Canvas2D.prototype._fetchPerfMetrics = function () {
  47580. this._drawCallsOpaqueCounter.addCount(0, true);
  47581. this._drawCallsAlphaTestCounter.addCount(0, true);
  47582. this._drawCallsTransparentCounter.addCount(0, true);
  47583. this._groupRenderCounter.addCount(0, true);
  47584. this._updateTransparentDataCounter.addCount(0, true);
  47585. this._cachedGroupRenderCounter.addCount(0, true);
  47586. this._updateCachedStateCounter.addCount(0, true);
  47587. this._updateLayoutCounter.addCount(0, true);
  47588. this._updatePositioningCounter.addCount(0, true);
  47589. this._updateLocalTransformCounter.addCount(0, true);
  47590. this._updateGlobalTransformCounter.addCount(0, true);
  47591. this._boundingInfoRecomputeCounter.addCount(0, true);
  47592. };
  47593. Canvas2D.prototype._updateProfileCanvas = function () {
  47594. if (this._profileInfoText == null) {
  47595. return;
  47596. }
  47597. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  47598. var p = "Draw Calls:\n" +
  47599. (" - Opaque: " + format(this.drawCallsOpaqueCounter.current) + ", (avg:" + format(this.drawCallsOpaqueCounter.lastSecAverage) + ", t:" + format(this.drawCallsOpaqueCounter.total) + ")\n") +
  47600. (" - AlphaTest: " + format(this.drawCallsAlphaTestCounter.current) + ", (avg:" + format(this.drawCallsAlphaTestCounter.lastSecAverage) + ", t:" + format(this.drawCallsAlphaTestCounter.total) + ")\n") +
  47601. (" - Transparent: " + format(this.drawCallsTransparentCounter.current) + ", (avg:" + format(this.drawCallsTransparentCounter.lastSecAverage) + ", t:" + format(this.drawCallsTransparentCounter.total) + ")\n") +
  47602. ("Group Render: " + this.groupRenderCounter.current + ", (avg:" + format(this.groupRenderCounter.lastSecAverage) + ", t:" + format(this.groupRenderCounter.total) + ")\n") +
  47603. ("Update Transparent Data: " + this.updateTransparentDataCounter.current + ", (avg:" + format(this.updateTransparentDataCounter.lastSecAverage) + ", t:" + format(this.updateTransparentDataCounter.total) + ")\n") +
  47604. ("Cached Group Render: " + this.cachedGroupRenderCounter.current + ", (avg:" + format(this.cachedGroupRenderCounter.lastSecAverage) + ", t:" + format(this.cachedGroupRenderCounter.total) + ")\n") +
  47605. ("Update Cached States: " + this.updateCachedStateCounter.current + ", (avg:" + format(this.updateCachedStateCounter.lastSecAverage) + ", t:" + format(this.updateCachedStateCounter.total) + ")\n") +
  47606. (" - Update Layout: " + this.updateLayoutCounter.current + ", (avg:" + format(this.updateLayoutCounter.lastSecAverage) + ", t:" + format(this.updateLayoutCounter.total) + ")\n") +
  47607. (" - Update Positioning: " + this.updatePositioningCounter.current + ", (avg:" + format(this.updatePositioningCounter.lastSecAverage) + ", t:" + format(this.updatePositioningCounter.total) + ")\n") +
  47608. (" - Update Local Trans: " + this.updateLocalTransformCounter.current + ", (avg:" + format(this.updateLocalTransformCounter.lastSecAverage) + ", t:" + format(this.updateLocalTransformCounter.total) + ")\n") +
  47609. (" - Update Global Trans: " + this.updateGlobalTransformCounter.current + ", (avg:" + format(this.updateGlobalTransformCounter.lastSecAverage) + ", t:" + format(this.updateGlobalTransformCounter.total) + ")\n") +
  47610. (" - BoundingInfo Recompute: " + this.boundingInfoRecomputeCounter.current + ", (avg:" + format(this.boundingInfoRecomputeCounter.lastSecAverage) + ", t:" + format(this.boundingInfoRecomputeCounter.total) + ")\n");
  47611. this._profileInfoText.text = p;
  47612. };
  47613. Canvas2D.prototype._addDrawCallCount = function (count, renderMode) {
  47614. switch (renderMode) {
  47615. case BABYLON.Render2DContext.RenderModeOpaque:
  47616. this._drawCallsOpaqueCounter.addCount(count, false);
  47617. return;
  47618. case BABYLON.Render2DContext.RenderModeAlphaTest:
  47619. this._drawCallsAlphaTestCounter.addCount(count, false);
  47620. return;
  47621. case BABYLON.Render2DContext.RenderModeTransparent:
  47622. this._drawCallsTransparentCounter.addCount(count, false);
  47623. return;
  47624. }
  47625. };
  47626. Canvas2D.prototype._addGroupRenderCount = function (count) {
  47627. this._groupRenderCounter.addCount(count, false);
  47628. };
  47629. Canvas2D.prototype._addUpdateTransparentDataCount = function (count) {
  47630. this._updateTransparentDataCounter.addCount(count, false);
  47631. };
  47632. Canvas2D.prototype.addCachedGroupRenderCounter = function (count) {
  47633. this._cachedGroupRenderCounter.addCount(count, false);
  47634. };
  47635. Canvas2D.prototype.addUpdateCachedStateCounter = function (count) {
  47636. this._updateCachedStateCounter.addCount(count, false);
  47637. };
  47638. Canvas2D.prototype.addUpdateLayoutCounter = function (count) {
  47639. this._updateLayoutCounter.addCount(count, false);
  47640. };
  47641. Canvas2D.prototype.addUpdatePositioningCounter = function (count) {
  47642. this._updatePositioningCounter.addCount(count, false);
  47643. };
  47644. Canvas2D.prototype.addupdateLocalTransformCounter = function (count) {
  47645. this._updateLocalTransformCounter.addCount(count, false);
  47646. };
  47647. Canvas2D.prototype.addUpdateGlobalTransformCounter = function (count) {
  47648. this._updateGlobalTransformCounter.addCount(count, false);
  47649. };
  47650. Canvas2D.prototype._updateTrackedNodes = function () {
  47651. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  47652. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  47653. var rh = this.engine.getRenderHeight();
  47654. var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
  47655. for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
  47656. var group = _a[_i];
  47657. if (group.isDisposed || !group.isVisible) {
  47658. continue;
  47659. }
  47660. var node = group.trackedNode;
  47661. var worldMtx = node.getWorldMatrix();
  47662. var proj = BABYLON.Vector3.Project(Canvas2D._v, worldMtx, Canvas2D._m, v);
  47663. group.x = Math.round(proj.x);
  47664. group.y = Math.round(rh - proj.y);
  47665. }
  47666. };
  47667. /**
  47668. * Call this method change you want to have layout related data computed and up to date (layout area, primitive area, local/global transformation matrices)
  47669. */
  47670. Canvas2D.prototype.updateCanvasLayout = function (forceRecompute) {
  47671. this._updateCanvasState(forceRecompute);
  47672. };
  47673. Canvas2D.prototype._updateAdaptiveSizeWorldCanvas = function () {
  47674. if (this._globalTransformStep < 2) {
  47675. return;
  47676. }
  47677. var n = this.worldSpaceCanvasNode;
  47678. var bi = n.getBoundingInfo().boundingBox;
  47679. var v = bi.vectorsWorld;
  47680. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  47681. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  47682. var vp = cam.viewport.toGlobal(this.engine.getRenderWidth(), this.engine.getRenderHeight());
  47683. var projPoints = new Array(4);
  47684. for (var i = 0; i < 4; i++) {
  47685. projPoints[i] = BABYLON.Vector3.Project(v[i], Canvas2D._mI, Canvas2D._m, vp);
  47686. }
  47687. var left = projPoints[3].subtract(projPoints[0]).length();
  47688. var top = projPoints[3].subtract(projPoints[1]).length();
  47689. var right = projPoints[1].subtract(projPoints[2]).length();
  47690. var bottom = projPoints[2].subtract(projPoints[0]).length();
  47691. var w = Math.round(Math.max(top, bottom));
  47692. var h = Math.round(Math.max(right, left));
  47693. var isW = w > h;
  47694. // Basically if it's under 256 we use 256, otherwise we take the biggest power of 2
  47695. var edge = Math.max(w, h);
  47696. if (edge < 256) {
  47697. edge = 256;
  47698. }
  47699. else {
  47700. edge = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  47701. }
  47702. // Clip values if needed
  47703. edge = Math.min(edge, this._maxAdaptiveWorldSpaceCanvasSize);
  47704. var newScale = edge / ((isW) ? this.size.width : this.size.height);
  47705. if (newScale !== this.scale) {
  47706. var scale = newScale;
  47707. // console.log(`New adaptive scale for Canvas ${this.id}, w: ${w}, h: ${h}, scale: ${scale}, edge: ${edge}, isW: ${isW}`);
  47708. this._setRenderingScale(scale);
  47709. }
  47710. };
  47711. Canvas2D.prototype._updateCanvasState = function (forceRecompute) {
  47712. // Check if the update has already been made for this render Frame
  47713. if (!forceRecompute && this.scene.getRenderId() === this._updateRenderId) {
  47714. return;
  47715. }
  47716. // Detect a change of rendering size
  47717. var renderingSizeChanged = false;
  47718. var newWidth = this.engine.getRenderWidth();
  47719. if (newWidth !== this._renderingSize.width) {
  47720. renderingSizeChanged = true;
  47721. }
  47722. this._renderingSize.width = newWidth;
  47723. var newHeight = this.engine.getRenderHeight();
  47724. if (newHeight !== this._renderingSize.height) {
  47725. renderingSizeChanged = true;
  47726. }
  47727. this._renderingSize.height = newHeight;
  47728. // If the canvas fit the rendering size and it changed, update
  47729. if (renderingSizeChanged && this._fitRenderingDevice) {
  47730. this.size = this._renderingSize;
  47731. if (this._background) {
  47732. this._background.size = this.size;
  47733. }
  47734. // Dirty the Layout at the Canvas level to recompute as the size changed
  47735. this._setLayoutDirty();
  47736. }
  47737. var context = new BABYLON.PrepareRender2DContext();
  47738. ++this._globalTransformProcessStep;
  47739. this.updateCachedStates(false);
  47740. this._prepareGroupRender(context);
  47741. this._updateRenderId = this.scene.getRenderId();
  47742. };
  47743. /**
  47744. * Method that renders the Canvas, you should not invoke
  47745. */
  47746. Canvas2D.prototype._render = function () {
  47747. this._initPerfMetrics();
  47748. this._updateTrackedNodes();
  47749. this._updateCanvasState(false);
  47750. if (!this._isScreenSpace) {
  47751. this._updateAdaptiveSizeWorldCanvas();
  47752. }
  47753. this._updateCanvasState(false);
  47754. if (this._primPointerInfo.canvasPointerPos) {
  47755. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false);
  47756. this._updateOverStatus(); // TODO this._primPointerInfo may not be up to date!
  47757. }
  47758. this.engine.setState(false);
  47759. this._groupRender();
  47760. if (!this._isScreenSpace) {
  47761. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagWorldCacheChanged)) {
  47762. this.worldSpaceCacheChanged();
  47763. this._clearFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  47764. }
  47765. }
  47766. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  47767. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  47768. this._cachedCanvasGroup._renderCachedCanvas();
  47769. }
  47770. this._fetchPerfMetrics();
  47771. this._updateProfileCanvas();
  47772. };
  47773. /**
  47774. * Internal method that allocate a cache for the given group.
  47775. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  47776. * @param group The group to allocate the cache of.
  47777. * @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.
  47778. */
  47779. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize, useMipMap, anisotropicLevel) {
  47780. if (useMipMap === void 0) { useMipMap = false; }
  47781. if (anisotropicLevel === void 0) { anisotropicLevel = 1; }
  47782. var key = (useMipMap ? "MipMap" : "NoMipMap") + "_" + anisotropicLevel;
  47783. // Determine size
  47784. var size = group.actualSize;
  47785. size = new BABYLON.Size(Math.ceil(size.width), Math.ceil(size.height));
  47786. if (minSize) {
  47787. size.width = Math.max(minSize.width, size.width);
  47788. size.height = Math.max(minSize.height, size.height);
  47789. }
  47790. var mapArray = this._groupCacheMaps.getOrAddWithFactory(key, function () { return new Array(); });
  47791. // Try to find a spot in one of the cached texture
  47792. var res = null;
  47793. var map;
  47794. for (var _i = 0; _i < mapArray.length; _i++) {
  47795. var _map = mapArray[_i];
  47796. map = _map;
  47797. var node = map.allocateRect(size);
  47798. if (node) {
  47799. res = { node: node, texture: map };
  47800. break;
  47801. }
  47802. }
  47803. // Couldn't find a map that could fit the rect, create a new map for it
  47804. if (!res) {
  47805. var mapSize = new BABYLON.Size(Canvas2D._groupTextureCacheSize, Canvas2D._groupTextureCacheSize);
  47806. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  47807. if (size.width > mapSize.width || size.height > mapSize.height) {
  47808. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  47809. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  47810. }
  47811. var id = "groupsMapChache" + this._mapCounter + "forCanvas" + this.id;
  47812. map = new BABYLON.MapTexture(id, this._scene, mapSize, useMipMap ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE, useMipMap);
  47813. map.anisotropicFilteringLevel = 4;
  47814. mapArray.splice(0, 0, map);
  47815. var node = map.allocateRect(size);
  47816. res = { node: node, texture: map };
  47817. }
  47818. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  47819. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  47820. if (group !== this || this._isScreenSpace) {
  47821. var node = res.node;
  47822. // 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
  47823. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS) {
  47824. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  47825. var sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: node.contentSize, spriteLocation: node.pos });
  47826. sprite.zOrder = 1;
  47827. sprite.origin = BABYLON.Vector2.Zero();
  47828. }
  47829. else {
  47830. var sprite = new BABYLON.Sprite2D(map, { parent: parent, id: "__cachedSpriteOfGroup__" + group.id, x: group.actualPosition.x, y: group.actualPosition.y, spriteSize: node.contentSize, spriteLocation: node.pos });
  47831. sprite.origin = group.origin.clone();
  47832. res.sprite = sprite;
  47833. }
  47834. }
  47835. return res;
  47836. };
  47837. /**
  47838. * Internal method used to register a Scene Node to track position for the given group
  47839. * Do not invoke this method, for internal purpose only.
  47840. * @param group the group to track its associated Scene Node
  47841. */
  47842. Canvas2D.prototype._registerTrackedNode = function (group) {
  47843. if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  47844. return;
  47845. }
  47846. this._trackedGroups.push(group);
  47847. group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  47848. };
  47849. /**
  47850. * Internal method used to unregister a tracked Scene Node
  47851. * Do not invoke this method, it's for internal purpose only.
  47852. * @param group the group to unregister its tracked Scene Node from.
  47853. */
  47854. Canvas2D.prototype._unregisterTrackedNode = function (group) {
  47855. if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  47856. return;
  47857. }
  47858. var i = this._trackedGroups.indexOf(group);
  47859. if (i !== -1) {
  47860. this._trackedGroups.splice(i, 1);
  47861. }
  47862. group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  47863. };
  47864. /**
  47865. * Get a Solid Color Brush instance matching the given color.
  47866. * @param color The color to retrieve
  47867. * @return A shared instance of the SolidColorBrush2D class that use the given color
  47868. */
  47869. Canvas2D.GetSolidColorBrush = function (color) {
  47870. return Canvas2D._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  47871. };
  47872. /**
  47873. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  47874. * @param color The color to retrieve
  47875. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  47876. */
  47877. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  47878. return Canvas2D._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  47879. };
  47880. /**
  47881. * Get a Gradient Color Brush
  47882. * @param color1 starting color
  47883. * @param color2 engine color
  47884. * @param translation translation vector to apply. default is [0;0]
  47885. * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
  47886. * @param scale scaling factor to apply. default is 1.
  47887. */
  47888. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  47889. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  47890. if (rotation === void 0) { rotation = 0; }
  47891. if (scale === void 0) { scale = 1; }
  47892. return Canvas2D._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  47893. };
  47894. /**
  47895. * Create a solid or gradient brush from a string value.
  47896. * @param brushString should be either
  47897. * - "solid: #RRGGBBAA" or "#RRGGBBAA"
  47898. * - "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.
  47899. */
  47900. Canvas2D.GetBrushFromString = function (brushString) {
  47901. // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
  47902. brushString = brushString.trim();
  47903. var split = brushString.split(",");
  47904. // Solid, formatted as: "[solid:]#FF808080"
  47905. if (split.length === 1) {
  47906. var value = null;
  47907. if (brushString.indexOf("solid:") === 0) {
  47908. value = brushString.substr(6).trim();
  47909. }
  47910. else if (brushString.indexOf("#") === 0) {
  47911. value = brushString;
  47912. }
  47913. else {
  47914. return null;
  47915. }
  47916. return Canvas2D.GetSolidColorBrushFromHex(value);
  47917. }
  47918. else {
  47919. if (split[0].indexOf("gradient:") === 0) {
  47920. split[0] = split[0].substr(9).trim();
  47921. }
  47922. try {
  47923. var start = BABYLON.Color4.FromHexString(split[0].trim());
  47924. var end = BABYLON.Color4.FromHexString(split[1].trim());
  47925. var t = BABYLON.Vector2.Zero();
  47926. if (split.length > 2) {
  47927. var v = split[2].trim();
  47928. if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
  47929. return null;
  47930. }
  47931. var sep = v.indexOf(":");
  47932. var x = parseFloat(v.substr(1, sep));
  47933. var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
  47934. t = new BABYLON.Vector2(x, y);
  47935. }
  47936. var r = 0;
  47937. if (split.length > 3) {
  47938. r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
  47939. }
  47940. var s = 1;
  47941. if (split.length > 4) {
  47942. s = parseFloat(split[4].trim());
  47943. }
  47944. return Canvas2D.GetGradientColorBrush(start, end, t, r, s);
  47945. }
  47946. catch (e) {
  47947. return null;
  47948. }
  47949. }
  47950. };
  47951. /**
  47952. * 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.
  47953. * This strategy doesn't allow primitives added directly as children of the Canvas.
  47954. * 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.
  47955. */
  47956. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  47957. /**
  47958. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  47959. * 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.
  47960. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  47961. * 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.
  47962. */
  47963. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  47964. /**
  47965. * 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).
  47966. */
  47967. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  47968. /**
  47969. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  47970. * 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).
  47971. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  47972. */
  47973. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  47974. Canvas2D._zMinDelta = 1 / (Math.pow(2, 24) - 1);
  47975. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  47976. Canvas2D._v = BABYLON.Vector3.Zero(); // Must stay zero
  47977. Canvas2D._m = BABYLON.Matrix.Identity();
  47978. Canvas2D._mI = BABYLON.Matrix.Identity(); // Must stay identity
  47979. /**
  47980. * Define the default size used for both the width and height of a MapTexture to allocate.
  47981. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  47982. */
  47983. Canvas2D._groupTextureCacheSize = 1024;
  47984. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  47985. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  47986. Canvas2D = __decorate([
  47987. BABYLON.className("Canvas2D")
  47988. ], Canvas2D);
  47989. return Canvas2D;
  47990. })(BABYLON.Group2D);
  47991. BABYLON.Canvas2D = Canvas2D;
  47992. var WorldSpaceCanvas2D = (function (_super) {
  47993. __extends(WorldSpaceCanvas2D, _super);
  47994. /**
  47995. * 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.
  47996. * 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.
  47997. * @param scene the Scene that owns the Canvas
  47998. * @param size the dimension of the Canvas in World Space
  47999. * @param settings a combination of settings, possible ones are
  48000. * - children: an array of direct children primitives
  48001. * - id: a text identifier, for information purpose only, default is null.
  48002. * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
  48003. * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  48004. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  48005. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  48006. * - 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).
  48007. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  48008. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  48009. * - 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.
  48010. * - 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.
  48011. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  48012. * - 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.
  48013. * - 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.
  48014. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  48015. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  48016. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  48017. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  48018. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  48019. */
  48020. function WorldSpaceCanvas2D(scene, size, settings) {
  48021. BABYLON.Prim2DBase._isCanvasInit = true;
  48022. var s = settings;
  48023. s.isScreenSpace = false;
  48024. s.size = size.clone();
  48025. settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
  48026. if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  48027. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  48028. }
  48029. _super.call(this, scene, settings);
  48030. BABYLON.Prim2DBase._isCanvasInit = false;
  48031. this._renderableData._useMipMap = true;
  48032. this._renderableData._anisotropicLevel = 8;
  48033. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  48034. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  48035. //}
  48036. var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
  48037. var id = settings ? settings.id || null : null;
  48038. // Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap
  48039. var capMaxTextSize = this.engine.getCaps().maxRenderTextureSize;
  48040. var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 4K if allowed otherwise the max allowed
  48041. if (settings.maxAdaptiveCanvasSize == null) {
  48042. this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;
  48043. }
  48044. else {
  48045. // We still clip the given value with the max allowed, the user may not be aware of these limitations
  48046. this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);
  48047. }
  48048. if (createWorldSpaceNode) {
  48049. var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, this);
  48050. var vertexData = BABYLON.VertexData.CreatePlane({
  48051. width: size.width,
  48052. height: size.height,
  48053. sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  48054. });
  48055. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  48056. this.applyCachedTexture(vertexData, mtl);
  48057. vertexData.applyToMesh(plane, true);
  48058. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  48059. mtl.disableLighting = true;
  48060. mtl.useAlphaFromDiffuseTexture = true;
  48061. plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
  48062. plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
  48063. plane.material = mtl;
  48064. this._worldSpaceNode = plane;
  48065. }
  48066. else {
  48067. this._worldSpaceNode = settings.customWorldSpaceNode;
  48068. this.applyCachedTexture(null, null);
  48069. }
  48070. }
  48071. WorldSpaceCanvas2D = __decorate([
  48072. BABYLON.className("WorldSpaceCanvas2D")
  48073. ], WorldSpaceCanvas2D);
  48074. return WorldSpaceCanvas2D;
  48075. })(Canvas2D);
  48076. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  48077. var ScreenSpaceCanvas2D = (function (_super) {
  48078. __extends(ScreenSpaceCanvas2D, _super);
  48079. /**
  48080. * 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.
  48081. * 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.
  48082. * All caching strategies will be available.
  48083. * 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]
  48084. * @param scene the Scene that owns the Canvas
  48085. * @param settings a combination of settings, possible ones are
  48086. * - children: an array of direct children primitives
  48087. * - id: a text identifier, for information purpose only
  48088. * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
  48089. * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
  48090. * - 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]
  48091. * - width: the width of the Canvas. you can alternatively use the size setting.
  48092. * - height: the height of the Canvas. you can alternatively use the size setting.
  48093. * - 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
  48094. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  48095. * - 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.
  48096. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  48097. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  48098. * - 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.
  48099. * - 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.
  48100. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  48101. * - 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.
  48102. * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  48103. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  48104. * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  48105. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  48106. * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
  48107. */
  48108. function ScreenSpaceCanvas2D(scene, settings) {
  48109. BABYLON.Prim2DBase._isCanvasInit = true;
  48110. _super.call(this, scene, settings);
  48111. }
  48112. ScreenSpaceCanvas2D = __decorate([
  48113. BABYLON.className("ScreenSpaceCanvas2D")
  48114. ], ScreenSpaceCanvas2D);
  48115. return ScreenSpaceCanvas2D;
  48116. })(Canvas2D);
  48117. BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
  48118. })(BABYLON || (BABYLON = {}));
  48119. var BABYLON;
  48120. (function (BABYLON) {
  48121. /**
  48122. * This is the class that is used to display a World Space Canvas into a 3D scene
  48123. */
  48124. var WorldSpaceCanvas2DNode = (function (_super) {
  48125. __extends(WorldSpaceCanvas2DNode, _super);
  48126. function WorldSpaceCanvas2DNode(name, scene, canvas) {
  48127. _super.call(this, name, scene);
  48128. this._canvas = canvas;
  48129. }
  48130. WorldSpaceCanvas2DNode.prototype.dispose = function () {
  48131. _super.prototype.dispose.call(this);
  48132. if (this._canvas) {
  48133. this._canvas.dispose();
  48134. this._canvas = null;
  48135. }
  48136. };
  48137. return WorldSpaceCanvas2DNode;
  48138. })(BABYLON.Mesh);
  48139. BABYLON.WorldSpaceCanvas2DNode = WorldSpaceCanvas2DNode;
  48140. })(BABYLON || (BABYLON = {}));
  48141. var BABYLON;
  48142. (function (BABYLON) {
  48143. var LayoutEngineBase = (function () {
  48144. function LayoutEngineBase() {
  48145. this.layoutDirtyOnPropertyChangedMask = 0;
  48146. }
  48147. LayoutEngineBase.prototype.updateLayout = function (prim) {
  48148. };
  48149. Object.defineProperty(LayoutEngineBase.prototype, "isChildPositionAllowed", {
  48150. get: function () {
  48151. return false;
  48152. },
  48153. enumerable: true,
  48154. configurable: true
  48155. });
  48156. LayoutEngineBase.prototype.isLocked = function () {
  48157. return this._isLocked;
  48158. };
  48159. LayoutEngineBase.prototype.lock = function () {
  48160. if (this._isLocked) {
  48161. return false;
  48162. }
  48163. this._isLocked = true;
  48164. return true;
  48165. };
  48166. LayoutEngineBase = __decorate([
  48167. BABYLON.className("LayoutEngineBase")
  48168. ], LayoutEngineBase);
  48169. return LayoutEngineBase;
  48170. })();
  48171. BABYLON.LayoutEngineBase = LayoutEngineBase;
  48172. var CanvasLayoutEngine = (function (_super) {
  48173. __extends(CanvasLayoutEngine, _super);
  48174. function CanvasLayoutEngine() {
  48175. _super.apply(this, arguments);
  48176. }
  48177. // A very simple (no) layout computing...
  48178. // The Canvas and its direct children gets the Canvas' size as Layout Area
  48179. // Indirect children have their Layout Area to the actualSize (margin area) of their parent
  48180. CanvasLayoutEngine.prototype.updateLayout = function (prim) {
  48181. // If this prim is layoutDiry we update its layoutArea and also the one of its direct children
  48182. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  48183. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  48184. var child = _a[_i];
  48185. this._doUpdate(child);
  48186. }
  48187. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  48188. }
  48189. };
  48190. CanvasLayoutEngine.prototype._doUpdate = function (prim) {
  48191. // Canvas ?
  48192. if (prim instanceof BABYLON.Canvas2D) {
  48193. prim.layoutArea = prim.actualSize;
  48194. }
  48195. else if (prim.parent instanceof BABYLON.Canvas2D) {
  48196. prim.layoutArea = prim.owner.actualSize;
  48197. }
  48198. else {
  48199. prim.layoutArea = prim.parent.contentArea;
  48200. }
  48201. };
  48202. Object.defineProperty(CanvasLayoutEngine.prototype, "isChildPositionAllowed", {
  48203. get: function () {
  48204. return true;
  48205. },
  48206. enumerable: true,
  48207. configurable: true
  48208. });
  48209. CanvasLayoutEngine.Singleton = new CanvasLayoutEngine();
  48210. CanvasLayoutEngine = __decorate([
  48211. BABYLON.className("CanvasLayoutEngine")
  48212. ], CanvasLayoutEngine);
  48213. return CanvasLayoutEngine;
  48214. })(LayoutEngineBase);
  48215. BABYLON.CanvasLayoutEngine = CanvasLayoutEngine;
  48216. var StackPanelLayoutEngine = (function (_super) {
  48217. __extends(StackPanelLayoutEngine, _super);
  48218. function StackPanelLayoutEngine() {
  48219. _super.call(this);
  48220. this._isHorizontal = true;
  48221. this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId;
  48222. }
  48223. Object.defineProperty(StackPanelLayoutEngine, "Horizontal", {
  48224. get: function () {
  48225. if (!StackPanelLayoutEngine._horizontal) {
  48226. StackPanelLayoutEngine._horizontal = new StackPanelLayoutEngine();
  48227. StackPanelLayoutEngine._horizontal.isHorizontal = true;
  48228. StackPanelLayoutEngine._horizontal.lock();
  48229. }
  48230. return StackPanelLayoutEngine._horizontal;
  48231. },
  48232. enumerable: true,
  48233. configurable: true
  48234. });
  48235. Object.defineProperty(StackPanelLayoutEngine, "Vertical", {
  48236. get: function () {
  48237. if (!StackPanelLayoutEngine._vertical) {
  48238. StackPanelLayoutEngine._vertical = new StackPanelLayoutEngine();
  48239. StackPanelLayoutEngine._vertical.isHorizontal = false;
  48240. StackPanelLayoutEngine._vertical.lock();
  48241. }
  48242. return StackPanelLayoutEngine._vertical;
  48243. },
  48244. enumerable: true,
  48245. configurable: true
  48246. });
  48247. Object.defineProperty(StackPanelLayoutEngine.prototype, "isHorizontal", {
  48248. get: function () {
  48249. return this._isHorizontal;
  48250. },
  48251. set: function (val) {
  48252. if (this.isLocked()) {
  48253. return;
  48254. }
  48255. this._isHorizontal = val;
  48256. },
  48257. enumerable: true,
  48258. configurable: true
  48259. });
  48260. StackPanelLayoutEngine.prototype.updateLayout = function (prim) {
  48261. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  48262. var x = 0;
  48263. var y = 0;
  48264. var h = this.isHorizontal;
  48265. var max = 0;
  48266. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  48267. var child = _a[_i];
  48268. var layoutArea = child.layoutArea;
  48269. child.margin.computeArea(child.actualSize, layoutArea);
  48270. max = Math.max(max, h ? layoutArea.height : layoutArea.width);
  48271. }
  48272. for (var _b = 0, _c = prim.children; _b < _c.length; _b++) {
  48273. var child = _c[_b];
  48274. child.layoutAreaPos = new BABYLON.Vector2(x, y);
  48275. var layoutArea = child.layoutArea;
  48276. if (h) {
  48277. x += layoutArea.width;
  48278. child.layoutArea = new BABYLON.Size(layoutArea.width, max);
  48279. }
  48280. else {
  48281. y += layoutArea.height;
  48282. child.layoutArea = new BABYLON.Size(max, layoutArea.height);
  48283. }
  48284. }
  48285. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  48286. }
  48287. };
  48288. Object.defineProperty(StackPanelLayoutEngine.prototype, "isChildPositionAllowed", {
  48289. get: function () {
  48290. return false;
  48291. },
  48292. enumerable: true,
  48293. configurable: true
  48294. });
  48295. StackPanelLayoutEngine._horizontal = null;
  48296. StackPanelLayoutEngine._vertical = null;
  48297. StackPanelLayoutEngine = __decorate([
  48298. BABYLON.className("StackPanelLayoutEngine")
  48299. ], StackPanelLayoutEngine);
  48300. return StackPanelLayoutEngine;
  48301. })(LayoutEngineBase);
  48302. BABYLON.StackPanelLayoutEngine = StackPanelLayoutEngine;
  48303. })(BABYLON || (BABYLON = {}));
  48304. var BABYLON;
  48305. (function (BABYLON) {
  48306. var ShaderMaterial = (function (_super) {
  48307. __extends(ShaderMaterial, _super);
  48308. function ShaderMaterial(name, scene, shaderPath, options) {
  48309. _super.call(this, name, scene);
  48310. this._textures = {};
  48311. this._textureArrays = {};
  48312. this._floats = {};
  48313. this._floatsArrays = {};
  48314. this._colors3 = {};
  48315. this._colors4 = {};
  48316. this._vectors2 = {};
  48317. this._vectors3 = {};
  48318. this._vectors4 = {};
  48319. this._matrices = {};
  48320. this._matrices3x3 = {};
  48321. this._matrices2x2 = {};
  48322. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  48323. this._shaderPath = shaderPath;
  48324. options.needAlphaBlending = options.needAlphaBlending || false;
  48325. options.needAlphaTesting = options.needAlphaTesting || false;
  48326. options.attributes = options.attributes || ["position", "normal", "uv"];
  48327. options.uniforms = options.uniforms || ["worldViewProjection"];
  48328. options.samplers = options.samplers || [];
  48329. options.defines = options.defines || [];
  48330. this._options = options;
  48331. }
  48332. ShaderMaterial.prototype.needAlphaBlending = function () {
  48333. return this._options.needAlphaBlending;
  48334. };
  48335. ShaderMaterial.prototype.needAlphaTesting = function () {
  48336. return this._options.needAlphaTesting;
  48337. };
  48338. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  48339. if (this._options.uniforms.indexOf(uniformName) === -1) {
  48340. this._options.uniforms.push(uniformName);
  48341. }
  48342. };
  48343. ShaderMaterial.prototype.setTexture = function (name, texture) {
  48344. if (this._options.samplers.indexOf(name) === -1) {
  48345. this._options.samplers.push(name);
  48346. }
  48347. this._textures[name] = texture;
  48348. return this;
  48349. };
  48350. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  48351. if (this._options.samplers.indexOf(name) === -1) {
  48352. this._options.samplers.push(name);
  48353. }
  48354. this._checkUniform(name);
  48355. this._textureArrays[name] = textures;
  48356. return this;
  48357. };
  48358. ShaderMaterial.prototype.setFloat = function (name, value) {
  48359. this._checkUniform(name);
  48360. this._floats[name] = value;
  48361. return this;
  48362. };
  48363. ShaderMaterial.prototype.setFloats = function (name, value) {
  48364. this._checkUniform(name);
  48365. this._floatsArrays[name] = value;
  48366. return this;
  48367. };
  48368. ShaderMaterial.prototype.setColor3 = function (name, value) {
  48369. this._checkUniform(name);
  48370. this._colors3[name] = value;
  48371. return this;
  48372. };
  48373. ShaderMaterial.prototype.setColor4 = function (name, value) {
  48374. this._checkUniform(name);
  48375. this._colors4[name] = value;
  48376. return this;
  48377. };
  48378. ShaderMaterial.prototype.setVector2 = function (name, value) {
  48379. this._checkUniform(name);
  48380. this._vectors2[name] = value;
  48381. return this;
  48382. };
  48383. ShaderMaterial.prototype.setVector3 = function (name, value) {
  48384. this._checkUniform(name);
  48385. this._vectors3[name] = value;
  48386. return this;
  48387. };
  48388. ShaderMaterial.prototype.setVector4 = function (name, value) {
  48389. this._checkUniform(name);
  48390. this._vectors4[name] = value;
  48391. return this;
  48392. };
  48393. ShaderMaterial.prototype.setMatrix = function (name, value) {
  48394. this._checkUniform(name);
  48395. this._matrices[name] = value;
  48396. return this;
  48397. };
  48398. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  48399. this._checkUniform(name);
  48400. this._matrices3x3[name] = value;
  48401. return this;
  48402. };
  48403. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  48404. this._checkUniform(name);
  48405. this._matrices2x2[name] = value;
  48406. return this;
  48407. };
  48408. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  48409. var scene = this.getScene();
  48410. var engine = scene.getEngine();
  48411. if (!this.checkReadyOnEveryCall) {
  48412. if (this._renderId === scene.getRenderId()) {
  48413. return true;
  48414. }
  48415. }
  48416. // Instances
  48417. var defines = [];
  48418. var fallbacks = new BABYLON.EffectFallbacks();
  48419. if (useInstances) {
  48420. defines.push("#define INSTANCES");
  48421. }
  48422. for (var index = 0; index < this._options.defines.length; index++) {
  48423. defines.push(this._options.defines[index]);
  48424. }
  48425. // Bones
  48426. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  48427. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48428. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48429. fallbacks.addCPUSkinningFallback(0, mesh);
  48430. }
  48431. // Alpha test
  48432. if (engine.getAlphaTesting()) {
  48433. defines.push("#define ALPHATEST");
  48434. }
  48435. var previousEffect = this._effect;
  48436. var join = defines.join("\n");
  48437. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  48438. if (!this._effect.isReady()) {
  48439. return false;
  48440. }
  48441. if (previousEffect !== this._effect) {
  48442. scene.resetCachedMaterial();
  48443. }
  48444. this._renderId = scene.getRenderId();
  48445. return true;
  48446. };
  48447. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  48448. var scene = this.getScene();
  48449. if (this._options.uniforms.indexOf("world") !== -1) {
  48450. this._effect.setMatrix("world", world);
  48451. }
  48452. if (this._options.uniforms.indexOf("worldView") !== -1) {
  48453. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  48454. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  48455. }
  48456. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  48457. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  48458. }
  48459. };
  48460. ShaderMaterial.prototype.bind = function (world, mesh) {
  48461. // Std values
  48462. this.bindOnlyWorldMatrix(world);
  48463. if (this.getScene().getCachedMaterial() !== this) {
  48464. if (this._options.uniforms.indexOf("view") !== -1) {
  48465. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  48466. }
  48467. if (this._options.uniforms.indexOf("projection") !== -1) {
  48468. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  48469. }
  48470. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  48471. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  48472. }
  48473. // Bones
  48474. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  48475. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  48476. }
  48477. var name;
  48478. // Texture
  48479. for (name in this._textures) {
  48480. this._effect.setTexture(name, this._textures[name]);
  48481. }
  48482. // Texture arrays
  48483. for (name in this._textureArrays) {
  48484. this._effect.setTextureArray(name, this._textureArrays[name]);
  48485. }
  48486. // Float
  48487. for (name in this._floats) {
  48488. this._effect.setFloat(name, this._floats[name]);
  48489. }
  48490. // Float s
  48491. for (name in this._floatsArrays) {
  48492. this._effect.setArray(name, this._floatsArrays[name]);
  48493. }
  48494. // Color3
  48495. for (name in this._colors3) {
  48496. this._effect.setColor3(name, this._colors3[name]);
  48497. }
  48498. // Color4
  48499. for (name in this._colors4) {
  48500. var color = this._colors4[name];
  48501. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  48502. }
  48503. // Vector2
  48504. for (name in this._vectors2) {
  48505. this._effect.setVector2(name, this._vectors2[name]);
  48506. }
  48507. // Vector3
  48508. for (name in this._vectors3) {
  48509. this._effect.setVector3(name, this._vectors3[name]);
  48510. }
  48511. // Vector4
  48512. for (name in this._vectors4) {
  48513. this._effect.setVector4(name, this._vectors4[name]);
  48514. }
  48515. // Matrix
  48516. for (name in this._matrices) {
  48517. this._effect.setMatrix(name, this._matrices[name]);
  48518. }
  48519. // Matrix 3x3
  48520. for (name in this._matrices3x3) {
  48521. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  48522. }
  48523. // Matrix 2x2
  48524. for (name in this._matrices2x2) {
  48525. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  48526. }
  48527. }
  48528. _super.prototype.bind.call(this, world, mesh);
  48529. };
  48530. ShaderMaterial.prototype.clone = function (name) {
  48531. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  48532. return newShaderMaterial;
  48533. };
  48534. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  48535. if (forceDisposeTextures) {
  48536. var name;
  48537. for (name in this._textures) {
  48538. this._textures[name].dispose();
  48539. }
  48540. for (name in this._textureArrays) {
  48541. var array = this._textureArrays[name];
  48542. for (var index = 0; index < array.length; index++) {
  48543. array[index].dispose();
  48544. }
  48545. }
  48546. }
  48547. this._textures = {};
  48548. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  48549. };
  48550. ShaderMaterial.prototype.serialize = function () {
  48551. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48552. serializationObject.customType = "BABYLON.ShaderMaterial";
  48553. serializationObject.options = this._options;
  48554. serializationObject.shaderPath = this._shaderPath;
  48555. var name;
  48556. // Texture
  48557. serializationObject.textures = {};
  48558. for (name in this._textures) {
  48559. serializationObject.textures[name] = this._textures[name].serialize();
  48560. }
  48561. // Texture arrays
  48562. serializationObject.textureArrays = {};
  48563. for (name in this._textureArrays) {
  48564. serializationObject.textureArrays[name] = [];
  48565. var array = this._textureArrays[name];
  48566. for (var index = 0; index < array.length; index++) {
  48567. serializationObject.textureArrays[name].push(array[index].serialize());
  48568. }
  48569. }
  48570. // Float
  48571. serializationObject.floats = {};
  48572. for (name in this._floats) {
  48573. serializationObject.floats[name] = this._floats[name];
  48574. }
  48575. // Float s
  48576. serializationObject.floatArrays = {};
  48577. for (name in this._floatsArrays) {
  48578. serializationObject.floatArrays[name] = this._floatsArrays[name];
  48579. }
  48580. // Color3
  48581. serializationObject.colors3 = {};
  48582. for (name in this._colors3) {
  48583. serializationObject.colors3[name] = this._colors3[name].asArray();
  48584. }
  48585. // Color4
  48586. serializationObject.colors4 = {};
  48587. for (name in this._colors4) {
  48588. serializationObject.colors4[name] = this._colors4[name].asArray();
  48589. }
  48590. // Vector2
  48591. serializationObject.vectors2 = {};
  48592. for (name in this._vectors2) {
  48593. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  48594. }
  48595. // Vector3
  48596. serializationObject.vectors3 = {};
  48597. for (name in this._vectors3) {
  48598. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  48599. }
  48600. // Vector4
  48601. serializationObject.vectors4 = {};
  48602. for (name in this._vectors4) {
  48603. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  48604. }
  48605. // Matrix
  48606. serializationObject.matrices = {};
  48607. for (name in this._matrices) {
  48608. serializationObject.matrices[name] = this._matrices[name].asArray();
  48609. }
  48610. // Matrix 3x3
  48611. serializationObject.matrices3x3 = {};
  48612. for (name in this._matrices3x3) {
  48613. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  48614. }
  48615. // Matrix 2x2
  48616. serializationObject.matrices2x2 = {};
  48617. for (name in this._matrices2x2) {
  48618. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  48619. }
  48620. return serializationObject;
  48621. };
  48622. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  48623. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  48624. var name;
  48625. // Texture
  48626. for (name in source.textures) {
  48627. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  48628. }
  48629. // Texture arrays
  48630. for (name in source.textureArrays) {
  48631. var array = source.textureArrays[name];
  48632. var textureArray = new Array();
  48633. for (var index = 0; index < array.length; index++) {
  48634. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  48635. }
  48636. material.setTextureArray(name, textureArray);
  48637. }
  48638. // Float
  48639. for (name in source.floats) {
  48640. material.setFloat(name, source.floats[name]);
  48641. }
  48642. // Float s
  48643. for (name in source.floatsArrays) {
  48644. material.setFloats(name, source.floatsArrays[name]);
  48645. }
  48646. // Color3
  48647. for (name in source.colors3) {
  48648. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  48649. }
  48650. // Color4
  48651. for (name in source.colors4) {
  48652. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  48653. }
  48654. // Vector2
  48655. for (name in source.vectors2) {
  48656. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  48657. }
  48658. // Vector3
  48659. for (name in source.vectors3) {
  48660. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  48661. }
  48662. // Vector4
  48663. for (name in source.vectors4) {
  48664. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  48665. }
  48666. // Matrix
  48667. for (name in source.matrices) {
  48668. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  48669. }
  48670. // Matrix 3x3
  48671. for (name in source.matrices3x3) {
  48672. material.setMatrix3x3(name, source.matrices3x3[name]);
  48673. }
  48674. // Matrix 2x2
  48675. for (name in source.matrices2x2) {
  48676. material.setMatrix2x2(name, source.matrices2x2[name]);
  48677. }
  48678. return material;
  48679. };
  48680. return ShaderMaterial;
  48681. })(BABYLON.Material);
  48682. BABYLON.ShaderMaterial = ShaderMaterial;
  48683. })(BABYLON || (BABYLON = {}));
  48684. var BABYLON;
  48685. (function (BABYLON) {
  48686. var Internals;
  48687. (function (Internals) {
  48688. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  48689. // All values and structures referenced from:
  48690. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  48691. var DDS_MAGIC = 0x20534444;
  48692. 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;
  48693. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  48694. 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;
  48695. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  48696. function FourCCToInt32(value) {
  48697. return value.charCodeAt(0) +
  48698. (value.charCodeAt(1) << 8) +
  48699. (value.charCodeAt(2) << 16) +
  48700. (value.charCodeAt(3) << 24);
  48701. }
  48702. function Int32ToFourCC(value) {
  48703. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  48704. }
  48705. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  48706. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  48707. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  48708. var headerLengthInt = 31; // The header length in 32 bit ints
  48709. // Offsets into the header array
  48710. var off_magic = 0;
  48711. var off_size = 1;
  48712. var off_flags = 2;
  48713. var off_height = 3;
  48714. var off_width = 4;
  48715. var off_mipmapCount = 7;
  48716. var off_pfFlags = 20;
  48717. var off_pfFourCC = 21;
  48718. var off_RGBbpp = 22;
  48719. var off_RMask = 23;
  48720. var off_GMask = 24;
  48721. var off_BMask = 25;
  48722. var off_AMask = 26;
  48723. var off_caps1 = 27;
  48724. var off_caps2 = 28;
  48725. ;
  48726. var DDSTools = (function () {
  48727. function DDSTools() {
  48728. }
  48729. DDSTools.GetDDSInfo = function (arrayBuffer) {
  48730. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  48731. var mipmapCount = 1;
  48732. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  48733. mipmapCount = Math.max(1, header[off_mipmapCount]);
  48734. }
  48735. return {
  48736. width: header[off_width],
  48737. height: header[off_height],
  48738. mipmapCount: mipmapCount,
  48739. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  48740. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  48741. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  48742. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  48743. };
  48744. };
  48745. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  48746. var byteArray = new Uint8Array(dataLength);
  48747. var srcData = new Uint8Array(arrayBuffer);
  48748. var index = 0;
  48749. for (var y = height - 1; y >= 0; y--) {
  48750. for (var x = 0; x < width; x++) {
  48751. var srcPos = dataOffset + (x + y * width) * 4;
  48752. byteArray[index + 2] = srcData[srcPos];
  48753. byteArray[index + 1] = srcData[srcPos + 1];
  48754. byteArray[index] = srcData[srcPos + 2];
  48755. byteArray[index + 3] = srcData[srcPos + 3];
  48756. index += 4;
  48757. }
  48758. }
  48759. return byteArray;
  48760. };
  48761. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  48762. var byteArray = new Uint8Array(dataLength);
  48763. var srcData = new Uint8Array(arrayBuffer);
  48764. var index = 0;
  48765. for (var y = height - 1; y >= 0; y--) {
  48766. for (var x = 0; x < width; x++) {
  48767. var srcPos = dataOffset + (x + y * width) * 3;
  48768. byteArray[index + 2] = srcData[srcPos];
  48769. byteArray[index + 1] = srcData[srcPos + 1];
  48770. byteArray[index] = srcData[srcPos + 2];
  48771. index += 3;
  48772. }
  48773. }
  48774. return byteArray;
  48775. };
  48776. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  48777. var byteArray = new Uint8Array(dataLength);
  48778. var srcData = new Uint8Array(arrayBuffer);
  48779. var index = 0;
  48780. for (var y = height - 1; y >= 0; y--) {
  48781. for (var x = 0; x < width; x++) {
  48782. var srcPos = dataOffset + (x + y * width);
  48783. byteArray[index] = srcData[srcPos];
  48784. index++;
  48785. }
  48786. }
  48787. return byteArray;
  48788. };
  48789. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  48790. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  48791. if (header[off_magic] != DDS_MAGIC) {
  48792. BABYLON.Tools.Error("Invalid magic number in DDS header");
  48793. return;
  48794. }
  48795. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  48796. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  48797. return;
  48798. }
  48799. if (info.isFourCC) {
  48800. fourCC = header[off_pfFourCC];
  48801. switch (fourCC) {
  48802. case FOURCC_DXT1:
  48803. blockBytes = 8;
  48804. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  48805. break;
  48806. case FOURCC_DXT3:
  48807. blockBytes = 16;
  48808. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  48809. break;
  48810. case FOURCC_DXT5:
  48811. blockBytes = 16;
  48812. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  48813. break;
  48814. default:
  48815. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  48816. return;
  48817. }
  48818. }
  48819. mipmapCount = 1;
  48820. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  48821. mipmapCount = Math.max(1, header[off_mipmapCount]);
  48822. }
  48823. var bpp = header[off_RGBbpp];
  48824. for (var face = 0; face < faces; face++) {
  48825. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  48826. width = header[off_width];
  48827. height = header[off_height];
  48828. dataOffset = header[off_size] + 4;
  48829. for (i = 0; i < mipmapCount; ++i) {
  48830. if (info.isRGB) {
  48831. if (bpp === 24) {
  48832. dataLength = width * height * 3;
  48833. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  48834. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  48835. }
  48836. else {
  48837. dataLength = width * height * 4;
  48838. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  48839. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  48840. }
  48841. }
  48842. else if (info.isLuminance) {
  48843. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  48844. var unpaddedRowSize = width;
  48845. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  48846. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  48847. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  48848. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  48849. }
  48850. else {
  48851. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  48852. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  48853. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  48854. }
  48855. dataOffset += dataLength;
  48856. width *= 0.5;
  48857. height *= 0.5;
  48858. width = Math.max(1.0, width);
  48859. height = Math.max(1.0, height);
  48860. }
  48861. }
  48862. };
  48863. return DDSTools;
  48864. })();
  48865. Internals.DDSTools = DDSTools;
  48866. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48867. })(BABYLON || (BABYLON = {}));
  48868. var BABYLON;
  48869. (function (BABYLON) {
  48870. var CannonJSPlugin = (function () {
  48871. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  48872. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  48873. if (iterations === void 0) { iterations = 10; }
  48874. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  48875. this.name = "CannonJSPlugin";
  48876. this._physicsMaterials = [];
  48877. this._fixedTimeStep = 1 / 60;
  48878. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  48879. this._currentCollisionGroup = 2;
  48880. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  48881. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  48882. this._tmpPosition = BABYLON.Vector3.Zero();
  48883. this._tmpQuaternion = new BABYLON.Quaternion();
  48884. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  48885. this._tmpDeltaRotation = new BABYLON.Quaternion();
  48886. this._tmpUnityRotation = new BABYLON.Quaternion();
  48887. if (!this.isSupported()) {
  48888. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  48889. return;
  48890. }
  48891. this.world = new CANNON.World();
  48892. this.world.broadphase = new CANNON.NaiveBroadphase();
  48893. this.world.solver.iterations = iterations;
  48894. }
  48895. CannonJSPlugin.prototype.setGravity = function (gravity) {
  48896. this.world.gravity.copy(gravity);
  48897. };
  48898. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  48899. this._fixedTimeStep = timeStep;
  48900. };
  48901. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  48902. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  48903. };
  48904. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  48905. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  48906. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  48907. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  48908. };
  48909. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  48910. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  48911. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  48912. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  48913. };
  48914. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  48915. //parent-child relationship. Does this impostor has a parent impostor?
  48916. if (impostor.parent) {
  48917. if (impostor.physicsBody) {
  48918. this.removePhysicsBody(impostor);
  48919. //TODO is that needed?
  48920. impostor.forceUpdate();
  48921. }
  48922. return;
  48923. }
  48924. //should a new body be created for this impostor?
  48925. if (impostor.isBodyInitRequired()) {
  48926. var shape = this._createShape(impostor);
  48927. //unregister events, if body is being changed
  48928. var oldBody = impostor.physicsBody;
  48929. if (oldBody) {
  48930. this.removePhysicsBody(impostor);
  48931. }
  48932. //create the body and material
  48933. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  48934. var bodyCreationObject = {
  48935. mass: impostor.getParam("mass"),
  48936. material: material
  48937. };
  48938. // A simple extend, in case native options were used.
  48939. var nativeOptions = impostor.getParam("nativeOptions");
  48940. for (var key in nativeOptions) {
  48941. if (nativeOptions.hasOwnProperty(key)) {
  48942. bodyCreationObject[key] = nativeOptions[key];
  48943. }
  48944. }
  48945. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  48946. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  48947. this.world.addEventListener("preStep", impostor.beforeStep);
  48948. this.world.addEventListener("postStep", impostor.afterStep);
  48949. impostor.physicsBody.addShape(shape);
  48950. this.world.add(impostor.physicsBody);
  48951. //try to keep the body moving in the right direction by taking old properties.
  48952. //Should be tested!
  48953. if (oldBody) {
  48954. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  48955. impostor.physicsBody[param].copy(oldBody[param]);
  48956. });
  48957. }
  48958. this._processChildMeshes(impostor);
  48959. }
  48960. //now update the body's transformation
  48961. this._updatePhysicsBodyTransformation(impostor);
  48962. };
  48963. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  48964. var _this = this;
  48965. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  48966. if (meshChildren.length) {
  48967. var processMesh = function (localPosition, mesh) {
  48968. var childImpostor = mesh.getPhysicsImpostor();
  48969. if (childImpostor) {
  48970. var parent = childImpostor.parent;
  48971. if (parent !== mainImpostor) {
  48972. var localPosition = mesh.position;
  48973. if (childImpostor.physicsBody) {
  48974. _this.removePhysicsBody(childImpostor);
  48975. childImpostor.physicsBody = null;
  48976. }
  48977. childImpostor.parent = mainImpostor;
  48978. childImpostor.resetUpdateFlags();
  48979. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  48980. //Add the mass of the children.
  48981. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  48982. }
  48983. }
  48984. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  48985. };
  48986. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  48987. }
  48988. };
  48989. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  48990. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  48991. this.world.removeEventListener("preStep", impostor.beforeStep);
  48992. this.world.removeEventListener("postStep", impostor.afterStep);
  48993. this.world.remove(impostor.physicsBody);
  48994. };
  48995. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  48996. var mainBody = impostorJoint.mainImpostor.physicsBody;
  48997. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  48998. if (!mainBody || !connectedBody) {
  48999. return;
  49000. }
  49001. var constraint;
  49002. var jointData = impostorJoint.joint.jointData;
  49003. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  49004. var constraintData = {
  49005. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  49006. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  49007. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  49008. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  49009. maxForce: jointData.nativeParams.maxForce,
  49010. collideConnected: !!jointData.collision
  49011. };
  49012. //Not needed, Cannon has a collideConnected flag
  49013. /*if (!jointData.collision) {
  49014. //add 1st body to a collision group of its own, if it is not in 1
  49015. if (mainBody.collisionFilterGroup === 1) {
  49016. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  49017. this._currentCollisionGroup <<= 1;
  49018. }
  49019. if (connectedBody.collisionFilterGroup === 1) {
  49020. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  49021. this._currentCollisionGroup <<= 1;
  49022. }
  49023. //add their mask to the collisionFilterMask of each other:
  49024. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  49025. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  49026. }*/
  49027. switch (impostorJoint.joint.type) {
  49028. case BABYLON.PhysicsJoint.HingeJoint:
  49029. case BABYLON.PhysicsJoint.Hinge2Joint:
  49030. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  49031. break;
  49032. case BABYLON.PhysicsJoint.DistanceJoint:
  49033. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  49034. break;
  49035. case BABYLON.PhysicsJoint.SpringJoint:
  49036. var springData = jointData;
  49037. constraint = new CANNON.Spring(mainBody, connectedBody, {
  49038. restLength: springData.length,
  49039. stiffness: springData.stiffness,
  49040. damping: springData.damping,
  49041. localAnchorA: constraintData.pivotA,
  49042. localAnchorB: constraintData.pivotB
  49043. });
  49044. break;
  49045. case BABYLON.PhysicsJoint.LockJoint:
  49046. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  49047. break;
  49048. case BABYLON.PhysicsJoint.PointToPointJoint:
  49049. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  49050. default:
  49051. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  49052. break;
  49053. }
  49054. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  49055. constraint.collideConnected = !!jointData.collision;
  49056. impostorJoint.joint.physicsJoint = constraint;
  49057. //don't add spring as constraint, as it is not one.
  49058. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  49059. this.world.addConstraint(constraint);
  49060. }
  49061. else {
  49062. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  49063. constraint.applyForce();
  49064. });
  49065. }
  49066. };
  49067. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  49068. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  49069. };
  49070. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  49071. var index;
  49072. var mat;
  49073. for (index = 0; index < this._physicsMaterials.length; index++) {
  49074. mat = this._physicsMaterials[index];
  49075. if (mat.friction === friction && mat.restitution === restitution) {
  49076. return mat;
  49077. }
  49078. }
  49079. var currentMat = new CANNON.Material(name);
  49080. currentMat.friction = friction;
  49081. currentMat.restitution = restitution;
  49082. this._physicsMaterials.push(currentMat);
  49083. return currentMat;
  49084. };
  49085. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  49086. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  49087. };
  49088. CannonJSPlugin.prototype._createShape = function (impostor) {
  49089. var object = impostor.object;
  49090. var returnValue;
  49091. var extendSize = impostor.getObjectExtendSize();
  49092. switch (impostor.type) {
  49093. case BABYLON.PhysicsEngine.SphereImpostor:
  49094. var radiusX = extendSize.x;
  49095. var radiusY = extendSize.y;
  49096. var radiusZ = extendSize.z;
  49097. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  49098. break;
  49099. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  49100. case BABYLON.PhysicsImpostor.CylinderImpostor:
  49101. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  49102. break;
  49103. case BABYLON.PhysicsImpostor.BoxImpostor:
  49104. var box = extendSize.scale(0.5);
  49105. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  49106. break;
  49107. case BABYLON.PhysicsImpostor.PlaneImpostor:
  49108. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  49109. returnValue = new CANNON.Plane();
  49110. break;
  49111. case BABYLON.PhysicsImpostor.MeshImpostor:
  49112. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  49113. var rawFaces = object.getIndices ? object.getIndices() : [];
  49114. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  49115. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  49116. break;
  49117. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  49118. returnValue = this._createHeightmap(object);
  49119. break;
  49120. case BABYLON.PhysicsImpostor.ParticleImpostor:
  49121. returnValue = new CANNON.Particle();
  49122. break;
  49123. }
  49124. return returnValue;
  49125. };
  49126. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  49127. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49128. var matrix = [];
  49129. //For now pointDepth will not be used and will be automatically calculated.
  49130. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  49131. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  49132. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  49133. var elementSize = dim * 2 / arraySize;
  49134. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  49135. for (var i = 0; i < pos.length; i = i + 3) {
  49136. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  49137. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  49138. var y = pos[i + 1] + minY;
  49139. if (!matrix[x]) {
  49140. matrix[x] = [];
  49141. }
  49142. if (!matrix[x][z]) {
  49143. matrix[x][z] = y;
  49144. }
  49145. matrix[x][z] = Math.max(y, matrix[x][z]);
  49146. }
  49147. for (var x = 0; x <= arraySize; ++x) {
  49148. if (!matrix[x]) {
  49149. var loc = 1;
  49150. while (!matrix[(x + loc) % arraySize]) {
  49151. loc++;
  49152. }
  49153. matrix[x] = matrix[(x + loc) % arraySize].slice();
  49154. }
  49155. for (var z = 0; z <= arraySize; ++z) {
  49156. if (!matrix[x][z]) {
  49157. var loc = 1;
  49158. var newValue;
  49159. while (newValue === undefined) {
  49160. newValue = matrix[x][(z + loc++) % arraySize];
  49161. }
  49162. matrix[x][z] = newValue;
  49163. }
  49164. }
  49165. }
  49166. var shape = new CANNON.Heightfield(matrix, {
  49167. elementSize: elementSize
  49168. });
  49169. //For future reference, needed for body transformation
  49170. shape.minY = minY;
  49171. return shape;
  49172. };
  49173. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  49174. var object = impostor.object;
  49175. //make sure it is updated...
  49176. object.computeWorldMatrix && object.computeWorldMatrix(true);
  49177. // The delta between the mesh position and the mesh bounding box center
  49178. var center = impostor.getObjectCenter();
  49179. var extendSize = impostor.getObjectExtendSize();
  49180. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  49181. this._tmpPosition.copyFrom(center);
  49182. var quaternion = object.rotationQuaternion;
  49183. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  49184. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  49185. //-90 DEG in X, precalculated
  49186. quaternion = quaternion.multiply(this._minus90X);
  49187. //Invert! (Precalculated, 90 deg in X)
  49188. //No need to clone. this will never change.
  49189. impostor.setDeltaRotation(this._plus90X);
  49190. }
  49191. //If it is a heightfield, if should be centered.
  49192. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  49193. var mesh = object;
  49194. //calculate the correct body position:
  49195. var rotationQuaternion = mesh.rotationQuaternion;
  49196. mesh.rotationQuaternion = this._tmpUnityRotation;
  49197. mesh.computeWorldMatrix(true);
  49198. //get original center with no rotation
  49199. var c = center.clone();
  49200. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  49201. //rotation is back
  49202. mesh.rotationQuaternion = rotationQuaternion;
  49203. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  49204. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  49205. mesh.setPivotMatrix(p);
  49206. mesh.computeWorldMatrix(true);
  49207. //calculate the translation
  49208. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  49209. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  49210. //add it inverted to the delta
  49211. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  49212. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  49213. mesh.setPivotMatrix(oldPivot);
  49214. mesh.computeWorldMatrix(true);
  49215. }
  49216. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  49217. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  49218. this._tmpPosition.copyFrom(object.position);
  49219. }
  49220. impostor.setDeltaPosition(this._tmpDeltaPosition);
  49221. //Now update the impostor object
  49222. impostor.physicsBody.position.copy(this._tmpPosition);
  49223. impostor.physicsBody.quaternion.copy(quaternion);
  49224. };
  49225. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  49226. impostor.object.position.copyFrom(impostor.physicsBody.position);
  49227. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  49228. };
  49229. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  49230. impostor.physicsBody.position.copy(newPosition);
  49231. impostor.physicsBody.quaternion.copy(newRotation);
  49232. };
  49233. CannonJSPlugin.prototype.isSupported = function () {
  49234. return window.CANNON !== undefined;
  49235. };
  49236. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  49237. impostor.physicsBody.velocity.copy(velocity);
  49238. };
  49239. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  49240. impostor.physicsBody.angularVelocity.copy(velocity);
  49241. };
  49242. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  49243. var v = impostor.physicsBody.velocity;
  49244. if (!v)
  49245. return null;
  49246. return new BABYLON.Vector3(v.x, v.y, v.z);
  49247. };
  49248. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  49249. var v = impostor.physicsBody.angularVelocity;
  49250. if (!v)
  49251. return null;
  49252. return new BABYLON.Vector3(v.x, v.y, v.z);
  49253. };
  49254. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  49255. impostor.physicsBody.mass = mass;
  49256. impostor.physicsBody.updateMassProperties();
  49257. };
  49258. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  49259. impostor.physicsBody.sleep();
  49260. };
  49261. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  49262. impostor.physicsBody.wakeUp();
  49263. };
  49264. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  49265. joint.physicsJoint.distance = maxDistance;
  49266. };
  49267. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  49268. if (!motorIndex) {
  49269. joint.physicsJoint.enableMotor();
  49270. }
  49271. };
  49272. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  49273. if (!motorIndex) {
  49274. joint.physicsJoint.disableMotor();
  49275. }
  49276. };
  49277. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  49278. if (!motorIndex) {
  49279. joint.physicsJoint.enableMotor();
  49280. joint.physicsJoint.setMotorSpeed(speed);
  49281. if (maxForce) {
  49282. this.setLimit(joint, maxForce);
  49283. }
  49284. }
  49285. };
  49286. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  49287. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  49288. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  49289. };
  49290. CannonJSPlugin.prototype.dispose = function () {
  49291. //nothing to do, actually.
  49292. };
  49293. return CannonJSPlugin;
  49294. })();
  49295. BABYLON.CannonJSPlugin = CannonJSPlugin;
  49296. })(BABYLON || (BABYLON = {}));
  49297. var BABYLON;
  49298. (function (BABYLON) {
  49299. var OimoJSPlugin = (function () {
  49300. function OimoJSPlugin(iterations) {
  49301. this.name = "OimoJSPlugin";
  49302. this._tmpImpostorsArray = [];
  49303. this._tmpPositionVector = BABYLON.Vector3.Zero();
  49304. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  49305. this.world.clear();
  49306. //making sure no stats are calculated
  49307. this.world.isNoStat = true;
  49308. }
  49309. OimoJSPlugin.prototype.setGravity = function (gravity) {
  49310. this.world.gravity.copy(gravity);
  49311. };
  49312. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  49313. this.world.timeStep = timeStep;
  49314. };
  49315. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  49316. var _this = this;
  49317. impostors.forEach(function (impostor) {
  49318. impostor.beforeStep();
  49319. });
  49320. this.world.step();
  49321. impostors.forEach(function (impostor) {
  49322. impostor.afterStep();
  49323. //update the ordered impostors array
  49324. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  49325. });
  49326. //check for collisions
  49327. var contact = this.world.contacts;
  49328. while (contact !== null) {
  49329. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  49330. contact = contact.next;
  49331. continue;
  49332. }
  49333. //is this body colliding with any other? get the impostor
  49334. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  49335. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  49336. if (!mainImpostor || !collidingImpostor) {
  49337. contact = contact.next;
  49338. continue;
  49339. }
  49340. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  49341. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  49342. contact = contact.next;
  49343. }
  49344. };
  49345. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  49346. var mass = impostor.physicsBody.massInfo.mass;
  49347. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  49348. };
  49349. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  49350. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  49351. this.applyImpulse(impostor, force, contactPoint);
  49352. };
  49353. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  49354. var _this = this;
  49355. //parent-child relationship. Does this impostor has a parent impostor?
  49356. if (impostor.parent) {
  49357. if (impostor.physicsBody) {
  49358. this.removePhysicsBody(impostor);
  49359. //TODO is that needed?
  49360. impostor.forceUpdate();
  49361. }
  49362. return;
  49363. }
  49364. if (impostor.isBodyInitRequired()) {
  49365. var bodyConfig = {
  49366. name: impostor.uniqueId,
  49367. //Oimo must have mass, also for static objects.
  49368. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  49369. size: [],
  49370. type: [],
  49371. pos: [],
  49372. rot: [],
  49373. move: impostor.getParam("mass") !== 0,
  49374. //Supporting older versions of Oimo
  49375. world: this.world
  49376. };
  49377. var impostors = [impostor];
  49378. function addToArray(parent) {
  49379. if (!parent.getChildMeshes)
  49380. return;
  49381. parent.getChildMeshes().forEach(function (m) {
  49382. if (m.physicsImpostor) {
  49383. impostors.push(m.physicsImpostor);
  49384. m.physicsImpostor._init();
  49385. }
  49386. });
  49387. }
  49388. addToArray(impostor.object);
  49389. function checkWithEpsilon(value) {
  49390. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  49391. }
  49392. impostors.forEach(function (i) {
  49393. //get the correct bounding box
  49394. var oldQuaternion = i.object.rotationQuaternion;
  49395. var rot = new OIMO.Euler().setFromQuaternion({
  49396. x: impostor.object.rotationQuaternion.x,
  49397. y: impostor.object.rotationQuaternion.y,
  49398. z: impostor.object.rotationQuaternion.z,
  49399. s: impostor.object.rotationQuaternion.w
  49400. });
  49401. var extendSize = i.getObjectExtendSize();
  49402. if (i === impostor) {
  49403. var center = impostor.getObjectCenter();
  49404. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  49405. //Can also use Array.prototype.push.apply
  49406. bodyConfig.pos.push(center.x);
  49407. bodyConfig.pos.push(center.y);
  49408. bodyConfig.pos.push(center.z);
  49409. //tmp solution
  49410. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  49411. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  49412. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  49413. }
  49414. else {
  49415. bodyConfig.pos.push(i.object.position.x);
  49416. bodyConfig.pos.push(i.object.position.y);
  49417. bodyConfig.pos.push(i.object.position.z);
  49418. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  49419. bodyConfig.rot.push(0);
  49420. bodyConfig.rot.push(0);
  49421. bodyConfig.rot.push(0);
  49422. }
  49423. // register mesh
  49424. switch (i.type) {
  49425. case BABYLON.PhysicsImpostor.ParticleImpostor:
  49426. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  49427. case BABYLON.PhysicsImpostor.SphereImpostor:
  49428. var radiusX = extendSize.x;
  49429. var radiusY = extendSize.y;
  49430. var radiusZ = extendSize.z;
  49431. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  49432. bodyConfig.type.push('sphere');
  49433. //due to the way oimo works with compounds, add 3 times
  49434. bodyConfig.size.push(size);
  49435. bodyConfig.size.push(size);
  49436. bodyConfig.size.push(size);
  49437. break;
  49438. case BABYLON.PhysicsImpostor.CylinderImpostor:
  49439. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  49440. var sizeY = checkWithEpsilon(extendSize.y);
  49441. bodyConfig.type.push('cylinder');
  49442. bodyConfig.size.push(sizeX);
  49443. bodyConfig.size.push(sizeY);
  49444. //due to the way oimo works with compounds, add one more value.
  49445. bodyConfig.size.push(sizeY);
  49446. break;
  49447. case BABYLON.PhysicsImpostor.PlaneImpostor:
  49448. case BABYLON.PhysicsImpostor.BoxImpostor:
  49449. default:
  49450. var sizeX = checkWithEpsilon(extendSize.x);
  49451. var sizeY = checkWithEpsilon(extendSize.y);
  49452. var sizeZ = checkWithEpsilon(extendSize.z);
  49453. bodyConfig.type.push('box');
  49454. bodyConfig.size.push(sizeX);
  49455. bodyConfig.size.push(sizeY);
  49456. bodyConfig.size.push(sizeZ);
  49457. break;
  49458. }
  49459. //actually not needed, but hey...
  49460. i.object.rotationQuaternion = oldQuaternion;
  49461. });
  49462. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  49463. }
  49464. else {
  49465. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  49466. }
  49467. impostor.setDeltaPosition(this._tmpPositionVector);
  49468. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  49469. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  49470. };
  49471. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  49472. //impostor.physicsBody.dispose();
  49473. //Same as : (older oimo versions)
  49474. this.world.removeRigidBody(impostor.physicsBody);
  49475. };
  49476. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  49477. var mainBody = impostorJoint.mainImpostor.physicsBody;
  49478. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  49479. if (!mainBody || !connectedBody) {
  49480. return;
  49481. }
  49482. var jointData = impostorJoint.joint.jointData;
  49483. var options = jointData.nativeParams || {};
  49484. var type;
  49485. var nativeJointData = {
  49486. body1: mainBody,
  49487. body2: connectedBody,
  49488. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  49489. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  49490. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  49491. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  49492. min: options.min,
  49493. max: options.max,
  49494. collision: options.collision || jointData.collision,
  49495. spring: options.spring,
  49496. //supporting older version of Oimo
  49497. world: this.world
  49498. };
  49499. switch (impostorJoint.joint.type) {
  49500. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  49501. type = "jointBall";
  49502. break;
  49503. case BABYLON.PhysicsJoint.SpringJoint:
  49504. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  49505. var springData = jointData;
  49506. nativeJointData.min = springData.length || nativeJointData.min;
  49507. //Max should also be set, just make sure it is at least min
  49508. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  49509. case BABYLON.PhysicsJoint.DistanceJoint:
  49510. type = "jointDistance";
  49511. nativeJointData.max = jointData.maxDistance;
  49512. break;
  49513. case BABYLON.PhysicsJoint.PrismaticJoint:
  49514. type = "jointPrisme";
  49515. break;
  49516. case BABYLON.PhysicsJoint.SliderJoint:
  49517. type = "jointSlide";
  49518. break;
  49519. case BABYLON.PhysicsJoint.WheelJoint:
  49520. type = "jointWheel";
  49521. break;
  49522. case BABYLON.PhysicsJoint.HingeJoint:
  49523. default:
  49524. type = "jointHinge";
  49525. break;
  49526. }
  49527. nativeJointData.type = type;
  49528. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  49529. };
  49530. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  49531. //Bug in Oimo prevents us from disposing a joint in the playground
  49532. //joint.joint.physicsJoint.dispose();
  49533. //So we will bruteforce it!
  49534. try {
  49535. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  49536. }
  49537. catch (e) {
  49538. BABYLON.Tools.Warn(e);
  49539. }
  49540. };
  49541. OimoJSPlugin.prototype.isSupported = function () {
  49542. return OIMO !== undefined;
  49543. };
  49544. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  49545. if (!impostor.physicsBody.sleeping) {
  49546. //TODO check that
  49547. if (impostor.physicsBody.shapes.next) {
  49548. var parentShape = this._getLastShape(impostor.physicsBody);
  49549. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  49550. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  49551. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  49552. }
  49553. else {
  49554. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  49555. }
  49556. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  49557. impostor.object.rotationQuaternion.normalize();
  49558. }
  49559. };
  49560. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  49561. var body = impostor.physicsBody;
  49562. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  49563. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  49564. body.syncShapes();
  49565. body.awake();
  49566. };
  49567. OimoJSPlugin.prototype._getLastShape = function (body) {
  49568. var lastShape = body.shapes;
  49569. while (lastShape.next) {
  49570. lastShape = lastShape.next;
  49571. }
  49572. return lastShape;
  49573. };
  49574. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  49575. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  49576. };
  49577. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  49578. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  49579. };
  49580. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  49581. var v = impostor.physicsBody.linearVelocity;
  49582. if (!v)
  49583. return null;
  49584. return new BABYLON.Vector3(v.x, v.y, v.z);
  49585. };
  49586. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  49587. var v = impostor.physicsBody.angularVelocity;
  49588. if (!v)
  49589. return null;
  49590. return new BABYLON.Vector3(v.x, v.y, v.z);
  49591. };
  49592. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  49593. var staticBody = mass === 0;
  49594. //this will actually set the body's density and not its mass.
  49595. //But this is how oimo treats the mass variable.
  49596. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  49597. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  49598. };
  49599. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  49600. impostor.physicsBody.sleep();
  49601. };
  49602. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  49603. impostor.physicsBody.awake();
  49604. };
  49605. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  49606. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  49607. if (minDistance !== void 0) {
  49608. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  49609. }
  49610. };
  49611. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  49612. //TODO separate rotational and transational motors.
  49613. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  49614. if (motor) {
  49615. motor.setMotor(speed, maxForce);
  49616. }
  49617. };
  49618. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  49619. //TODO separate rotational and transational motors.
  49620. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  49621. if (motor) {
  49622. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  49623. }
  49624. };
  49625. OimoJSPlugin.prototype.dispose = function () {
  49626. this.world.clear();
  49627. };
  49628. return OimoJSPlugin;
  49629. })();
  49630. BABYLON.OimoJSPlugin = OimoJSPlugin;
  49631. })(BABYLON || (BABYLON = {}));
  49632. var BABYLON;
  49633. (function (BABYLON) {
  49634. var DisplayPassPostProcess = (function (_super) {
  49635. __extends(DisplayPassPostProcess, _super);
  49636. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  49637. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  49638. }
  49639. return DisplayPassPostProcess;
  49640. })(BABYLON.PostProcess);
  49641. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  49642. })(BABYLON || (BABYLON = {}));
  49643. var BABYLON;
  49644. (function (BABYLON) {
  49645. var SimplificationSettings = (function () {
  49646. function SimplificationSettings(quality, distance, optimizeMesh) {
  49647. this.quality = quality;
  49648. this.distance = distance;
  49649. this.optimizeMesh = optimizeMesh;
  49650. }
  49651. return SimplificationSettings;
  49652. })();
  49653. BABYLON.SimplificationSettings = SimplificationSettings;
  49654. var SimplificationQueue = (function () {
  49655. function SimplificationQueue() {
  49656. this.running = false;
  49657. this._simplificationArray = [];
  49658. }
  49659. SimplificationQueue.prototype.addTask = function (task) {
  49660. this._simplificationArray.push(task);
  49661. };
  49662. SimplificationQueue.prototype.executeNext = function () {
  49663. var task = this._simplificationArray.pop();
  49664. if (task) {
  49665. this.running = true;
  49666. this.runSimplification(task);
  49667. }
  49668. else {
  49669. this.running = false;
  49670. }
  49671. };
  49672. SimplificationQueue.prototype.runSimplification = function (task) {
  49673. var _this = this;
  49674. if (task.parallelProcessing) {
  49675. //parallel simplifier
  49676. task.settings.forEach(function (setting) {
  49677. var simplifier = _this.getSimplifier(task);
  49678. simplifier.simplify(setting, function (newMesh) {
  49679. task.mesh.addLODLevel(setting.distance, newMesh);
  49680. newMesh.isVisible = true;
  49681. //check if it is the last
  49682. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  49683. //all done, run the success callback.
  49684. task.successCallback();
  49685. }
  49686. _this.executeNext();
  49687. });
  49688. });
  49689. }
  49690. else {
  49691. //single simplifier.
  49692. var simplifier = this.getSimplifier(task);
  49693. var runDecimation = function (setting, callback) {
  49694. simplifier.simplify(setting, function (newMesh) {
  49695. task.mesh.addLODLevel(setting.distance, newMesh);
  49696. newMesh.isVisible = true;
  49697. //run the next quality level
  49698. callback();
  49699. });
  49700. };
  49701. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  49702. runDecimation(task.settings[loop.index], function () {
  49703. loop.executeNext();
  49704. });
  49705. }, function () {
  49706. //execution ended, run the success callback.
  49707. if (task.successCallback) {
  49708. task.successCallback();
  49709. }
  49710. _this.executeNext();
  49711. });
  49712. }
  49713. };
  49714. SimplificationQueue.prototype.getSimplifier = function (task) {
  49715. switch (task.simplificationType) {
  49716. case SimplificationType.QUADRATIC:
  49717. default:
  49718. return new QuadraticErrorSimplification(task.mesh);
  49719. }
  49720. };
  49721. return SimplificationQueue;
  49722. })();
  49723. BABYLON.SimplificationQueue = SimplificationQueue;
  49724. /**
  49725. * The implemented types of simplification.
  49726. * At the moment only Quadratic Error Decimation is implemented.
  49727. */
  49728. (function (SimplificationType) {
  49729. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  49730. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  49731. var SimplificationType = BABYLON.SimplificationType;
  49732. var DecimationTriangle = (function () {
  49733. function DecimationTriangle(vertices) {
  49734. this.vertices = vertices;
  49735. this.error = new Array(4);
  49736. this.deleted = false;
  49737. this.isDirty = false;
  49738. this.deletePending = false;
  49739. this.borderFactor = 0;
  49740. }
  49741. return DecimationTriangle;
  49742. })();
  49743. BABYLON.DecimationTriangle = DecimationTriangle;
  49744. var DecimationVertex = (function () {
  49745. function DecimationVertex(position, id) {
  49746. this.position = position;
  49747. this.id = id;
  49748. this.isBorder = true;
  49749. this.q = new QuadraticMatrix();
  49750. this.triangleCount = 0;
  49751. this.triangleStart = 0;
  49752. this.originalOffsets = [];
  49753. }
  49754. DecimationVertex.prototype.updatePosition = function (newPosition) {
  49755. this.position.copyFrom(newPosition);
  49756. };
  49757. return DecimationVertex;
  49758. })();
  49759. BABYLON.DecimationVertex = DecimationVertex;
  49760. var QuadraticMatrix = (function () {
  49761. function QuadraticMatrix(data) {
  49762. this.data = new Array(10);
  49763. for (var i = 0; i < 10; ++i) {
  49764. if (data && data[i]) {
  49765. this.data[i] = data[i];
  49766. }
  49767. else {
  49768. this.data[i] = 0;
  49769. }
  49770. }
  49771. }
  49772. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  49773. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  49774. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  49775. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  49776. return det;
  49777. };
  49778. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  49779. for (var i = 0; i < 10; ++i) {
  49780. this.data[i] += matrix.data[i];
  49781. }
  49782. };
  49783. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  49784. for (var i = 0; i < 10; ++i) {
  49785. this.data[i] += data[i];
  49786. }
  49787. };
  49788. QuadraticMatrix.prototype.add = function (matrix) {
  49789. var m = new QuadraticMatrix();
  49790. for (var i = 0; i < 10; ++i) {
  49791. m.data[i] = this.data[i] + matrix.data[i];
  49792. }
  49793. return m;
  49794. };
  49795. QuadraticMatrix.FromData = function (a, b, c, d) {
  49796. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  49797. };
  49798. //returning an array to avoid garbage collection
  49799. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  49800. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  49801. };
  49802. return QuadraticMatrix;
  49803. })();
  49804. BABYLON.QuadraticMatrix = QuadraticMatrix;
  49805. var Reference = (function () {
  49806. function Reference(vertexId, triangleId) {
  49807. this.vertexId = vertexId;
  49808. this.triangleId = triangleId;
  49809. }
  49810. return Reference;
  49811. })();
  49812. BABYLON.Reference = Reference;
  49813. /**
  49814. * An implementation of the Quadratic Error simplification algorithm.
  49815. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  49816. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  49817. * @author RaananW
  49818. */
  49819. var QuadraticErrorSimplification = (function () {
  49820. function QuadraticErrorSimplification(_mesh) {
  49821. this._mesh = _mesh;
  49822. this.initialized = false;
  49823. this.syncIterations = 5000;
  49824. this.aggressiveness = 7;
  49825. this.decimationIterations = 100;
  49826. this.boundingBoxEpsilon = BABYLON.Epsilon;
  49827. }
  49828. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  49829. var _this = this;
  49830. this.initDecimatedMesh();
  49831. //iterating through the submeshes array, one after the other.
  49832. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  49833. _this.initWithMesh(loop.index, function () {
  49834. _this.runDecimation(settings, loop.index, function () {
  49835. loop.executeNext();
  49836. });
  49837. }, settings.optimizeMesh);
  49838. }, function () {
  49839. setTimeout(function () {
  49840. successCallback(_this._reconstructedMesh);
  49841. }, 0);
  49842. });
  49843. };
  49844. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  49845. var _this = this;
  49846. var gCount = 0;
  49847. triangle.vertices.forEach(function (vertex) {
  49848. var count = 0;
  49849. var vPos = vertex.position;
  49850. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  49851. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  49852. ++count;
  49853. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  49854. ++count;
  49855. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  49856. ++count;
  49857. if (count > 1) {
  49858. ++gCount;
  49859. }
  49860. ;
  49861. });
  49862. if (gCount > 1) {
  49863. console.log(triangle, gCount);
  49864. }
  49865. return gCount > 1;
  49866. };
  49867. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  49868. var _this = this;
  49869. var targetCount = ~~(this.triangles.length * settings.quality);
  49870. var deletedTriangles = 0;
  49871. var triangleCount = this.triangles.length;
  49872. var iterationFunction = function (iteration, callback) {
  49873. setTimeout(function () {
  49874. if (iteration % 5 === 0) {
  49875. _this.updateMesh(iteration === 0);
  49876. }
  49877. for (var i = 0; i < _this.triangles.length; ++i) {
  49878. _this.triangles[i].isDirty = false;
  49879. }
  49880. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  49881. var trianglesIterator = function (i) {
  49882. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  49883. var t = _this.triangles[tIdx];
  49884. if (!t)
  49885. return;
  49886. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  49887. return;
  49888. }
  49889. for (var j = 0; j < 3; ++j) {
  49890. if (t.error[j] < threshold) {
  49891. var deleted0 = [];
  49892. var deleted1 = [];
  49893. var v0 = t.vertices[j];
  49894. var v1 = t.vertices[(j + 1) % 3];
  49895. if (v0.isBorder || v1.isBorder)
  49896. continue;
  49897. var p = BABYLON.Vector3.Zero();
  49898. var n = BABYLON.Vector3.Zero();
  49899. var uv = BABYLON.Vector2.Zero();
  49900. var color = new BABYLON.Color4(0, 0, 0, 1);
  49901. _this.calculateError(v0, v1, p, n, uv, color);
  49902. var delTr = [];
  49903. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  49904. continue;
  49905. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  49906. continue;
  49907. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  49908. continue;
  49909. var uniqueArray = [];
  49910. delTr.forEach(function (deletedT) {
  49911. if (uniqueArray.indexOf(deletedT) === -1) {
  49912. deletedT.deletePending = true;
  49913. uniqueArray.push(deletedT);
  49914. }
  49915. });
  49916. if (uniqueArray.length % 2 !== 0) {
  49917. continue;
  49918. }
  49919. v0.q = v1.q.add(v0.q);
  49920. v0.updatePosition(p);
  49921. var tStart = _this.references.length;
  49922. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  49923. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  49924. var tCount = _this.references.length - tStart;
  49925. if (tCount <= v0.triangleCount) {
  49926. if (tCount) {
  49927. for (var c = 0; c < tCount; c++) {
  49928. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  49929. }
  49930. }
  49931. }
  49932. else {
  49933. v0.triangleStart = tStart;
  49934. }
  49935. v0.triangleCount = tCount;
  49936. break;
  49937. }
  49938. }
  49939. };
  49940. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  49941. }, 0);
  49942. };
  49943. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  49944. if (triangleCount - deletedTriangles <= targetCount)
  49945. loop.breakLoop();
  49946. else {
  49947. iterationFunction(loop.index, function () {
  49948. loop.executeNext();
  49949. });
  49950. }
  49951. }, function () {
  49952. setTimeout(function () {
  49953. //reconstruct this part of the mesh
  49954. _this.reconstructMesh(submeshIndex);
  49955. successCallback();
  49956. }, 0);
  49957. });
  49958. };
  49959. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  49960. var _this = this;
  49961. this.vertices = [];
  49962. this.triangles = [];
  49963. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49964. var indices = this._mesh.getIndices();
  49965. var submesh = this._mesh.subMeshes[submeshIndex];
  49966. var findInVertices = function (positionToSearch) {
  49967. if (optimizeMesh) {
  49968. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  49969. if (_this.vertices[ii].position.equals(positionToSearch)) {
  49970. return _this.vertices[ii];
  49971. }
  49972. }
  49973. }
  49974. return null;
  49975. };
  49976. var vertexReferences = [];
  49977. var vertexInit = function (i) {
  49978. var offset = i + submesh.verticesStart;
  49979. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  49980. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  49981. vertex.originalOffsets.push(offset);
  49982. if (vertex.id === _this.vertices.length) {
  49983. _this.vertices.push(vertex);
  49984. }
  49985. vertexReferences.push(vertex.id);
  49986. };
  49987. //var totalVertices = mesh.getTotalVertices();
  49988. var totalVertices = submesh.verticesCount;
  49989. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  49990. var indicesInit = function (i) {
  49991. var offset = (submesh.indexStart / 3) + i;
  49992. var pos = (offset * 3);
  49993. var i0 = indices[pos + 0];
  49994. var i1 = indices[pos + 1];
  49995. var i2 = indices[pos + 2];
  49996. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  49997. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  49998. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  49999. var triangle = new DecimationTriangle([v0, v1, v2]);
  50000. triangle.originalOffset = pos;
  50001. _this.triangles.push(triangle);
  50002. };
  50003. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  50004. _this.init(callback);
  50005. });
  50006. });
  50007. };
  50008. QuadraticErrorSimplification.prototype.init = function (callback) {
  50009. var _this = this;
  50010. var triangleInit1 = function (i) {
  50011. var t = _this.triangles[i];
  50012. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  50013. for (var j = 0; j < 3; j++) {
  50014. 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))));
  50015. }
  50016. };
  50017. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  50018. var triangleInit2 = function (i) {
  50019. var t = _this.triangles[i];
  50020. for (var j = 0; j < 3; ++j) {
  50021. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  50022. }
  50023. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  50024. };
  50025. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  50026. _this.initialized = true;
  50027. callback();
  50028. });
  50029. });
  50030. };
  50031. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  50032. var newTriangles = [];
  50033. var i;
  50034. for (i = 0; i < this.vertices.length; ++i) {
  50035. this.vertices[i].triangleCount = 0;
  50036. }
  50037. var t;
  50038. var j;
  50039. for (i = 0; i < this.triangles.length; ++i) {
  50040. if (!this.triangles[i].deleted) {
  50041. t = this.triangles[i];
  50042. for (j = 0; j < 3; ++j) {
  50043. t.vertices[j].triangleCount = 1;
  50044. }
  50045. newTriangles.push(t);
  50046. }
  50047. }
  50048. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  50049. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  50050. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  50051. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  50052. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50053. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50054. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  50055. var vertexCount = 0;
  50056. for (i = 0; i < this.vertices.length; ++i) {
  50057. var vertex = this.vertices[i];
  50058. vertex.id = vertexCount;
  50059. if (vertex.triangleCount) {
  50060. vertex.originalOffsets.forEach(function (originalOffset) {
  50061. newPositionData.push(vertex.position.x);
  50062. newPositionData.push(vertex.position.y);
  50063. newPositionData.push(vertex.position.z);
  50064. newNormalData.push(normalData[originalOffset * 3]);
  50065. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  50066. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  50067. if (uvs && uvs.length) {
  50068. newUVsData.push(uvs[(originalOffset * 2)]);
  50069. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  50070. }
  50071. else if (colorsData && colorsData.length) {
  50072. newColorsData.push(colorsData[(originalOffset * 4)]);
  50073. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  50074. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  50075. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  50076. }
  50077. ++vertexCount;
  50078. });
  50079. }
  50080. }
  50081. var startingIndex = this._reconstructedMesh.getTotalIndices();
  50082. var startingVertex = this._reconstructedMesh.getTotalVertices();
  50083. var submeshesArray = this._reconstructedMesh.subMeshes;
  50084. this._reconstructedMesh.subMeshes = [];
  50085. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  50086. var originalIndices = this._mesh.getIndices();
  50087. for (i = 0; i < newTriangles.length; ++i) {
  50088. t = newTriangles[i]; //now get the new referencing point for each vertex
  50089. [0, 1, 2].forEach(function (idx) {
  50090. var id = originalIndices[t.originalOffset + idx];
  50091. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  50092. if (offset < 0)
  50093. offset = 0;
  50094. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  50095. });
  50096. }
  50097. //overwriting the old vertex buffers and indices.
  50098. this._reconstructedMesh.setIndices(newIndicesArray);
  50099. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  50100. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  50101. if (newUVsData.length > 0)
  50102. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  50103. if (newColorsData.length > 0)
  50104. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  50105. //create submesh
  50106. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  50107. if (submeshIndex > 0) {
  50108. this._reconstructedMesh.subMeshes = [];
  50109. submeshesArray.forEach(function (submesh) {
  50110. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  50111. });
  50112. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  50113. }
  50114. };
  50115. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  50116. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  50117. this._reconstructedMesh.material = this._mesh.material;
  50118. this._reconstructedMesh.parent = this._mesh.parent;
  50119. this._reconstructedMesh.isVisible = false;
  50120. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  50121. };
  50122. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  50123. for (var i = 0; i < vertex1.triangleCount; ++i) {
  50124. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  50125. if (t.deleted)
  50126. continue;
  50127. var s = this.references[vertex1.triangleStart + i].vertexId;
  50128. var v1 = t.vertices[(s + 1) % 3];
  50129. var v2 = t.vertices[(s + 2) % 3];
  50130. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  50131. deletedArray[i] = true;
  50132. delTr.push(t);
  50133. continue;
  50134. }
  50135. var d1 = v1.position.subtract(point);
  50136. d1 = d1.normalize();
  50137. var d2 = v2.position.subtract(point);
  50138. d2 = d2.normalize();
  50139. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  50140. return true;
  50141. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  50142. deletedArray[i] = false;
  50143. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  50144. return true;
  50145. }
  50146. return false;
  50147. };
  50148. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  50149. var newDeleted = deletedTriangles;
  50150. for (var i = 0; i < vertex.triangleCount; ++i) {
  50151. var ref = this.references[vertex.triangleStart + i];
  50152. var t = this.triangles[ref.triangleId];
  50153. if (t.deleted)
  50154. continue;
  50155. if (deletedArray[i] && t.deletePending) {
  50156. t.deleted = true;
  50157. newDeleted++;
  50158. continue;
  50159. }
  50160. t.vertices[ref.vertexId] = origVertex;
  50161. t.isDirty = true;
  50162. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  50163. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  50164. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  50165. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  50166. this.references.push(ref);
  50167. }
  50168. return newDeleted;
  50169. };
  50170. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  50171. for (var i = 0; i < this.vertices.length; ++i) {
  50172. var vCount = [];
  50173. var vId = [];
  50174. var v = this.vertices[i];
  50175. var j;
  50176. for (j = 0; j < v.triangleCount; ++j) {
  50177. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  50178. for (var ii = 0; ii < 3; ii++) {
  50179. var ofs = 0;
  50180. var vv = triangle.vertices[ii];
  50181. while (ofs < vCount.length) {
  50182. if (vId[ofs] === vv.id)
  50183. break;
  50184. ++ofs;
  50185. }
  50186. if (ofs === vCount.length) {
  50187. vCount.push(1);
  50188. vId.push(vv.id);
  50189. }
  50190. else {
  50191. vCount[ofs]++;
  50192. }
  50193. }
  50194. }
  50195. for (j = 0; j < vCount.length; ++j) {
  50196. if (vCount[j] === 1) {
  50197. this.vertices[vId[j]].isBorder = true;
  50198. }
  50199. else {
  50200. this.vertices[vId[j]].isBorder = false;
  50201. }
  50202. }
  50203. }
  50204. };
  50205. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  50206. if (identifyBorders === void 0) { identifyBorders = false; }
  50207. var i;
  50208. if (!identifyBorders) {
  50209. var newTrianglesVector = [];
  50210. for (i = 0; i < this.triangles.length; ++i) {
  50211. if (!this.triangles[i].deleted) {
  50212. newTrianglesVector.push(this.triangles[i]);
  50213. }
  50214. }
  50215. this.triangles = newTrianglesVector;
  50216. }
  50217. for (i = 0; i < this.vertices.length; ++i) {
  50218. this.vertices[i].triangleCount = 0;
  50219. this.vertices[i].triangleStart = 0;
  50220. }
  50221. var t;
  50222. var j;
  50223. var v;
  50224. for (i = 0; i < this.triangles.length; ++i) {
  50225. t = this.triangles[i];
  50226. for (j = 0; j < 3; ++j) {
  50227. v = t.vertices[j];
  50228. v.triangleCount++;
  50229. }
  50230. }
  50231. var tStart = 0;
  50232. for (i = 0; i < this.vertices.length; ++i) {
  50233. this.vertices[i].triangleStart = tStart;
  50234. tStart += this.vertices[i].triangleCount;
  50235. this.vertices[i].triangleCount = 0;
  50236. }
  50237. var newReferences = new Array(this.triangles.length * 3);
  50238. for (i = 0; i < this.triangles.length; ++i) {
  50239. t = this.triangles[i];
  50240. for (j = 0; j < 3; ++j) {
  50241. v = t.vertices[j];
  50242. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  50243. v.triangleCount++;
  50244. }
  50245. }
  50246. this.references = newReferences;
  50247. if (identifyBorders) {
  50248. this.identifyBorder();
  50249. }
  50250. };
  50251. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  50252. var x = point.x;
  50253. var y = point.y;
  50254. var z = point.z;
  50255. 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
  50256. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  50257. };
  50258. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  50259. var q = vertex1.q.add(vertex2.q);
  50260. var border = vertex1.isBorder && vertex2.isBorder;
  50261. var error = 0;
  50262. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  50263. if (qDet !== 0 && !border) {
  50264. if (!pointResult) {
  50265. pointResult = BABYLON.Vector3.Zero();
  50266. }
  50267. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  50268. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  50269. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  50270. error = this.vertexError(q, pointResult);
  50271. }
  50272. else {
  50273. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  50274. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  50275. var error1 = this.vertexError(q, vertex1.position);
  50276. var error2 = this.vertexError(q, vertex2.position);
  50277. var error3 = this.vertexError(q, p3);
  50278. error = Math.min(error1, error2, error3);
  50279. if (error === error1) {
  50280. if (pointResult) {
  50281. pointResult.copyFrom(vertex1.position);
  50282. }
  50283. }
  50284. else if (error === error2) {
  50285. if (pointResult) {
  50286. pointResult.copyFrom(vertex2.position);
  50287. }
  50288. }
  50289. else {
  50290. if (pointResult) {
  50291. pointResult.copyFrom(p3);
  50292. }
  50293. }
  50294. }
  50295. return error;
  50296. };
  50297. return QuadraticErrorSimplification;
  50298. })();
  50299. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  50300. })(BABYLON || (BABYLON = {}));
  50301. var BABYLON;
  50302. (function (BABYLON) {
  50303. var serializedGeometries = [];
  50304. var serializeGeometry = function (geometry, serializationGeometries) {
  50305. if (serializedGeometries[geometry.id]) {
  50306. return;
  50307. }
  50308. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  50309. serializationGeometries.boxes.push(geometry.serialize());
  50310. }
  50311. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  50312. serializationGeometries.spheres.push(geometry.serialize());
  50313. }
  50314. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  50315. serializationGeometries.cylinders.push(geometry.serialize());
  50316. }
  50317. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  50318. serializationGeometries.toruses.push(geometry.serialize());
  50319. }
  50320. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  50321. serializationGeometries.grounds.push(geometry.serialize());
  50322. }
  50323. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  50324. serializationGeometries.planes.push(geometry.serialize());
  50325. }
  50326. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  50327. serializationGeometries.torusKnots.push(geometry.serialize());
  50328. }
  50329. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  50330. throw new Error("Unknown primitive type");
  50331. }
  50332. else {
  50333. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  50334. }
  50335. serializedGeometries[geometry.id] = true;
  50336. };
  50337. var serializeMesh = function (mesh, serializationScene) {
  50338. var serializationObject = {};
  50339. serializationObject.name = mesh.name;
  50340. serializationObject.id = mesh.id;
  50341. if (BABYLON.Tags.HasTags(mesh)) {
  50342. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  50343. }
  50344. serializationObject.position = mesh.position.asArray();
  50345. if (mesh.rotationQuaternion) {
  50346. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  50347. }
  50348. else if (mesh.rotation) {
  50349. serializationObject.rotation = mesh.rotation.asArray();
  50350. }
  50351. serializationObject.scaling = mesh.scaling.asArray();
  50352. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  50353. serializationObject.isEnabled = mesh.isEnabled();
  50354. serializationObject.isVisible = mesh.isVisible;
  50355. serializationObject.infiniteDistance = mesh.infiniteDistance;
  50356. serializationObject.pickable = mesh.isPickable;
  50357. serializationObject.receiveShadows = mesh.receiveShadows;
  50358. serializationObject.billboardMode = mesh.billboardMode;
  50359. serializationObject.visibility = mesh.visibility;
  50360. serializationObject.checkCollisions = mesh.checkCollisions;
  50361. // Parent
  50362. if (mesh.parent) {
  50363. serializationObject.parentId = mesh.parent.id;
  50364. }
  50365. // Geometry
  50366. var geometry = mesh._geometry;
  50367. if (geometry) {
  50368. var geometryId = geometry.id;
  50369. serializationObject.geometryId = geometryId;
  50370. if (!mesh.getScene().getGeometryByID(geometryId)) {
  50371. // 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
  50372. serializeGeometry(geometry, serializationScene.geometries);
  50373. }
  50374. // SubMeshes
  50375. serializationObject.subMeshes = [];
  50376. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  50377. var subMesh = mesh.subMeshes[subIndex];
  50378. serializationObject.subMeshes.push({
  50379. materialIndex: subMesh.materialIndex,
  50380. verticesStart: subMesh.verticesStart,
  50381. verticesCount: subMesh.verticesCount,
  50382. indexStart: subMesh.indexStart,
  50383. indexCount: subMesh.indexCount
  50384. });
  50385. }
  50386. }
  50387. // Material
  50388. if (mesh.material) {
  50389. serializationObject.materialId = mesh.material.id;
  50390. }
  50391. else {
  50392. mesh.material = null;
  50393. }
  50394. // Skeleton
  50395. if (mesh.skeleton) {
  50396. serializationObject.skeletonId = mesh.skeleton.id;
  50397. }
  50398. // Physics
  50399. //TODO implement correct serialization for physics impostors.
  50400. if (mesh.getPhysicsImpostor()) {
  50401. serializationObject.physicsMass = mesh.getPhysicsMass();
  50402. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  50403. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  50404. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  50405. }
  50406. // Instances
  50407. serializationObject.instances = [];
  50408. for (var index = 0; index < mesh.instances.length; index++) {
  50409. var instance = mesh.instances[index];
  50410. var serializationInstance = {
  50411. name: instance.name,
  50412. position: instance.position.asArray(),
  50413. scaling: instance.scaling.asArray()
  50414. };
  50415. if (instance.rotationQuaternion) {
  50416. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  50417. }
  50418. else if (instance.rotation) {
  50419. serializationInstance.rotation = instance.rotation.asArray();
  50420. }
  50421. serializationObject.instances.push(serializationInstance);
  50422. // Animations
  50423. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  50424. serializationInstance.ranges = instance.serializeAnimationRanges();
  50425. }
  50426. // Animations
  50427. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  50428. serializationObject.ranges = mesh.serializeAnimationRanges();
  50429. // Layer mask
  50430. serializationObject.layerMask = mesh.layerMask;
  50431. // Action Manager
  50432. if (mesh.actionManager) {
  50433. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  50434. }
  50435. return serializationObject;
  50436. };
  50437. var finalizeSingleMesh = function (mesh, serializationObject) {
  50438. //only works if the mesh is already loaded
  50439. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  50440. //serialize material
  50441. if (mesh.material) {
  50442. if (mesh.material instanceof BABYLON.StandardMaterial) {
  50443. serializationObject.materials = serializationObject.materials || [];
  50444. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  50445. serializationObject.materials.push(mesh.material.serialize());
  50446. }
  50447. }
  50448. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  50449. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  50450. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  50451. serializationObject.multiMaterials.push(mesh.material.serialize());
  50452. }
  50453. }
  50454. }
  50455. //serialize geometry
  50456. var geometry = mesh._geometry;
  50457. if (geometry) {
  50458. if (!serializationObject.geometries) {
  50459. serializationObject.geometries = {};
  50460. serializationObject.geometries.boxes = [];
  50461. serializationObject.geometries.spheres = [];
  50462. serializationObject.geometries.cylinders = [];
  50463. serializationObject.geometries.toruses = [];
  50464. serializationObject.geometries.grounds = [];
  50465. serializationObject.geometries.planes = [];
  50466. serializationObject.geometries.torusKnots = [];
  50467. serializationObject.geometries.vertexData = [];
  50468. }
  50469. serializeGeometry(geometry, serializationObject.geometries);
  50470. }
  50471. // Skeletons
  50472. if (mesh.skeleton) {
  50473. serializationObject.skeletons = serializationObject.skeletons || [];
  50474. serializationObject.skeletons.push(mesh.skeleton.serialize());
  50475. }
  50476. //serialize the actual mesh
  50477. serializationObject.meshes = serializationObject.meshes || [];
  50478. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  50479. }
  50480. };
  50481. var SceneSerializer = (function () {
  50482. function SceneSerializer() {
  50483. }
  50484. SceneSerializer.ClearCache = function () {
  50485. serializedGeometries = [];
  50486. };
  50487. SceneSerializer.Serialize = function (scene) {
  50488. var serializationObject = {};
  50489. // Scene
  50490. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  50491. serializationObject.autoClear = scene.autoClear;
  50492. serializationObject.clearColor = scene.clearColor.asArray();
  50493. serializationObject.ambientColor = scene.ambientColor.asArray();
  50494. serializationObject.gravity = scene.gravity.asArray();
  50495. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  50496. serializationObject.workerCollisions = scene.workerCollisions;
  50497. // Fog
  50498. if (scene.fogMode && scene.fogMode !== 0) {
  50499. serializationObject.fogMode = scene.fogMode;
  50500. serializationObject.fogColor = scene.fogColor.asArray();
  50501. serializationObject.fogStart = scene.fogStart;
  50502. serializationObject.fogEnd = scene.fogEnd;
  50503. serializationObject.fogDensity = scene.fogDensity;
  50504. }
  50505. //Physics
  50506. if (scene.isPhysicsEnabled()) {
  50507. serializationObject.physicsEnabled = true;
  50508. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  50509. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  50510. }
  50511. // Lights
  50512. serializationObject.lights = [];
  50513. var index;
  50514. var light;
  50515. for (index = 0; index < scene.lights.length; index++) {
  50516. light = scene.lights[index];
  50517. serializationObject.lights.push(light.serialize());
  50518. }
  50519. // Cameras
  50520. serializationObject.cameras = [];
  50521. for (index = 0; index < scene.cameras.length; index++) {
  50522. var camera = scene.cameras[index];
  50523. serializationObject.cameras.push(camera.serialize());
  50524. }
  50525. if (scene.activeCamera) {
  50526. serializationObject.activeCameraID = scene.activeCamera.id;
  50527. }
  50528. // Animations
  50529. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  50530. // Materials
  50531. serializationObject.materials = [];
  50532. serializationObject.multiMaterials = [];
  50533. var material;
  50534. for (index = 0; index < scene.materials.length; index++) {
  50535. material = scene.materials[index];
  50536. serializationObject.materials.push(material.serialize());
  50537. }
  50538. // MultiMaterials
  50539. serializationObject.multiMaterials = [];
  50540. for (index = 0; index < scene.multiMaterials.length; index++) {
  50541. var multiMaterial = scene.multiMaterials[index];
  50542. serializationObject.multiMaterials.push(multiMaterial.serialize());
  50543. }
  50544. // Skeletons
  50545. serializationObject.skeletons = [];
  50546. for (index = 0; index < scene.skeletons.length; index++) {
  50547. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  50548. }
  50549. // Geometries
  50550. serializationObject.geometries = {};
  50551. serializationObject.geometries.boxes = [];
  50552. serializationObject.geometries.spheres = [];
  50553. serializationObject.geometries.cylinders = [];
  50554. serializationObject.geometries.toruses = [];
  50555. serializationObject.geometries.grounds = [];
  50556. serializationObject.geometries.planes = [];
  50557. serializationObject.geometries.torusKnots = [];
  50558. serializationObject.geometries.vertexData = [];
  50559. serializedGeometries = [];
  50560. var geometries = scene.getGeometries();
  50561. for (index = 0; index < geometries.length; index++) {
  50562. var geometry = geometries[index];
  50563. if (geometry.isReady()) {
  50564. serializeGeometry(geometry, serializationObject.geometries);
  50565. }
  50566. }
  50567. // Meshes
  50568. serializationObject.meshes = [];
  50569. for (index = 0; index < scene.meshes.length; index++) {
  50570. var abstractMesh = scene.meshes[index];
  50571. if (abstractMesh instanceof BABYLON.Mesh) {
  50572. var mesh = abstractMesh;
  50573. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  50574. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  50575. }
  50576. }
  50577. }
  50578. // Particles Systems
  50579. serializationObject.particleSystems = [];
  50580. for (index = 0; index < scene.particleSystems.length; index++) {
  50581. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  50582. }
  50583. // Lens flares
  50584. serializationObject.lensFlareSystems = [];
  50585. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  50586. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  50587. }
  50588. // Shadows
  50589. serializationObject.shadowGenerators = [];
  50590. for (index = 0; index < scene.lights.length; index++) {
  50591. light = scene.lights[index];
  50592. var shadowGenerator = light.getShadowGenerator();
  50593. // Only support serialization for official generator so far.
  50594. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  50595. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  50596. }
  50597. }
  50598. // Action Manager
  50599. if (scene.actionManager) {
  50600. serializationObject.actions = scene.actionManager.serialize("scene");
  50601. }
  50602. // Audio
  50603. serializationObject.sounds = [];
  50604. for (index = 0; index < scene.soundTracks.length; index++) {
  50605. var soundtrack = scene.soundTracks[index];
  50606. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  50607. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  50608. }
  50609. }
  50610. return serializationObject;
  50611. };
  50612. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  50613. if (withParents === void 0) { withParents = false; }
  50614. if (withChildren === void 0) { withChildren = false; }
  50615. var serializationObject = {};
  50616. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  50617. if (withParents || withChildren) {
  50618. //deliberate for loop! not for each, appended should be processed as well.
  50619. for (var i = 0; i < toSerialize.length; ++i) {
  50620. if (withChildren) {
  50621. toSerialize[i].getDescendants().forEach(function (node) {
  50622. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  50623. toSerialize.push(node);
  50624. }
  50625. });
  50626. }
  50627. //make sure the array doesn't contain the object already
  50628. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  50629. toSerialize.push(toSerialize[i].parent);
  50630. }
  50631. }
  50632. }
  50633. toSerialize.forEach(function (mesh) {
  50634. finalizeSingleMesh(mesh, serializationObject);
  50635. });
  50636. return serializationObject;
  50637. };
  50638. return SceneSerializer;
  50639. })();
  50640. BABYLON.SceneSerializer = SceneSerializer;
  50641. })(BABYLON || (BABYLON = {}));
  50642. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  50643. // Huge respect for a such great lib.
  50644. // Earcut license:
  50645. // Copyright (c) 2016, Mapbox
  50646. //
  50647. // Permission to use, copy, modify, and/or distribute this software for any purpose
  50648. // with or without fee is hereby granted, provided that the above copyright notice
  50649. // and this permission notice appear in all copies.
  50650. //
  50651. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  50652. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  50653. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  50654. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  50655. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  50656. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  50657. // THIS SOFTWARE.
  50658. var Earcut;
  50659. (function (Earcut) {
  50660. /**
  50661. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  50662. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  50663. * @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).
  50664. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  50665. */
  50666. function earcut(data, holeIndices, dim) {
  50667. dim = dim || 2;
  50668. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  50669. if (!outerNode)
  50670. return triangles;
  50671. var minX, minY, maxX, maxY, x, y, size;
  50672. if (hasHoles)
  50673. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  50674. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  50675. if (data.length > 80 * dim) {
  50676. minX = maxX = data[0];
  50677. minY = maxY = data[1];
  50678. for (var i = dim; i < outerLen; i += dim) {
  50679. x = data[i];
  50680. y = data[i + 1];
  50681. if (x < minX)
  50682. minX = x;
  50683. if (y < minY)
  50684. minY = y;
  50685. if (x > maxX)
  50686. maxX = x;
  50687. if (y > maxY)
  50688. maxY = y;
  50689. }
  50690. // minX, minY and size are later used to transform coords into integers for z-order calculation
  50691. size = Math.max(maxX - minX, maxY - minY);
  50692. }
  50693. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  50694. return triangles;
  50695. }
  50696. Earcut.earcut = earcut;
  50697. // create a circular doubly linked list from polygon points in the specified winding order
  50698. function linkedList(data, start, end, dim, clockwise) {
  50699. var i, last;
  50700. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  50701. for (i = start; i < end; i += dim)
  50702. last = insertNode(i, data[i], data[i + 1], last);
  50703. }
  50704. else {
  50705. for (i = end - dim; i >= start; i -= dim)
  50706. last = insertNode(i, data[i], data[i + 1], last);
  50707. }
  50708. if (last && equals(last, last.next)) {
  50709. removeNode(last);
  50710. last = last.next;
  50711. }
  50712. return last;
  50713. }
  50714. // eliminate colinear or duplicate points
  50715. function filterPoints(start, end) {
  50716. if (!start)
  50717. return start;
  50718. if (!end)
  50719. end = start;
  50720. var p = start, again;
  50721. do {
  50722. again = false;
  50723. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  50724. removeNode(p);
  50725. p = end = p.prev;
  50726. if (p === p.next)
  50727. return null;
  50728. again = true;
  50729. }
  50730. else {
  50731. p = p.next;
  50732. }
  50733. } while (again || p !== end);
  50734. return end;
  50735. }
  50736. // main ear slicing loop which triangulates a polygon (given as a linked list)
  50737. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  50738. if (!ear)
  50739. return;
  50740. // interlink polygon nodes in z-order
  50741. if (!pass && size)
  50742. indexCurve(ear, minX, minY, size);
  50743. var stop = ear, prev, next;
  50744. // iterate through ears, slicing them one by one
  50745. while (ear.prev !== ear.next) {
  50746. prev = ear.prev;
  50747. next = ear.next;
  50748. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  50749. // cut off the triangle
  50750. triangles.push(prev.i / dim);
  50751. triangles.push(ear.i / dim);
  50752. triangles.push(next.i / dim);
  50753. removeNode(ear);
  50754. // skipping the next vertice leads to less sliver triangles
  50755. ear = next.next;
  50756. stop = next.next;
  50757. continue;
  50758. }
  50759. ear = next;
  50760. // if we looped through the whole remaining polygon and can't find any more ears
  50761. if (ear === stop) {
  50762. // try filtering points and slicing again
  50763. if (!pass) {
  50764. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  50765. }
  50766. else if (pass === 1) {
  50767. ear = cureLocalIntersections(ear, triangles, dim);
  50768. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  50769. }
  50770. else if (pass === 2) {
  50771. splitEarcut(ear, triangles, dim, minX, minY, size);
  50772. }
  50773. break;
  50774. }
  50775. }
  50776. }
  50777. // check whether a polygon node forms a valid ear with adjacent nodes
  50778. function isEar(ear) {
  50779. var a = ear.prev, b = ear, c = ear.next;
  50780. if (area(a, b, c) >= 0)
  50781. return false; // reflex, can't be an ear
  50782. // now make sure we don't have other points inside the potential ear
  50783. var p = ear.next.next;
  50784. while (p !== ear.prev) {
  50785. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  50786. area(p.prev, p, p.next) >= 0)
  50787. return false;
  50788. p = p.next;
  50789. }
  50790. return true;
  50791. }
  50792. function isEarHashed(ear, minX, minY, size) {
  50793. var a = ear.prev, b = ear, c = ear.next;
  50794. if (area(a, b, c) >= 0)
  50795. return false; // reflex, can't be an ear
  50796. // triangle bbox; min & max are calculated like this for speed
  50797. 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);
  50798. // z-order range for the current triangle bbox;
  50799. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  50800. // first look for points inside the triangle in increasing z-order
  50801. var p = ear.nextZ;
  50802. while (p && p.z <= maxZ) {
  50803. if (p !== ear.prev &&
  50804. p !== ear.next &&
  50805. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  50806. area(p.prev, p, p.next) >= 0)
  50807. return false;
  50808. p = p.nextZ;
  50809. }
  50810. // then look for points in decreasing z-order
  50811. p = ear.prevZ;
  50812. while (p && p.z >= minZ) {
  50813. if (p !== ear.prev &&
  50814. p !== ear.next &&
  50815. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  50816. area(p.prev, p, p.next) >= 0)
  50817. return false;
  50818. p = p.prevZ;
  50819. }
  50820. return true;
  50821. }
  50822. // go through all polygon nodes and cure small local self-intersections
  50823. function cureLocalIntersections(start, triangles, dim) {
  50824. var p = start;
  50825. do {
  50826. var a = p.prev, b = p.next.next;
  50827. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  50828. triangles.push(a.i / dim);
  50829. triangles.push(p.i / dim);
  50830. triangles.push(b.i / dim);
  50831. // remove two nodes involved
  50832. removeNode(p);
  50833. removeNode(p.next);
  50834. p = start = b;
  50835. }
  50836. p = p.next;
  50837. } while (p !== start);
  50838. return p;
  50839. }
  50840. // try splitting polygon into two and triangulate them independently
  50841. function splitEarcut(start, triangles, dim, minX, minY, size) {
  50842. // look for a valid diagonal that divides the polygon into two
  50843. var a = start;
  50844. do {
  50845. var b = a.next.next;
  50846. while (b !== a.prev) {
  50847. if (a.i !== b.i && isValidDiagonal(a, b)) {
  50848. // split the polygon in two by the diagonal
  50849. var c = splitPolygon(a, b);
  50850. // filter colinear points around the cuts
  50851. a = filterPoints(a, a.next);
  50852. c = filterPoints(c, c.next);
  50853. // run earcut on each half
  50854. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  50855. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  50856. return;
  50857. }
  50858. b = b.next;
  50859. }
  50860. a = a.next;
  50861. } while (a !== start);
  50862. }
  50863. // link every hole into the outer loop, producing a single-ring polygon without holes
  50864. function eliminateHoles(data, holeIndices, outerNode, dim) {
  50865. var queue = [], i, len, start, end, list;
  50866. for (i = 0, len = holeIndices.length; i < len; i++) {
  50867. start = holeIndices[i] * dim;
  50868. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  50869. list = linkedList(data, start, end, dim, false);
  50870. if (list === list.next)
  50871. list.steiner = true;
  50872. queue.push(getLeftmost(list));
  50873. }
  50874. queue.sort(compareX);
  50875. // process holes from left to right
  50876. for (i = 0; i < queue.length; i++) {
  50877. eliminateHole(queue[i], outerNode);
  50878. outerNode = filterPoints(outerNode, outerNode.next);
  50879. }
  50880. return outerNode;
  50881. }
  50882. function compareX(a, b) {
  50883. return a.x - b.x;
  50884. }
  50885. // find a bridge between vertices that connects hole with an outer ring and and link it
  50886. function eliminateHole(hole, outerNode) {
  50887. outerNode = findHoleBridge(hole, outerNode);
  50888. if (outerNode) {
  50889. var b = splitPolygon(outerNode, hole);
  50890. filterPoints(b, b.next);
  50891. }
  50892. }
  50893. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  50894. function findHoleBridge(hole, outerNode) {
  50895. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  50896. // find a segment intersected by a ray from the hole's leftmost point to the left;
  50897. // segment's endpoint with lesser x will be potential connection point
  50898. do {
  50899. if (hy <= p.y && hy >= p.next.y) {
  50900. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  50901. if (x <= hx && x > qx) {
  50902. qx = x;
  50903. if (x === hx) {
  50904. if (hy === p.y)
  50905. return p;
  50906. if (hy === p.next.y)
  50907. return p.next;
  50908. }
  50909. m = p.x < p.next.x ? p : p.next;
  50910. }
  50911. }
  50912. p = p.next;
  50913. } while (p !== outerNode);
  50914. if (!m)
  50915. return null;
  50916. if (hx === qx)
  50917. return m.prev; // hole touches outer segment; pick lower endpoint
  50918. // look for points inside the triangle of hole point, segment intersection and endpoint;
  50919. // if there are no points found, we have a valid connection;
  50920. // otherwise choose the point of the minimum angle with the ray as connection point
  50921. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  50922. p = m.next;
  50923. while (p !== stop) {
  50924. if (hx >= p.x &&
  50925. p.x >= mx &&
  50926. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  50927. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  50928. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  50929. m = p;
  50930. tanMin = tan;
  50931. }
  50932. }
  50933. p = p.next;
  50934. }
  50935. return m;
  50936. }
  50937. // interlink polygon nodes in z-order
  50938. function indexCurve(start, minX, minY, size) {
  50939. var p = start;
  50940. do {
  50941. if (p.z === null)
  50942. p.z = zOrder(p.x, p.y, minX, minY, size);
  50943. p.prevZ = p.prev;
  50944. p.nextZ = p.next;
  50945. p = p.next;
  50946. } while (p !== start);
  50947. p.prevZ.nextZ = null;
  50948. p.prevZ = null;
  50949. sortLinked(p);
  50950. }
  50951. // Simon Tatham's linked list merge sort algorithm
  50952. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  50953. function sortLinked(list) {
  50954. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  50955. do {
  50956. p = list;
  50957. list = null;
  50958. tail = null;
  50959. numMerges = 0;
  50960. while (p) {
  50961. numMerges++;
  50962. q = p;
  50963. pSize = 0;
  50964. for (i = 0; i < inSize; i++) {
  50965. pSize++;
  50966. q = q.nextZ;
  50967. if (!q)
  50968. break;
  50969. }
  50970. qSize = inSize;
  50971. while (pSize > 0 || (qSize > 0 && q)) {
  50972. if (pSize === 0) {
  50973. e = q;
  50974. q = q.nextZ;
  50975. qSize--;
  50976. }
  50977. else if (qSize === 0 || !q) {
  50978. e = p;
  50979. p = p.nextZ;
  50980. pSize--;
  50981. }
  50982. else if (p.z <= q.z) {
  50983. e = p;
  50984. p = p.nextZ;
  50985. pSize--;
  50986. }
  50987. else {
  50988. e = q;
  50989. q = q.nextZ;
  50990. qSize--;
  50991. }
  50992. if (tail)
  50993. tail.nextZ = e;
  50994. else
  50995. list = e;
  50996. e.prevZ = tail;
  50997. tail = e;
  50998. }
  50999. p = q;
  51000. }
  51001. tail.nextZ = null;
  51002. inSize *= 2;
  51003. } while (numMerges > 1);
  51004. return list;
  51005. }
  51006. // z-order of a point given coords and size of the data bounding box
  51007. function zOrder(x, y, minX, minY, size) {
  51008. // coords are transformed into non-negative 15-bit integer range
  51009. x = 32767 * (x - minX) / size;
  51010. y = 32767 * (y - minY) / size;
  51011. x = (x | (x << 8)) & 0x00FF00FF;
  51012. x = (x | (x << 4)) & 0x0F0F0F0F;
  51013. x = (x | (x << 2)) & 0x33333333;
  51014. x = (x | (x << 1)) & 0x55555555;
  51015. y = (y | (y << 8)) & 0x00FF00FF;
  51016. y = (y | (y << 4)) & 0x0F0F0F0F;
  51017. y = (y | (y << 2)) & 0x33333333;
  51018. y = (y | (y << 1)) & 0x55555555;
  51019. return x | (y << 1);
  51020. }
  51021. // find the leftmost node of a polygon ring
  51022. function getLeftmost(start) {
  51023. var p = start, leftmost = start;
  51024. do {
  51025. if (p.x < leftmost.x)
  51026. leftmost = p;
  51027. p = p.next;
  51028. } while (p !== start);
  51029. return leftmost;
  51030. }
  51031. // check if a point lies within a convex triangle
  51032. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  51033. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  51034. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  51035. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  51036. }
  51037. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  51038. function isValidDiagonal(a, b) {
  51039. return a.next.i !== b.i &&
  51040. a.prev.i !== b.i &&
  51041. !intersectsPolygon(a, b) &&
  51042. locallyInside(a, b) &&
  51043. locallyInside(b, a) &&
  51044. middleInside(a, b);
  51045. }
  51046. // signed area of a triangle
  51047. function area(p, q, r) {
  51048. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  51049. }
  51050. // check if two points are equal
  51051. function equals(p1, p2) {
  51052. return p1.x === p2.x && p1.y === p2.y;
  51053. }
  51054. // check if two segments intersect
  51055. function intersects(p1, q1, p2, q2) {
  51056. if ((equals(p1, q1) && equals(p2, q2)) ||
  51057. (equals(p1, q2) && equals(p2, q1)))
  51058. return true;
  51059. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  51060. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  51061. }
  51062. // check if a polygon diagonal intersects any polygon segments
  51063. function intersectsPolygon(a, b) {
  51064. var p = a;
  51065. do {
  51066. if (p.i !== a.i &&
  51067. p.next.i !== a.i &&
  51068. p.i !== b.i &&
  51069. p.next.i !== b.i &&
  51070. intersects(p, p.next, a, b))
  51071. return true;
  51072. p = p.next;
  51073. } while (p !== a);
  51074. return false;
  51075. }
  51076. // check if a polygon diagonal is locally inside the polygon
  51077. function locallyInside(a, b) {
  51078. return area(a.prev, a, a.next) < 0
  51079. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  51080. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  51081. }
  51082. // check if the middle point of a polygon diagonal is inside the polygon
  51083. function middleInside(a, b) {
  51084. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  51085. do {
  51086. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  51087. inside = !inside;
  51088. p = p.next;
  51089. } while (p !== a);
  51090. return inside;
  51091. }
  51092. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  51093. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  51094. function splitPolygon(a, b) {
  51095. 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;
  51096. a.next = b;
  51097. b.prev = a;
  51098. a2.next = an;
  51099. an.prev = a2;
  51100. b2.next = a2;
  51101. a2.prev = b2;
  51102. bp.next = b2;
  51103. b2.prev = bp;
  51104. return b2;
  51105. }
  51106. // create a node and optionally link it with previous one (in a circular doubly linked list)
  51107. function insertNode(i, x, y, last) {
  51108. var p = new Node(i, x, y);
  51109. if (!last) {
  51110. p.prev = p;
  51111. p.next = p;
  51112. }
  51113. else {
  51114. p.next = last.next;
  51115. p.prev = last;
  51116. last.next.prev = p;
  51117. last.next = p;
  51118. }
  51119. return p;
  51120. }
  51121. function removeNode(p) {
  51122. p.next.prev = p.prev;
  51123. p.prev.next = p.next;
  51124. if (p.prevZ)
  51125. p.prevZ.nextZ = p.nextZ;
  51126. if (p.nextZ)
  51127. p.nextZ.prevZ = p.prevZ;
  51128. }
  51129. function Node(i, x, y) {
  51130. // vertice index in coordinates array
  51131. this.i = i;
  51132. // vertex coordinates
  51133. this.x = x;
  51134. this.y = y;
  51135. // previous and next vertice nodes in a polygon ring
  51136. this.prev = null;
  51137. this.next = null;
  51138. // z-order curve value
  51139. this.z = null;
  51140. // previous and next nodes in z-order
  51141. this.prevZ = null;
  51142. this.nextZ = null;
  51143. // indicates whether this is a steiner point
  51144. this.steiner = false;
  51145. }
  51146. /**
  51147. * return a percentage difference between the polygon area and its triangulation area;
  51148. * used to verify correctness of triangulation
  51149. */
  51150. function deviation(data, holeIndices, dim, triangles) {
  51151. var hasHoles = holeIndices && holeIndices.length;
  51152. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  51153. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  51154. if (hasHoles) {
  51155. for (var i = 0, len = holeIndices.length; i < len; i++) {
  51156. var start = holeIndices[i] * dim;
  51157. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  51158. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  51159. }
  51160. }
  51161. var trianglesArea = 0;
  51162. for (i = 0; i < triangles.length; i += 3) {
  51163. var a = triangles[i] * dim;
  51164. var b = triangles[i + 1] * dim;
  51165. var c = triangles[i + 2] * dim;
  51166. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  51167. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  51168. }
  51169. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  51170. }
  51171. Earcut.deviation = deviation;
  51172. ;
  51173. function signedArea(data, start, end, dim) {
  51174. var sum = 0;
  51175. for (var i = start, j = end - dim; i < end; i += dim) {
  51176. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  51177. j = i;
  51178. }
  51179. return sum;
  51180. }
  51181. /**
  51182. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  51183. */
  51184. function flatten(data) {
  51185. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  51186. for (var i = 0; i < data.length; i++) {
  51187. for (var j = 0; j < data[i].length; j++) {
  51188. for (var d = 0; d < dim; d++)
  51189. result.vertices.push(data[i][j][d]);
  51190. }
  51191. if (i > 0) {
  51192. holeIndex += data[i - 1].length;
  51193. result.holes.push(holeIndex);
  51194. }
  51195. }
  51196. return result;
  51197. }
  51198. Earcut.flatten = flatten;
  51199. ;
  51200. })(Earcut || (Earcut = {}));
  51201. var BABYLON;
  51202. (function (BABYLON) {
  51203. // Unique ID when we import meshes from Babylon to CSG
  51204. var currentCSGMeshId = 0;
  51205. // # class Vertex
  51206. // Represents a vertex of a polygon. Use your own vertex class instead of this
  51207. // one to provide additional features like texture coordinates and vertex
  51208. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  51209. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  51210. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  51211. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  51212. // is not used anywhere else.
  51213. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  51214. var Vertex = (function () {
  51215. function Vertex(pos, normal, uv) {
  51216. this.pos = pos;
  51217. this.normal = normal;
  51218. this.uv = uv;
  51219. }
  51220. Vertex.prototype.clone = function () {
  51221. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  51222. };
  51223. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  51224. // orientation of a polygon is flipped.
  51225. Vertex.prototype.flip = function () {
  51226. this.normal = this.normal.scale(-1);
  51227. };
  51228. // Create a new vertex between this vertex and `other` by linearly
  51229. // interpolating all properties using a parameter of `t`. Subclasses should
  51230. // override this to interpolate additional properties.
  51231. Vertex.prototype.interpolate = function (other, t) {
  51232. 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));
  51233. };
  51234. return Vertex;
  51235. })();
  51236. // # class Plane
  51237. // Represents a plane in 3D space.
  51238. var Plane = (function () {
  51239. function Plane(normal, w) {
  51240. this.normal = normal;
  51241. this.w = w;
  51242. }
  51243. Plane.FromPoints = function (a, b, c) {
  51244. var v0 = c.subtract(a);
  51245. var v1 = b.subtract(a);
  51246. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  51247. return null;
  51248. }
  51249. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  51250. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  51251. };
  51252. Plane.prototype.clone = function () {
  51253. return new Plane(this.normal.clone(), this.w);
  51254. };
  51255. Plane.prototype.flip = function () {
  51256. this.normal.scaleInPlace(-1);
  51257. this.w = -this.w;
  51258. };
  51259. // Split `polygon` by this plane if needed, then put the polygon or polygon
  51260. // fragments in the appropriate lists. Coplanar polygons go into either
  51261. // `coplanarFront` or `coplanarBack` depending on their orientation with
  51262. // respect to this plane. Polygons in front or in back of this plane go into
  51263. // either `front` or `back`.
  51264. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  51265. var COPLANAR = 0;
  51266. var FRONT = 1;
  51267. var BACK = 2;
  51268. var SPANNING = 3;
  51269. // Classify each point as well as the entire polygon into one of the above
  51270. // four classes.
  51271. var polygonType = 0;
  51272. var types = [];
  51273. var i;
  51274. var t;
  51275. for (i = 0; i < polygon.vertices.length; i++) {
  51276. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  51277. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  51278. polygonType |= type;
  51279. types.push(type);
  51280. }
  51281. // Put the polygon in the correct list, splitting it when necessary.
  51282. switch (polygonType) {
  51283. case COPLANAR:
  51284. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  51285. break;
  51286. case FRONT:
  51287. front.push(polygon);
  51288. break;
  51289. case BACK:
  51290. back.push(polygon);
  51291. break;
  51292. case SPANNING:
  51293. var f = [], b = [];
  51294. for (i = 0; i < polygon.vertices.length; i++) {
  51295. var j = (i + 1) % polygon.vertices.length;
  51296. var ti = types[i], tj = types[j];
  51297. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  51298. if (ti !== BACK)
  51299. f.push(vi);
  51300. if (ti !== FRONT)
  51301. b.push(ti !== BACK ? vi.clone() : vi);
  51302. if ((ti | tj) === SPANNING) {
  51303. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  51304. var v = vi.interpolate(vj, t);
  51305. f.push(v);
  51306. b.push(v.clone());
  51307. }
  51308. }
  51309. var poly;
  51310. if (f.length >= 3) {
  51311. poly = new Polygon(f, polygon.shared);
  51312. if (poly.plane)
  51313. front.push(poly);
  51314. }
  51315. if (b.length >= 3) {
  51316. poly = new Polygon(b, polygon.shared);
  51317. if (poly.plane)
  51318. back.push(poly);
  51319. }
  51320. break;
  51321. }
  51322. };
  51323. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  51324. // point is on the plane.
  51325. Plane.EPSILON = 1e-5;
  51326. return Plane;
  51327. })();
  51328. // # class Polygon
  51329. // Represents a convex polygon. The vertices used to initialize a polygon must
  51330. // be coplanar and form a convex loop.
  51331. //
  51332. // Each convex polygon has a `shared` property, which is shared between all
  51333. // polygons that are clones of each other or were split from the same polygon.
  51334. // This can be used to define per-polygon properties (such as surface color).
  51335. var Polygon = (function () {
  51336. function Polygon(vertices, shared) {
  51337. this.vertices = vertices;
  51338. this.shared = shared;
  51339. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  51340. }
  51341. Polygon.prototype.clone = function () {
  51342. var vertices = this.vertices.map(function (v) { return v.clone(); });
  51343. return new Polygon(vertices, this.shared);
  51344. };
  51345. Polygon.prototype.flip = function () {
  51346. this.vertices.reverse().map(function (v) { v.flip(); });
  51347. this.plane.flip();
  51348. };
  51349. return Polygon;
  51350. })();
  51351. // # class Node
  51352. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  51353. // by picking a polygon to split along. That polygon (and all other coplanar
  51354. // polygons) are added directly to that node and the other polygons are added to
  51355. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  51356. // no distinction between internal and leaf nodes.
  51357. var Node = (function () {
  51358. function Node(polygons) {
  51359. this.plane = null;
  51360. this.front = null;
  51361. this.back = null;
  51362. this.polygons = [];
  51363. if (polygons) {
  51364. this.build(polygons);
  51365. }
  51366. }
  51367. Node.prototype.clone = function () {
  51368. var node = new Node();
  51369. node.plane = this.plane && this.plane.clone();
  51370. node.front = this.front && this.front.clone();
  51371. node.back = this.back && this.back.clone();
  51372. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  51373. return node;
  51374. };
  51375. // Convert solid space to empty space and empty space to solid space.
  51376. Node.prototype.invert = function () {
  51377. for (var i = 0; i < this.polygons.length; i++) {
  51378. this.polygons[i].flip();
  51379. }
  51380. if (this.plane) {
  51381. this.plane.flip();
  51382. }
  51383. if (this.front) {
  51384. this.front.invert();
  51385. }
  51386. if (this.back) {
  51387. this.back.invert();
  51388. }
  51389. var temp = this.front;
  51390. this.front = this.back;
  51391. this.back = temp;
  51392. };
  51393. // Recursively remove all polygons in `polygons` that are inside this BSP
  51394. // tree.
  51395. Node.prototype.clipPolygons = function (polygons) {
  51396. if (!this.plane)
  51397. return polygons.slice();
  51398. var front = [], back = [];
  51399. for (var i = 0; i < polygons.length; i++) {
  51400. this.plane.splitPolygon(polygons[i], front, back, front, back);
  51401. }
  51402. if (this.front) {
  51403. front = this.front.clipPolygons(front);
  51404. }
  51405. if (this.back) {
  51406. back = this.back.clipPolygons(back);
  51407. }
  51408. else {
  51409. back = [];
  51410. }
  51411. return front.concat(back);
  51412. };
  51413. // Remove all polygons in this BSP tree that are inside the other BSP tree
  51414. // `bsp`.
  51415. Node.prototype.clipTo = function (bsp) {
  51416. this.polygons = bsp.clipPolygons(this.polygons);
  51417. if (this.front)
  51418. this.front.clipTo(bsp);
  51419. if (this.back)
  51420. this.back.clipTo(bsp);
  51421. };
  51422. // Return a list of all polygons in this BSP tree.
  51423. Node.prototype.allPolygons = function () {
  51424. var polygons = this.polygons.slice();
  51425. if (this.front)
  51426. polygons = polygons.concat(this.front.allPolygons());
  51427. if (this.back)
  51428. polygons = polygons.concat(this.back.allPolygons());
  51429. return polygons;
  51430. };
  51431. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  51432. // new polygons are filtered down to the bottom of the tree and become new
  51433. // nodes there. Each set of polygons is partitioned using the first polygon
  51434. // (no heuristic is used to pick a good split).
  51435. Node.prototype.build = function (polygons) {
  51436. if (!polygons.length)
  51437. return;
  51438. if (!this.plane)
  51439. this.plane = polygons[0].plane.clone();
  51440. var front = [], back = [];
  51441. for (var i = 0; i < polygons.length; i++) {
  51442. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  51443. }
  51444. if (front.length) {
  51445. if (!this.front)
  51446. this.front = new Node();
  51447. this.front.build(front);
  51448. }
  51449. if (back.length) {
  51450. if (!this.back)
  51451. this.back = new Node();
  51452. this.back.build(back);
  51453. }
  51454. };
  51455. return Node;
  51456. })();
  51457. var CSG = (function () {
  51458. function CSG() {
  51459. this.polygons = new Array();
  51460. }
  51461. // Convert BABYLON.Mesh to BABYLON.CSG
  51462. CSG.FromMesh = function (mesh) {
  51463. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  51464. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  51465. if (mesh instanceof BABYLON.Mesh) {
  51466. mesh.computeWorldMatrix(true);
  51467. matrix = mesh.getWorldMatrix();
  51468. meshPosition = mesh.position.clone();
  51469. meshRotation = mesh.rotation.clone();
  51470. if (mesh.rotationQuaternion) {
  51471. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  51472. }
  51473. meshScaling = mesh.scaling.clone();
  51474. }
  51475. else {
  51476. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  51477. }
  51478. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51479. var subMeshes = mesh.subMeshes;
  51480. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  51481. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  51482. vertices = [];
  51483. for (var j = 0; j < 3; j++) {
  51484. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  51485. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  51486. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  51487. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  51488. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  51489. vertex = new Vertex(position, normal, uv);
  51490. vertices.push(vertex);
  51491. }
  51492. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  51493. // To handle the case of degenerated triangle
  51494. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  51495. if (polygon.plane)
  51496. polygons.push(polygon);
  51497. }
  51498. }
  51499. var csg = CSG.FromPolygons(polygons);
  51500. csg.matrix = matrix;
  51501. csg.position = meshPosition;
  51502. csg.rotation = meshRotation;
  51503. csg.scaling = meshScaling;
  51504. csg.rotationQuaternion = meshRotationQuaternion;
  51505. currentCSGMeshId++;
  51506. return csg;
  51507. };
  51508. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  51509. CSG.FromPolygons = function (polygons) {
  51510. var csg = new CSG();
  51511. csg.polygons = polygons;
  51512. return csg;
  51513. };
  51514. CSG.prototype.clone = function () {
  51515. var csg = new CSG();
  51516. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  51517. csg.copyTransformAttributes(this);
  51518. return csg;
  51519. };
  51520. CSG.prototype.toPolygons = function () {
  51521. return this.polygons;
  51522. };
  51523. CSG.prototype.union = function (csg) {
  51524. var a = new Node(this.clone().polygons);
  51525. var b = new Node(csg.clone().polygons);
  51526. a.clipTo(b);
  51527. b.clipTo(a);
  51528. b.invert();
  51529. b.clipTo(a);
  51530. b.invert();
  51531. a.build(b.allPolygons());
  51532. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  51533. };
  51534. CSG.prototype.unionInPlace = function (csg) {
  51535. var a = new Node(this.polygons);
  51536. var b = new Node(csg.polygons);
  51537. a.clipTo(b);
  51538. b.clipTo(a);
  51539. b.invert();
  51540. b.clipTo(a);
  51541. b.invert();
  51542. a.build(b.allPolygons());
  51543. this.polygons = a.allPolygons();
  51544. };
  51545. CSG.prototype.subtract = function (csg) {
  51546. var a = new Node(this.clone().polygons);
  51547. var b = new Node(csg.clone().polygons);
  51548. a.invert();
  51549. a.clipTo(b);
  51550. b.clipTo(a);
  51551. b.invert();
  51552. b.clipTo(a);
  51553. b.invert();
  51554. a.build(b.allPolygons());
  51555. a.invert();
  51556. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  51557. };
  51558. CSG.prototype.subtractInPlace = function (csg) {
  51559. var a = new Node(this.polygons);
  51560. var b = new Node(csg.polygons);
  51561. a.invert();
  51562. a.clipTo(b);
  51563. b.clipTo(a);
  51564. b.invert();
  51565. b.clipTo(a);
  51566. b.invert();
  51567. a.build(b.allPolygons());
  51568. a.invert();
  51569. this.polygons = a.allPolygons();
  51570. };
  51571. CSG.prototype.intersect = function (csg) {
  51572. var a = new Node(this.clone().polygons);
  51573. var b = new Node(csg.clone().polygons);
  51574. a.invert();
  51575. b.clipTo(a);
  51576. b.invert();
  51577. a.clipTo(b);
  51578. b.clipTo(a);
  51579. a.build(b.allPolygons());
  51580. a.invert();
  51581. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  51582. };
  51583. CSG.prototype.intersectInPlace = function (csg) {
  51584. var a = new Node(this.polygons);
  51585. var b = new Node(csg.polygons);
  51586. a.invert();
  51587. b.clipTo(a);
  51588. b.invert();
  51589. a.clipTo(b);
  51590. b.clipTo(a);
  51591. a.build(b.allPolygons());
  51592. a.invert();
  51593. this.polygons = a.allPolygons();
  51594. };
  51595. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  51596. // not modified.
  51597. CSG.prototype.inverse = function () {
  51598. var csg = this.clone();
  51599. csg.inverseInPlace();
  51600. return csg;
  51601. };
  51602. CSG.prototype.inverseInPlace = function () {
  51603. this.polygons.map(function (p) { p.flip(); });
  51604. };
  51605. // This is used to keep meshes transformations so they can be restored
  51606. // when we build back a Babylon Mesh
  51607. // NB : All CSG operations are performed in world coordinates
  51608. CSG.prototype.copyTransformAttributes = function (csg) {
  51609. this.matrix = csg.matrix;
  51610. this.position = csg.position;
  51611. this.rotation = csg.rotation;
  51612. this.scaling = csg.scaling;
  51613. this.rotationQuaternion = csg.rotationQuaternion;
  51614. return this;
  51615. };
  51616. // Build Raw mesh from CSG
  51617. // Coordinates here are in world space
  51618. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  51619. var matrix = this.matrix.clone();
  51620. matrix.invert();
  51621. 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;
  51622. if (keepSubMeshes) {
  51623. // Sort Polygons, since subMeshes are indices range
  51624. polygons.sort(function (a, b) {
  51625. if (a.shared.meshId === b.shared.meshId) {
  51626. return a.shared.subMeshId - b.shared.subMeshId;
  51627. }
  51628. else {
  51629. return a.shared.meshId - b.shared.meshId;
  51630. }
  51631. });
  51632. }
  51633. for (var i = 0, il = polygons.length; i < il; i++) {
  51634. polygon = polygons[i];
  51635. // Building SubMeshes
  51636. if (!subMesh_dict[polygon.shared.meshId]) {
  51637. subMesh_dict[polygon.shared.meshId] = {};
  51638. }
  51639. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  51640. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  51641. indexStart: +Infinity,
  51642. indexEnd: -Infinity,
  51643. materialIndex: polygon.shared.materialIndex
  51644. };
  51645. }
  51646. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  51647. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  51648. polygonIndices[0] = 0;
  51649. polygonIndices[1] = j - 1;
  51650. polygonIndices[2] = j;
  51651. for (var k = 0; k < 3; k++) {
  51652. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  51653. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  51654. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  51655. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  51656. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  51657. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  51658. // Check if 2 points can be merged
  51659. if (!(typeof vertex_idx !== 'undefined' &&
  51660. normals[vertex_idx * 3] === localNormal.x &&
  51661. normals[vertex_idx * 3 + 1] === localNormal.y &&
  51662. normals[vertex_idx * 3 + 2] === localNormal.z &&
  51663. uvs[vertex_idx * 2] === uv.x &&
  51664. uvs[vertex_idx * 2 + 1] === uv.y)) {
  51665. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  51666. uvs.push(uv.x, uv.y);
  51667. normals.push(normal.x, normal.y, normal.z);
  51668. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  51669. }
  51670. indices.push(vertex_idx);
  51671. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  51672. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  51673. currentIndex++;
  51674. }
  51675. }
  51676. }
  51677. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  51678. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  51679. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  51680. mesh.setIndices(indices);
  51681. if (keepSubMeshes) {
  51682. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  51683. var materialIndexOffset = 0, materialMaxIndex;
  51684. mesh.subMeshes = new Array();
  51685. for (var m in subMesh_dict) {
  51686. materialMaxIndex = -1;
  51687. for (var sm in subMesh_dict[m]) {
  51688. subMesh_obj = subMesh_dict[m][sm];
  51689. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  51690. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  51691. }
  51692. materialIndexOffset += ++materialMaxIndex;
  51693. }
  51694. }
  51695. return mesh;
  51696. };
  51697. // Build Mesh from CSG taking material and transforms into account
  51698. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  51699. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  51700. mesh.material = material;
  51701. mesh.position.copyFrom(this.position);
  51702. mesh.rotation.copyFrom(this.rotation);
  51703. if (this.rotationQuaternion) {
  51704. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  51705. }
  51706. mesh.scaling.copyFrom(this.scaling);
  51707. mesh.computeWorldMatrix(true);
  51708. return mesh;
  51709. };
  51710. return CSG;
  51711. })();
  51712. BABYLON.CSG = CSG;
  51713. })(BABYLON || (BABYLON = {}));
  51714. var BABYLON;
  51715. (function (BABYLON) {
  51716. var VRDistortionCorrectionPostProcess = (function (_super) {
  51717. __extends(VRDistortionCorrectionPostProcess, _super);
  51718. //ANY
  51719. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  51720. var _this = this;
  51721. _super.call(this, name, "vrDistortionCorrection", [
  51722. 'LensCenter',
  51723. 'Scale',
  51724. 'ScaleIn',
  51725. 'HmdWarpParam'
  51726. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  51727. this._isRightEye = isRightEye;
  51728. this._distortionFactors = vrMetrics.distortionK;
  51729. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  51730. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  51731. this.onSizeChangedObservable.add(function () {
  51732. _this.aspectRatio = _this.width * .5 / _this.height;
  51733. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  51734. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  51735. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  51736. });
  51737. this.onApplyObservable.add(function (effect) {
  51738. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  51739. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  51740. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  51741. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  51742. });
  51743. }
  51744. return VRDistortionCorrectionPostProcess;
  51745. })(BABYLON.PostProcess);
  51746. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  51747. })(BABYLON || (BABYLON = {}));
  51748. // Mainly based on these 2 articles :
  51749. // 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
  51750. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  51751. var BABYLON;
  51752. (function (BABYLON) {
  51753. (function (JoystickAxis) {
  51754. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  51755. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  51756. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  51757. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  51758. var JoystickAxis = BABYLON.JoystickAxis;
  51759. var VirtualJoystick = (function () {
  51760. function VirtualJoystick(leftJoystick) {
  51761. var _this = this;
  51762. if (leftJoystick) {
  51763. this._leftJoystick = true;
  51764. }
  51765. else {
  51766. this._leftJoystick = false;
  51767. }
  51768. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  51769. VirtualJoystick._globalJoystickIndex++;
  51770. // By default left & right arrow keys are moving the X
  51771. // and up & down keys are moving the Y
  51772. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  51773. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  51774. this.reverseLeftRight = false;
  51775. this.reverseUpDown = false;
  51776. // collections of pointers
  51777. this._touches = new BABYLON.StringDictionary();
  51778. this.deltaPosition = BABYLON.Vector3.Zero();
  51779. this._joystickSensibility = 25;
  51780. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  51781. this._rotationSpeed = 25;
  51782. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  51783. this._rotateOnAxisRelativeToMesh = false;
  51784. this._onResize = function (evt) {
  51785. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  51786. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  51787. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  51788. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  51789. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  51790. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  51791. };
  51792. // injecting a canvas element on top of the canvas 3D game
  51793. if (!VirtualJoystick.vjCanvas) {
  51794. window.addEventListener("resize", this._onResize, false);
  51795. VirtualJoystick.vjCanvas = document.createElement("canvas");
  51796. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  51797. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  51798. VirtualJoystick.vjCanvas.width = window.innerWidth;
  51799. VirtualJoystick.vjCanvas.height = window.innerHeight;
  51800. VirtualJoystick.vjCanvas.style.width = "100%";
  51801. VirtualJoystick.vjCanvas.style.height = "100%";
  51802. VirtualJoystick.vjCanvas.style.position = "absolute";
  51803. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  51804. VirtualJoystick.vjCanvas.style.top = "0px";
  51805. VirtualJoystick.vjCanvas.style.left = "0px";
  51806. VirtualJoystick.vjCanvas.style.zIndex = "5";
  51807. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  51808. // Support for jQuery PEP polyfill
  51809. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  51810. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  51811. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  51812. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  51813. document.body.appendChild(VirtualJoystick.vjCanvas);
  51814. }
  51815. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  51816. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  51817. this.pressed = false;
  51818. // default joystick color
  51819. this._joystickColor = "cyan";
  51820. this._joystickPointerID = -1;
  51821. // current joystick position
  51822. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  51823. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  51824. // origin joystick position
  51825. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  51826. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  51827. this._onPointerDownHandlerRef = function (evt) {
  51828. _this._onPointerDown(evt);
  51829. };
  51830. this._onPointerMoveHandlerRef = function (evt) {
  51831. _this._onPointerMove(evt);
  51832. };
  51833. this._onPointerOutHandlerRef = function (evt) {
  51834. _this._onPointerUp(evt);
  51835. };
  51836. this._onPointerUpHandlerRef = function (evt) {
  51837. _this._onPointerUp(evt);
  51838. };
  51839. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  51840. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  51841. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  51842. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  51843. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  51844. evt.preventDefault(); // Disables system menu
  51845. }, false);
  51846. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  51847. }
  51848. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  51849. this._joystickSensibility = newJoystickSensibility;
  51850. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  51851. };
  51852. VirtualJoystick.prototype._onPointerDown = function (e) {
  51853. var positionOnScreenCondition;
  51854. e.preventDefault();
  51855. if (this._leftJoystick === true) {
  51856. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  51857. }
  51858. else {
  51859. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  51860. }
  51861. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  51862. // First contact will be dedicated to the virtual joystick
  51863. this._joystickPointerID = e.pointerId;
  51864. this._joystickPointerStartPos.x = e.clientX;
  51865. this._joystickPointerStartPos.y = e.clientY;
  51866. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  51867. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  51868. this._deltaJoystickVector.x = 0;
  51869. this._deltaJoystickVector.y = 0;
  51870. this.pressed = true;
  51871. this._touches.add(e.pointerId.toString(), e);
  51872. }
  51873. else {
  51874. // You can only trigger the action buttons with a joystick declared
  51875. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  51876. this._action();
  51877. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  51878. }
  51879. }
  51880. };
  51881. VirtualJoystick.prototype._onPointerMove = function (e) {
  51882. // If the current pointer is the one associated to the joystick (first touch contact)
  51883. if (this._joystickPointerID == e.pointerId) {
  51884. this._joystickPointerPos.x = e.clientX;
  51885. this._joystickPointerPos.y = e.clientY;
  51886. this._deltaJoystickVector = this._joystickPointerPos.clone();
  51887. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  51888. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  51889. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  51890. switch (this._axisTargetedByLeftAndRight) {
  51891. case JoystickAxis.X:
  51892. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  51893. break;
  51894. case JoystickAxis.Y:
  51895. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  51896. break;
  51897. case JoystickAxis.Z:
  51898. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  51899. break;
  51900. }
  51901. var directionUpDown = this.reverseUpDown ? 1 : -1;
  51902. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  51903. switch (this._axisTargetedByUpAndDown) {
  51904. case JoystickAxis.X:
  51905. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  51906. break;
  51907. case JoystickAxis.Y:
  51908. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  51909. break;
  51910. case JoystickAxis.Z:
  51911. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  51912. break;
  51913. }
  51914. }
  51915. else {
  51916. var data = this._touches.get(e.pointerId.toString());
  51917. if (data) {
  51918. data.x = e.clientX;
  51919. data.y = e.clientY;
  51920. }
  51921. }
  51922. };
  51923. VirtualJoystick.prototype._onPointerUp = function (e) {
  51924. if (this._joystickPointerID == e.pointerId) {
  51925. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  51926. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  51927. this._joystickPointerID = -1;
  51928. this.pressed = false;
  51929. }
  51930. else {
  51931. var touch = this._touches.get(e.pointerId.toString());
  51932. if (touch) {
  51933. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  51934. }
  51935. }
  51936. this._deltaJoystickVector.x = 0;
  51937. this._deltaJoystickVector.y = 0;
  51938. this._touches.remove(e.pointerId.toString());
  51939. };
  51940. /**
  51941. * Change the color of the virtual joystick
  51942. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  51943. */
  51944. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  51945. this._joystickColor = newColor;
  51946. };
  51947. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  51948. this._action = action;
  51949. };
  51950. // Define which axis you'd like to control for left & right
  51951. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  51952. switch (axis) {
  51953. case JoystickAxis.X:
  51954. case JoystickAxis.Y:
  51955. case JoystickAxis.Z:
  51956. this._axisTargetedByLeftAndRight = axis;
  51957. break;
  51958. default:
  51959. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  51960. break;
  51961. }
  51962. };
  51963. // Define which axis you'd like to control for up & down
  51964. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  51965. switch (axis) {
  51966. case JoystickAxis.X:
  51967. case JoystickAxis.Y:
  51968. case JoystickAxis.Z:
  51969. this._axisTargetedByUpAndDown = axis;
  51970. break;
  51971. default:
  51972. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  51973. break;
  51974. }
  51975. };
  51976. VirtualJoystick.prototype._clearCanvas = function () {
  51977. if (this._leftJoystick) {
  51978. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  51979. }
  51980. else {
  51981. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  51982. }
  51983. };
  51984. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  51985. var _this = this;
  51986. if (this.pressed) {
  51987. this._touches.forEach(function (touch) {
  51988. if (touch.pointerId === _this._joystickPointerID) {
  51989. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  51990. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  51991. VirtualJoystick.vjCanvasContext.beginPath();
  51992. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  51993. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  51994. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  51995. VirtualJoystick.vjCanvasContext.stroke();
  51996. VirtualJoystick.vjCanvasContext.closePath();
  51997. VirtualJoystick.vjCanvasContext.beginPath();
  51998. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  51999. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  52000. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  52001. VirtualJoystick.vjCanvasContext.stroke();
  52002. VirtualJoystick.vjCanvasContext.closePath();
  52003. VirtualJoystick.vjCanvasContext.beginPath();
  52004. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  52005. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  52006. VirtualJoystick.vjCanvasContext.stroke();
  52007. VirtualJoystick.vjCanvasContext.closePath();
  52008. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  52009. }
  52010. else {
  52011. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  52012. VirtualJoystick.vjCanvasContext.beginPath();
  52013. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  52014. VirtualJoystick.vjCanvasContext.beginPath();
  52015. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  52016. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  52017. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  52018. VirtualJoystick.vjCanvasContext.stroke();
  52019. VirtualJoystick.vjCanvasContext.closePath();
  52020. touch.prevX = touch.x;
  52021. touch.prevY = touch.y;
  52022. }
  52023. ;
  52024. });
  52025. }
  52026. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  52027. };
  52028. VirtualJoystick.prototype.releaseCanvas = function () {
  52029. if (VirtualJoystick.vjCanvas) {
  52030. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  52031. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  52032. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  52033. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  52034. window.removeEventListener("resize", this._onResize);
  52035. document.body.removeChild(VirtualJoystick.vjCanvas);
  52036. VirtualJoystick.vjCanvas = null;
  52037. }
  52038. };
  52039. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  52040. VirtualJoystick._globalJoystickIndex = 0;
  52041. return VirtualJoystick;
  52042. })();
  52043. BABYLON.VirtualJoystick = VirtualJoystick;
  52044. })(BABYLON || (BABYLON = {}));
  52045. var BABYLON;
  52046. (function (BABYLON) {
  52047. // We're mainly based on the logic defined into the FreeCamera code
  52048. var VirtualJoysticksCamera = (function (_super) {
  52049. __extends(VirtualJoysticksCamera, _super);
  52050. function VirtualJoysticksCamera(name, position, scene) {
  52051. _super.call(this, name, position, scene);
  52052. this.inputs.addVirtualJoystick();
  52053. }
  52054. return VirtualJoysticksCamera;
  52055. })(BABYLON.FreeCamera);
  52056. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  52057. })(BABYLON || (BABYLON = {}));
  52058. var BABYLON;
  52059. (function (BABYLON) {
  52060. var FreeCameraVirtualJoystickInput = (function () {
  52061. function FreeCameraVirtualJoystickInput() {
  52062. }
  52063. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  52064. return this._leftjoystick;
  52065. };
  52066. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  52067. return this._rightjoystick;
  52068. };
  52069. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  52070. if (this._leftjoystick) {
  52071. var camera = this.camera;
  52072. var speed = camera._computeLocalCameraSpeed() * 50;
  52073. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  52074. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  52075. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  52076. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  52077. if (!this._leftjoystick.pressed) {
  52078. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  52079. }
  52080. if (!this._rightjoystick.pressed) {
  52081. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  52082. }
  52083. }
  52084. };
  52085. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  52086. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  52087. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  52088. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  52089. this._leftjoystick.setJoystickSensibility(0.15);
  52090. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  52091. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  52092. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  52093. this._rightjoystick.reverseUpDown = true;
  52094. this._rightjoystick.setJoystickSensibility(0.05);
  52095. this._rightjoystick.setJoystickColor("yellow");
  52096. };
  52097. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  52098. this._leftjoystick.releaseCanvas();
  52099. this._rightjoystick.releaseCanvas();
  52100. };
  52101. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  52102. return "FreeCameraVirtualJoystickInput";
  52103. };
  52104. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  52105. return "virtualJoystick";
  52106. };
  52107. return FreeCameraVirtualJoystickInput;
  52108. })();
  52109. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  52110. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  52111. })(BABYLON || (BABYLON = {}));
  52112. var BABYLON;
  52113. (function (BABYLON) {
  52114. var AnaglyphPostProcess = (function (_super) {
  52115. __extends(AnaglyphPostProcess, _super);
  52116. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  52117. var _this = this;
  52118. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  52119. this._passedProcess = rigCameras[0]._rigPostProcess;
  52120. this.onApplyObservable.add(function (effect) {
  52121. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  52122. });
  52123. }
  52124. return AnaglyphPostProcess;
  52125. })(BABYLON.PostProcess);
  52126. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  52127. })(BABYLON || (BABYLON = {}));
  52128. var BABYLON;
  52129. (function (BABYLON) {
  52130. var OutlineRenderer = (function () {
  52131. function OutlineRenderer(scene) {
  52132. this._scene = scene;
  52133. }
  52134. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  52135. var _this = this;
  52136. if (useOverlay === void 0) { useOverlay = false; }
  52137. var scene = this._scene;
  52138. var engine = this._scene.getEngine();
  52139. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  52140. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  52141. return;
  52142. }
  52143. var mesh = subMesh.getRenderingMesh();
  52144. var material = subMesh.getMaterial();
  52145. engine.enableEffect(this._effect);
  52146. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  52147. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  52148. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  52149. // Bones
  52150. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52151. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  52152. }
  52153. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  52154. // Alpha test
  52155. if (material && material.needAlphaTesting()) {
  52156. var alphaTexture = material.getAlphaTestTexture();
  52157. this._effect.setTexture("diffuseSampler", alphaTexture);
  52158. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  52159. }
  52160. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  52161. };
  52162. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  52163. var defines = [];
  52164. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  52165. var mesh = subMesh.getMesh();
  52166. var material = subMesh.getMaterial();
  52167. // Alpha test
  52168. if (material && material.needAlphaTesting()) {
  52169. defines.push("#define ALPHATEST");
  52170. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52171. attribs.push(BABYLON.VertexBuffer.UVKind);
  52172. defines.push("#define UV1");
  52173. }
  52174. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52175. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52176. defines.push("#define UV2");
  52177. }
  52178. }
  52179. // Bones
  52180. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52181. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52182. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52183. if (mesh.numBoneInfluencers > 4) {
  52184. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52185. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52186. }
  52187. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52188. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52189. }
  52190. else {
  52191. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52192. }
  52193. // Instances
  52194. if (useInstances) {
  52195. defines.push("#define INSTANCES");
  52196. attribs.push("world0");
  52197. attribs.push("world1");
  52198. attribs.push("world2");
  52199. attribs.push("world3");
  52200. }
  52201. // Get correct effect
  52202. var join = defines.join("\n");
  52203. if (this._cachedDefines !== join) {
  52204. this._cachedDefines = join;
  52205. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  52206. }
  52207. return this._effect.isReady();
  52208. };
  52209. return OutlineRenderer;
  52210. })();
  52211. BABYLON.OutlineRenderer = OutlineRenderer;
  52212. })(BABYLON || (BABYLON = {}));
  52213. var BABYLON;
  52214. (function (BABYLON) {
  52215. var MeshAssetTask = (function () {
  52216. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  52217. this.name = name;
  52218. this.meshesNames = meshesNames;
  52219. this.rootUrl = rootUrl;
  52220. this.sceneFilename = sceneFilename;
  52221. this.isCompleted = false;
  52222. }
  52223. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  52224. var _this = this;
  52225. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  52226. _this.loadedMeshes = meshes;
  52227. _this.loadedParticleSystems = particleSystems;
  52228. _this.loadedSkeletons = skeletons;
  52229. _this.isCompleted = true;
  52230. if (_this.onSuccess) {
  52231. _this.onSuccess(_this);
  52232. }
  52233. onSuccess();
  52234. }, null, function () {
  52235. if (_this.onError) {
  52236. _this.onError(_this);
  52237. }
  52238. onError();
  52239. });
  52240. };
  52241. return MeshAssetTask;
  52242. })();
  52243. BABYLON.MeshAssetTask = MeshAssetTask;
  52244. var TextFileAssetTask = (function () {
  52245. function TextFileAssetTask(name, url) {
  52246. this.name = name;
  52247. this.url = url;
  52248. this.isCompleted = false;
  52249. }
  52250. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  52251. var _this = this;
  52252. BABYLON.Tools.LoadFile(this.url, function (data) {
  52253. _this.text = data;
  52254. _this.isCompleted = true;
  52255. if (_this.onSuccess) {
  52256. _this.onSuccess(_this);
  52257. }
  52258. onSuccess();
  52259. }, null, scene.database, false, function () {
  52260. if (_this.onError) {
  52261. _this.onError(_this);
  52262. }
  52263. onError();
  52264. });
  52265. };
  52266. return TextFileAssetTask;
  52267. })();
  52268. BABYLON.TextFileAssetTask = TextFileAssetTask;
  52269. var BinaryFileAssetTask = (function () {
  52270. function BinaryFileAssetTask(name, url) {
  52271. this.name = name;
  52272. this.url = url;
  52273. this.isCompleted = false;
  52274. }
  52275. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  52276. var _this = this;
  52277. BABYLON.Tools.LoadFile(this.url, function (data) {
  52278. _this.data = data;
  52279. _this.isCompleted = true;
  52280. if (_this.onSuccess) {
  52281. _this.onSuccess(_this);
  52282. }
  52283. onSuccess();
  52284. }, null, scene.database, true, function () {
  52285. if (_this.onError) {
  52286. _this.onError(_this);
  52287. }
  52288. onError();
  52289. });
  52290. };
  52291. return BinaryFileAssetTask;
  52292. })();
  52293. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  52294. var ImageAssetTask = (function () {
  52295. function ImageAssetTask(name, url) {
  52296. this.name = name;
  52297. this.url = url;
  52298. this.isCompleted = false;
  52299. }
  52300. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  52301. var _this = this;
  52302. var img = new Image();
  52303. BABYLON.Tools.SetCorsBehavior(this.url, img);
  52304. img.onload = function () {
  52305. _this.image = img;
  52306. _this.isCompleted = true;
  52307. if (_this.onSuccess) {
  52308. _this.onSuccess(_this);
  52309. }
  52310. onSuccess();
  52311. };
  52312. img.onerror = function () {
  52313. if (_this.onError) {
  52314. _this.onError(_this);
  52315. }
  52316. onError();
  52317. };
  52318. img.src = this.url;
  52319. };
  52320. return ImageAssetTask;
  52321. })();
  52322. BABYLON.ImageAssetTask = ImageAssetTask;
  52323. var TextureAssetTask = (function () {
  52324. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  52325. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52326. this.name = name;
  52327. this.url = url;
  52328. this.noMipmap = noMipmap;
  52329. this.invertY = invertY;
  52330. this.samplingMode = samplingMode;
  52331. this.isCompleted = false;
  52332. }
  52333. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  52334. var _this = this;
  52335. var onload = function () {
  52336. _this.isCompleted = true;
  52337. if (_this.onSuccess) {
  52338. _this.onSuccess(_this);
  52339. }
  52340. onSuccess();
  52341. };
  52342. var onerror = function () {
  52343. if (_this.onError) {
  52344. _this.onError(_this);
  52345. }
  52346. onError();
  52347. };
  52348. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  52349. };
  52350. return TextureAssetTask;
  52351. })();
  52352. BABYLON.TextureAssetTask = TextureAssetTask;
  52353. var AssetsManager = (function () {
  52354. function AssetsManager(scene) {
  52355. this._tasks = new Array();
  52356. this._waitingTasksCount = 0;
  52357. this.useDefaultLoadingScreen = true;
  52358. this._scene = scene;
  52359. }
  52360. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  52361. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  52362. this._tasks.push(task);
  52363. return task;
  52364. };
  52365. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  52366. var task = new TextFileAssetTask(taskName, url);
  52367. this._tasks.push(task);
  52368. return task;
  52369. };
  52370. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  52371. var task = new BinaryFileAssetTask(taskName, url);
  52372. this._tasks.push(task);
  52373. return task;
  52374. };
  52375. AssetsManager.prototype.addImageTask = function (taskName, url) {
  52376. var task = new ImageAssetTask(taskName, url);
  52377. this._tasks.push(task);
  52378. return task;
  52379. };
  52380. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  52381. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52382. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  52383. this._tasks.push(task);
  52384. return task;
  52385. };
  52386. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  52387. this._waitingTasksCount--;
  52388. if (this._waitingTasksCount === 0) {
  52389. if (this.onFinish) {
  52390. this.onFinish(this._tasks);
  52391. }
  52392. this._scene.getEngine().hideLoadingUI();
  52393. }
  52394. };
  52395. AssetsManager.prototype._runTask = function (task) {
  52396. var _this = this;
  52397. task.run(this._scene, function () {
  52398. if (_this.onTaskSuccess) {
  52399. _this.onTaskSuccess(task);
  52400. }
  52401. _this._decreaseWaitingTasksCount();
  52402. }, function () {
  52403. if (_this.onTaskError) {
  52404. _this.onTaskError(task);
  52405. }
  52406. _this._decreaseWaitingTasksCount();
  52407. });
  52408. };
  52409. AssetsManager.prototype.reset = function () {
  52410. this._tasks = new Array();
  52411. return this;
  52412. };
  52413. AssetsManager.prototype.load = function () {
  52414. this._waitingTasksCount = this._tasks.length;
  52415. if (this._waitingTasksCount === 0) {
  52416. if (this.onFinish) {
  52417. this.onFinish(this._tasks);
  52418. }
  52419. return this;
  52420. }
  52421. if (this.useDefaultLoadingScreen) {
  52422. this._scene.getEngine().displayLoadingUI();
  52423. }
  52424. for (var index = 0; index < this._tasks.length; index++) {
  52425. var task = this._tasks[index];
  52426. this._runTask(task);
  52427. }
  52428. return this;
  52429. };
  52430. return AssetsManager;
  52431. })();
  52432. BABYLON.AssetsManager = AssetsManager;
  52433. })(BABYLON || (BABYLON = {}));
  52434. var BABYLON;
  52435. (function (BABYLON) {
  52436. var VRCameraMetrics = (function () {
  52437. function VRCameraMetrics() {
  52438. this.compensateDistortion = true;
  52439. }
  52440. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  52441. get: function () {
  52442. return this.hResolution / (2 * this.vResolution);
  52443. },
  52444. enumerable: true,
  52445. configurable: true
  52446. });
  52447. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  52448. get: function () {
  52449. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  52450. },
  52451. enumerable: true,
  52452. configurable: true
  52453. });
  52454. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  52455. get: function () {
  52456. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  52457. var h = (4 * meters) / this.hScreenSize;
  52458. return BABYLON.Matrix.Translation(h, 0, 0);
  52459. },
  52460. enumerable: true,
  52461. configurable: true
  52462. });
  52463. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  52464. get: function () {
  52465. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  52466. var h = (4 * meters) / this.hScreenSize;
  52467. return BABYLON.Matrix.Translation(-h, 0, 0);
  52468. },
  52469. enumerable: true,
  52470. configurable: true
  52471. });
  52472. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  52473. get: function () {
  52474. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  52475. },
  52476. enumerable: true,
  52477. configurable: true
  52478. });
  52479. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  52480. get: function () {
  52481. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  52482. },
  52483. enumerable: true,
  52484. configurable: true
  52485. });
  52486. VRCameraMetrics.GetDefault = function () {
  52487. var result = new VRCameraMetrics();
  52488. result.hResolution = 1280;
  52489. result.vResolution = 800;
  52490. result.hScreenSize = 0.149759993;
  52491. result.vScreenSize = 0.0935999975;
  52492. result.vScreenCenter = 0.0467999987,
  52493. result.eyeToScreenDistance = 0.0410000011;
  52494. result.lensSeparationDistance = 0.0635000020;
  52495. result.interpupillaryDistance = 0.0640000030;
  52496. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  52497. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  52498. result.postProcessScaleFactor = 1.714605507808412;
  52499. result.lensCenterOffset = 0.151976421;
  52500. return result;
  52501. };
  52502. return VRCameraMetrics;
  52503. })();
  52504. BABYLON.VRCameraMetrics = VRCameraMetrics;
  52505. })(BABYLON || (BABYLON = {}));
  52506. var BABYLON;
  52507. (function (BABYLON) {
  52508. var WebVRFreeCamera = (function (_super) {
  52509. __extends(WebVRFreeCamera, _super);
  52510. function WebVRFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  52511. if (compensateDistortion === void 0) { compensateDistortion = true; }
  52512. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  52513. _super.call(this, name, position, scene);
  52514. this._hmdDevice = null;
  52515. this._sensorDevice = null;
  52516. this._cacheState = null;
  52517. this._vrEnabled = false;
  52518. vrCameraMetrics.compensateDistortion = compensateDistortion;
  52519. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  52520. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  52521. this.rotationQuaternion = new BABYLON.Quaternion();
  52522. this._quaternionCache = new BABYLON.Quaternion();
  52523. }
  52524. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  52525. var size = devices.length;
  52526. var i = 0;
  52527. // Reset devices.
  52528. this._sensorDevice = null;
  52529. this._hmdDevice = null;
  52530. // Search for a HmdDevice.
  52531. while (i < size && this._hmdDevice === null) {
  52532. if (devices[i] instanceof HMDVRDevice) {
  52533. this._hmdDevice = devices[i];
  52534. }
  52535. i++;
  52536. }
  52537. i = 0;
  52538. while (i < size && this._sensorDevice === null) {
  52539. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  52540. this._sensorDevice = devices[i];
  52541. }
  52542. i++;
  52543. }
  52544. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  52545. };
  52546. WebVRFreeCamera.prototype._checkInputs = function () {
  52547. if (this._vrEnabled) {
  52548. this._cacheState = this._sensorDevice.getState();
  52549. this.rotationQuaternion.copyFrom(this._cacheState.orientation);
  52550. //Flip in XY plane
  52551. this.rotationQuaternion.z *= -1;
  52552. this.rotationQuaternion.w *= -1;
  52553. if (this._initialQuaternion) {
  52554. this._quaternionCache.copyFrom(this.rotationQuaternion);
  52555. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  52556. }
  52557. }
  52558. _super.prototype._checkInputs.call(this);
  52559. };
  52560. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  52561. _super.prototype.attachControl.call(this, element, noPreventDefault);
  52562. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  52563. if (navigator.getVRDevices) {
  52564. navigator.getVRDevices().then(this._getWebVRDevices);
  52565. }
  52566. else if (navigator.mozGetVRDevices) {
  52567. navigator.mozGetVRDevices(this._getWebVRDevices);
  52568. }
  52569. };
  52570. WebVRFreeCamera.prototype.detachControl = function (element) {
  52571. _super.prototype.detachControl.call(this, element);
  52572. this._vrEnabled = false;
  52573. };
  52574. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  52575. if (!this._hmdDevice)
  52576. return;
  52577. this.getEngine().switchFullscreen(requestPointerlock, { vrDisplay: this._hmdDevice });
  52578. };
  52579. WebVRFreeCamera.prototype.getTypeName = function () {
  52580. return "WebVRFreeCamera";
  52581. };
  52582. WebVRFreeCamera.prototype.resetToCurrentRotation = function (axis) {
  52583. var _this = this;
  52584. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  52585. //can only work if this camera has a rotation quaternion already.
  52586. if (!this.rotationQuaternion)
  52587. return;
  52588. if (!this._initialQuaternion) {
  52589. this._initialQuaternion = new BABYLON.Quaternion();
  52590. }
  52591. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  52592. ['x', 'y', 'z'].forEach(function (axisName) {
  52593. if (!axis[axisName]) {
  52594. _this._initialQuaternion[axisName] = 0;
  52595. }
  52596. else {
  52597. _this._initialQuaternion[axisName] *= -1;
  52598. }
  52599. });
  52600. this._initialQuaternion.normalize();
  52601. };
  52602. return WebVRFreeCamera;
  52603. })(BABYLON.FreeCamera);
  52604. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  52605. })(BABYLON || (BABYLON = {}));
  52606. var BABYLON;
  52607. (function (BABYLON) {
  52608. // Standard optimizations
  52609. var SceneOptimization = (function () {
  52610. function SceneOptimization(priority) {
  52611. if (priority === void 0) { priority = 0; }
  52612. this.priority = priority;
  52613. this.apply = function (scene) {
  52614. return true; // Return true if everything that can be done was applied
  52615. };
  52616. }
  52617. return SceneOptimization;
  52618. })();
  52619. BABYLON.SceneOptimization = SceneOptimization;
  52620. var TextureOptimization = (function (_super) {
  52621. __extends(TextureOptimization, _super);
  52622. function TextureOptimization(priority, maximumSize) {
  52623. var _this = this;
  52624. if (priority === void 0) { priority = 0; }
  52625. if (maximumSize === void 0) { maximumSize = 1024; }
  52626. _super.call(this, priority);
  52627. this.priority = priority;
  52628. this.maximumSize = maximumSize;
  52629. this.apply = function (scene) {
  52630. var allDone = true;
  52631. for (var index = 0; index < scene.textures.length; index++) {
  52632. var texture = scene.textures[index];
  52633. if (!texture.canRescale) {
  52634. continue;
  52635. }
  52636. var currentSize = texture.getSize();
  52637. var maxDimension = Math.max(currentSize.width, currentSize.height);
  52638. if (maxDimension > _this.maximumSize) {
  52639. texture.scale(0.5);
  52640. allDone = false;
  52641. }
  52642. }
  52643. return allDone;
  52644. };
  52645. }
  52646. return TextureOptimization;
  52647. })(SceneOptimization);
  52648. BABYLON.TextureOptimization = TextureOptimization;
  52649. var HardwareScalingOptimization = (function (_super) {
  52650. __extends(HardwareScalingOptimization, _super);
  52651. function HardwareScalingOptimization(priority, maximumScale) {
  52652. var _this = this;
  52653. if (priority === void 0) { priority = 0; }
  52654. if (maximumScale === void 0) { maximumScale = 2; }
  52655. _super.call(this, priority);
  52656. this.priority = priority;
  52657. this.maximumScale = maximumScale;
  52658. this._currentScale = 1;
  52659. this.apply = function (scene) {
  52660. _this._currentScale++;
  52661. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  52662. return _this._currentScale >= _this.maximumScale;
  52663. };
  52664. }
  52665. return HardwareScalingOptimization;
  52666. })(SceneOptimization);
  52667. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  52668. var ShadowsOptimization = (function (_super) {
  52669. __extends(ShadowsOptimization, _super);
  52670. function ShadowsOptimization() {
  52671. _super.apply(this, arguments);
  52672. this.apply = function (scene) {
  52673. scene.shadowsEnabled = false;
  52674. return true;
  52675. };
  52676. }
  52677. return ShadowsOptimization;
  52678. })(SceneOptimization);
  52679. BABYLON.ShadowsOptimization = ShadowsOptimization;
  52680. var PostProcessesOptimization = (function (_super) {
  52681. __extends(PostProcessesOptimization, _super);
  52682. function PostProcessesOptimization() {
  52683. _super.apply(this, arguments);
  52684. this.apply = function (scene) {
  52685. scene.postProcessesEnabled = false;
  52686. return true;
  52687. };
  52688. }
  52689. return PostProcessesOptimization;
  52690. })(SceneOptimization);
  52691. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  52692. var LensFlaresOptimization = (function (_super) {
  52693. __extends(LensFlaresOptimization, _super);
  52694. function LensFlaresOptimization() {
  52695. _super.apply(this, arguments);
  52696. this.apply = function (scene) {
  52697. scene.lensFlaresEnabled = false;
  52698. return true;
  52699. };
  52700. }
  52701. return LensFlaresOptimization;
  52702. })(SceneOptimization);
  52703. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  52704. var ParticlesOptimization = (function (_super) {
  52705. __extends(ParticlesOptimization, _super);
  52706. function ParticlesOptimization() {
  52707. _super.apply(this, arguments);
  52708. this.apply = function (scene) {
  52709. scene.particlesEnabled = false;
  52710. return true;
  52711. };
  52712. }
  52713. return ParticlesOptimization;
  52714. })(SceneOptimization);
  52715. BABYLON.ParticlesOptimization = ParticlesOptimization;
  52716. var RenderTargetsOptimization = (function (_super) {
  52717. __extends(RenderTargetsOptimization, _super);
  52718. function RenderTargetsOptimization() {
  52719. _super.apply(this, arguments);
  52720. this.apply = function (scene) {
  52721. scene.renderTargetsEnabled = false;
  52722. return true;
  52723. };
  52724. }
  52725. return RenderTargetsOptimization;
  52726. })(SceneOptimization);
  52727. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  52728. var MergeMeshesOptimization = (function (_super) {
  52729. __extends(MergeMeshesOptimization, _super);
  52730. function MergeMeshesOptimization() {
  52731. var _this = this;
  52732. _super.apply(this, arguments);
  52733. this._canBeMerged = function (abstractMesh) {
  52734. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  52735. return false;
  52736. }
  52737. var mesh = abstractMesh;
  52738. if (!mesh.isVisible || !mesh.isEnabled()) {
  52739. return false;
  52740. }
  52741. if (mesh.instances.length > 0) {
  52742. return false;
  52743. }
  52744. if (mesh.skeleton || mesh.hasLODLevels) {
  52745. return false;
  52746. }
  52747. if (mesh.parent) {
  52748. return false;
  52749. }
  52750. return true;
  52751. };
  52752. this.apply = function (scene, updateSelectionTree) {
  52753. var globalPool = scene.meshes.slice(0);
  52754. var globalLength = globalPool.length;
  52755. for (var index = 0; index < globalLength; index++) {
  52756. var currentPool = new Array();
  52757. var current = globalPool[index];
  52758. // Checks
  52759. if (!_this._canBeMerged(current)) {
  52760. continue;
  52761. }
  52762. currentPool.push(current);
  52763. // Find compatible meshes
  52764. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  52765. var otherMesh = globalPool[subIndex];
  52766. if (!_this._canBeMerged(otherMesh)) {
  52767. continue;
  52768. }
  52769. if (otherMesh.material !== current.material) {
  52770. continue;
  52771. }
  52772. if (otherMesh.checkCollisions !== current.checkCollisions) {
  52773. continue;
  52774. }
  52775. currentPool.push(otherMesh);
  52776. globalLength--;
  52777. globalPool.splice(subIndex, 1);
  52778. subIndex--;
  52779. }
  52780. if (currentPool.length < 2) {
  52781. continue;
  52782. }
  52783. // Merge meshes
  52784. BABYLON.Mesh.MergeMeshes(currentPool);
  52785. }
  52786. if (updateSelectionTree != undefined) {
  52787. if (updateSelectionTree) {
  52788. scene.createOrUpdateSelectionOctree();
  52789. }
  52790. }
  52791. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  52792. scene.createOrUpdateSelectionOctree();
  52793. }
  52794. return true;
  52795. };
  52796. }
  52797. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  52798. get: function () {
  52799. return MergeMeshesOptimization._UpdateSelectionTree;
  52800. },
  52801. set: function (value) {
  52802. MergeMeshesOptimization._UpdateSelectionTree = value;
  52803. },
  52804. enumerable: true,
  52805. configurable: true
  52806. });
  52807. MergeMeshesOptimization._UpdateSelectionTree = false;
  52808. return MergeMeshesOptimization;
  52809. })(SceneOptimization);
  52810. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  52811. // Options
  52812. var SceneOptimizerOptions = (function () {
  52813. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  52814. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  52815. if (trackerDuration === void 0) { trackerDuration = 2000; }
  52816. this.targetFrameRate = targetFrameRate;
  52817. this.trackerDuration = trackerDuration;
  52818. this.optimizations = new Array();
  52819. }
  52820. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  52821. var result = new SceneOptimizerOptions(targetFrameRate);
  52822. var priority = 0;
  52823. result.optimizations.push(new MergeMeshesOptimization(priority));
  52824. result.optimizations.push(new ShadowsOptimization(priority));
  52825. result.optimizations.push(new LensFlaresOptimization(priority));
  52826. // Next priority
  52827. priority++;
  52828. result.optimizations.push(new PostProcessesOptimization(priority));
  52829. result.optimizations.push(new ParticlesOptimization(priority));
  52830. // Next priority
  52831. priority++;
  52832. result.optimizations.push(new TextureOptimization(priority, 1024));
  52833. return result;
  52834. };
  52835. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  52836. var result = new SceneOptimizerOptions(targetFrameRate);
  52837. var priority = 0;
  52838. result.optimizations.push(new MergeMeshesOptimization(priority));
  52839. result.optimizations.push(new ShadowsOptimization(priority));
  52840. result.optimizations.push(new LensFlaresOptimization(priority));
  52841. // Next priority
  52842. priority++;
  52843. result.optimizations.push(new PostProcessesOptimization(priority));
  52844. result.optimizations.push(new ParticlesOptimization(priority));
  52845. // Next priority
  52846. priority++;
  52847. result.optimizations.push(new TextureOptimization(priority, 512));
  52848. // Next priority
  52849. priority++;
  52850. result.optimizations.push(new RenderTargetsOptimization(priority));
  52851. // Next priority
  52852. priority++;
  52853. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  52854. return result;
  52855. };
  52856. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  52857. var result = new SceneOptimizerOptions(targetFrameRate);
  52858. var priority = 0;
  52859. result.optimizations.push(new MergeMeshesOptimization(priority));
  52860. result.optimizations.push(new ShadowsOptimization(priority));
  52861. result.optimizations.push(new LensFlaresOptimization(priority));
  52862. // Next priority
  52863. priority++;
  52864. result.optimizations.push(new PostProcessesOptimization(priority));
  52865. result.optimizations.push(new ParticlesOptimization(priority));
  52866. // Next priority
  52867. priority++;
  52868. result.optimizations.push(new TextureOptimization(priority, 256));
  52869. // Next priority
  52870. priority++;
  52871. result.optimizations.push(new RenderTargetsOptimization(priority));
  52872. // Next priority
  52873. priority++;
  52874. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  52875. return result;
  52876. };
  52877. return SceneOptimizerOptions;
  52878. })();
  52879. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  52880. // Scene optimizer tool
  52881. var SceneOptimizer = (function () {
  52882. function SceneOptimizer() {
  52883. }
  52884. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  52885. // TODO: add an epsilon
  52886. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  52887. if (onSuccess) {
  52888. onSuccess();
  52889. }
  52890. return;
  52891. }
  52892. // Apply current level of optimizations
  52893. var allDone = true;
  52894. var noOptimizationApplied = true;
  52895. for (var index = 0; index < options.optimizations.length; index++) {
  52896. var optimization = options.optimizations[index];
  52897. if (optimization.priority === currentPriorityLevel) {
  52898. noOptimizationApplied = false;
  52899. allDone = allDone && optimization.apply(scene);
  52900. }
  52901. }
  52902. // If no optimization was applied, this is a failure :(
  52903. if (noOptimizationApplied) {
  52904. if (onFailure) {
  52905. onFailure();
  52906. }
  52907. return;
  52908. }
  52909. // If all optimizations were done, move to next level
  52910. if (allDone) {
  52911. currentPriorityLevel++;
  52912. }
  52913. // Let's the system running for a specific amount of time before checking FPS
  52914. scene.executeWhenReady(function () {
  52915. setTimeout(function () {
  52916. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  52917. }, options.trackerDuration);
  52918. });
  52919. };
  52920. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  52921. if (!options) {
  52922. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  52923. }
  52924. // Let's the system running for a specific amount of time before checking FPS
  52925. scene.executeWhenReady(function () {
  52926. setTimeout(function () {
  52927. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  52928. }, options.trackerDuration);
  52929. });
  52930. };
  52931. return SceneOptimizer;
  52932. })();
  52933. BABYLON.SceneOptimizer = SceneOptimizer;
  52934. })(BABYLON || (BABYLON = {}));
  52935. var BABYLON;
  52936. (function (BABYLON) {
  52937. var Internals;
  52938. (function (Internals) {
  52939. var MeshLODLevel = (function () {
  52940. function MeshLODLevel(distance, mesh) {
  52941. this.distance = distance;
  52942. this.mesh = mesh;
  52943. }
  52944. return MeshLODLevel;
  52945. })();
  52946. Internals.MeshLODLevel = MeshLODLevel;
  52947. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  52948. })(BABYLON || (BABYLON = {}));
  52949. var BABYLON;
  52950. (function (BABYLON) {
  52951. var RawTexture = (function (_super) {
  52952. __extends(RawTexture, _super);
  52953. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  52954. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52955. if (invertY === void 0) { invertY = false; }
  52956. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52957. _super.call(this, null, scene, !generateMipMaps, invertY);
  52958. this.format = format;
  52959. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  52960. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52961. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52962. }
  52963. RawTexture.prototype.update = function (data) {
  52964. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  52965. };
  52966. // Statics
  52967. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52968. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52969. if (invertY === void 0) { invertY = false; }
  52970. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52971. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  52972. };
  52973. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52974. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52975. if (invertY === void 0) { invertY = false; }
  52976. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52977. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  52978. };
  52979. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52980. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52981. if (invertY === void 0) { invertY = false; }
  52982. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52983. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  52984. };
  52985. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52986. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52987. if (invertY === void 0) { invertY = false; }
  52988. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52989. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  52990. };
  52991. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52992. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52993. if (invertY === void 0) { invertY = false; }
  52994. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52995. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  52996. };
  52997. return RawTexture;
  52998. })(BABYLON.Texture);
  52999. BABYLON.RawTexture = RawTexture;
  53000. })(BABYLON || (BABYLON = {}));
  53001. var BABYLON;
  53002. (function (BABYLON) {
  53003. var IndexedVector2 = (function (_super) {
  53004. __extends(IndexedVector2, _super);
  53005. function IndexedVector2(original, index) {
  53006. _super.call(this, original.x, original.y);
  53007. this.index = index;
  53008. }
  53009. return IndexedVector2;
  53010. })(BABYLON.Vector2);
  53011. var PolygonPoints = (function () {
  53012. function PolygonPoints() {
  53013. this.elements = new Array();
  53014. }
  53015. PolygonPoints.prototype.add = function (originalPoints) {
  53016. var _this = this;
  53017. var result = new Array();
  53018. originalPoints.forEach(function (point) {
  53019. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  53020. var newPoint = new IndexedVector2(point, _this.elements.length);
  53021. result.push(newPoint);
  53022. _this.elements.push(newPoint);
  53023. }
  53024. });
  53025. return result;
  53026. };
  53027. PolygonPoints.prototype.computeBounds = function () {
  53028. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  53029. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  53030. this.elements.forEach(function (point) {
  53031. // x
  53032. if (point.x < lmin.x) {
  53033. lmin.x = point.x;
  53034. }
  53035. else if (point.x > lmax.x) {
  53036. lmax.x = point.x;
  53037. }
  53038. // y
  53039. if (point.y < lmin.y) {
  53040. lmin.y = point.y;
  53041. }
  53042. else if (point.y > lmax.y) {
  53043. lmax.y = point.y;
  53044. }
  53045. });
  53046. return {
  53047. min: lmin,
  53048. max: lmax,
  53049. width: lmax.x - lmin.x,
  53050. height: lmax.y - lmin.y
  53051. };
  53052. };
  53053. return PolygonPoints;
  53054. })();
  53055. var Polygon = (function () {
  53056. function Polygon() {
  53057. }
  53058. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  53059. return [
  53060. new BABYLON.Vector2(xmin, ymin),
  53061. new BABYLON.Vector2(xmax, ymin),
  53062. new BABYLON.Vector2(xmax, ymax),
  53063. new BABYLON.Vector2(xmin, ymax)
  53064. ];
  53065. };
  53066. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  53067. if (cx === void 0) { cx = 0; }
  53068. if (cy === void 0) { cy = 0; }
  53069. if (numberOfSides === void 0) { numberOfSides = 32; }
  53070. var result = new Array();
  53071. var angle = 0;
  53072. var increment = (Math.PI * 2) / numberOfSides;
  53073. for (var i = 0; i < numberOfSides; i++) {
  53074. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  53075. angle -= increment;
  53076. }
  53077. return result;
  53078. };
  53079. Polygon.Parse = function (input) {
  53080. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  53081. var i, result = [];
  53082. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  53083. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  53084. }
  53085. return result;
  53086. };
  53087. Polygon.StartingAt = function (x, y) {
  53088. return BABYLON.Path2.StartingAt(x, y);
  53089. };
  53090. return Polygon;
  53091. })();
  53092. BABYLON.Polygon = Polygon;
  53093. var PolygonMeshBuilder = (function () {
  53094. function PolygonMeshBuilder(name, contours, scene) {
  53095. this._points = new PolygonPoints();
  53096. this._outlinepoints = new PolygonPoints();
  53097. this._holes = [];
  53098. this._epoints = new Array();
  53099. this._eholes = new Array();
  53100. this._name = name;
  53101. this._scene = scene;
  53102. var points;
  53103. if (contours instanceof BABYLON.Path2) {
  53104. points = contours.getPoints();
  53105. }
  53106. else {
  53107. points = contours;
  53108. }
  53109. this._addToepoint(points);
  53110. this._points.add(points);
  53111. this._outlinepoints.add(points);
  53112. }
  53113. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  53114. for (var _i = 0; _i < points.length; _i++) {
  53115. var p = points[_i];
  53116. this._epoints.push(p.x, p.y);
  53117. }
  53118. };
  53119. PolygonMeshBuilder.prototype.addHole = function (hole) {
  53120. this._points.add(hole);
  53121. var holepoints = new PolygonPoints();
  53122. holepoints.add(hole);
  53123. this._holes.push(holepoints);
  53124. this._eholes.push(this._epoints.length / 2);
  53125. this._addToepoint(hole);
  53126. return this;
  53127. };
  53128. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  53129. var _this = this;
  53130. if (updatable === void 0) { updatable = false; }
  53131. var result = new BABYLON.Mesh(this._name, this._scene);
  53132. var normals = [];
  53133. var positions = [];
  53134. var uvs = [];
  53135. var bounds = this._points.computeBounds();
  53136. this._points.elements.forEach(function (p) {
  53137. normals.push(0, 1.0, 0);
  53138. positions.push(p.x, 0, p.y);
  53139. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  53140. });
  53141. var indices = [];
  53142. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  53143. for (var i = 0; i < res.length; i++) {
  53144. indices.push(res[i]);
  53145. }
  53146. if (depth > 0) {
  53147. var positionscount = (positions.length / 3); //get the current pointcount
  53148. this._points.elements.forEach(function (p) {
  53149. normals.push(0, -1.0, 0);
  53150. positions.push(p.x, -depth, p.y);
  53151. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  53152. });
  53153. var totalCount = indices.length;
  53154. for (var i = 0; i < totalCount; i += 3) {
  53155. var i0 = indices[i + 0];
  53156. var i1 = indices[i + 1];
  53157. var i2 = indices[i + 2];
  53158. indices.push(i2 + positionscount);
  53159. indices.push(i1 + positionscount);
  53160. indices.push(i0 + positionscount);
  53161. }
  53162. //Add the sides
  53163. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  53164. this._holes.forEach(function (hole) {
  53165. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  53166. });
  53167. }
  53168. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  53169. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  53170. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  53171. result.setIndices(indices);
  53172. return result;
  53173. };
  53174. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  53175. var StartIndex = positions.length / 3;
  53176. var ulength = 0;
  53177. for (var i = 0; i < points.elements.length; i++) {
  53178. var p = points.elements[i];
  53179. var p1;
  53180. if ((i + 1) > points.elements.length - 1) {
  53181. p1 = points.elements[0];
  53182. }
  53183. else {
  53184. p1 = points.elements[i + 1];
  53185. }
  53186. positions.push(p.x, 0, p.y);
  53187. positions.push(p.x, -depth, p.y);
  53188. positions.push(p1.x, 0, p1.y);
  53189. positions.push(p1.x, -depth, p1.y);
  53190. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  53191. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  53192. var v3 = v2.subtract(v1);
  53193. var v4 = new BABYLON.Vector3(0, 1, 0);
  53194. var vn = BABYLON.Vector3.Cross(v3, v4);
  53195. vn = vn.normalize();
  53196. uvs.push(ulength / bounds.width, 0);
  53197. uvs.push(ulength / bounds.width, 1);
  53198. ulength += v3.length();
  53199. uvs.push((ulength / bounds.width), 0);
  53200. uvs.push((ulength / bounds.width), 1);
  53201. if (!flip) {
  53202. normals.push(-vn.x, -vn.y, -vn.z);
  53203. normals.push(-vn.x, -vn.y, -vn.z);
  53204. normals.push(-vn.x, -vn.y, -vn.z);
  53205. normals.push(-vn.x, -vn.y, -vn.z);
  53206. indices.push(StartIndex);
  53207. indices.push(StartIndex + 1);
  53208. indices.push(StartIndex + 2);
  53209. indices.push(StartIndex + 1);
  53210. indices.push(StartIndex + 3);
  53211. indices.push(StartIndex + 2);
  53212. }
  53213. else {
  53214. normals.push(vn.x, vn.y, vn.z);
  53215. normals.push(vn.x, vn.y, vn.z);
  53216. normals.push(vn.x, vn.y, vn.z);
  53217. normals.push(vn.x, vn.y, vn.z);
  53218. indices.push(StartIndex);
  53219. indices.push(StartIndex + 2);
  53220. indices.push(StartIndex + 1);
  53221. indices.push(StartIndex + 1);
  53222. indices.push(StartIndex + 2);
  53223. indices.push(StartIndex + 3);
  53224. }
  53225. StartIndex += 4;
  53226. }
  53227. ;
  53228. };
  53229. return PolygonMeshBuilder;
  53230. })();
  53231. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  53232. })(BABYLON || (BABYLON = {}));
  53233. var BABYLON;
  53234. (function (BABYLON) {
  53235. var Octree = (function () {
  53236. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  53237. if (maxDepth === void 0) { maxDepth = 2; }
  53238. this.maxDepth = maxDepth;
  53239. this.dynamicContent = new Array();
  53240. this._maxBlockCapacity = maxBlockCapacity || 64;
  53241. this._selectionContent = new BABYLON.SmartArray(1024);
  53242. this._creationFunc = creationFunc;
  53243. }
  53244. // Methods
  53245. Octree.prototype.update = function (worldMin, worldMax, entries) {
  53246. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  53247. };
  53248. Octree.prototype.addMesh = function (entry) {
  53249. for (var index = 0; index < this.blocks.length; index++) {
  53250. var block = this.blocks[index];
  53251. block.addEntry(entry);
  53252. }
  53253. };
  53254. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  53255. this._selectionContent.reset();
  53256. for (var index = 0; index < this.blocks.length; index++) {
  53257. var block = this.blocks[index];
  53258. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  53259. }
  53260. if (allowDuplicate) {
  53261. this._selectionContent.concat(this.dynamicContent);
  53262. }
  53263. else {
  53264. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  53265. }
  53266. return this._selectionContent;
  53267. };
  53268. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  53269. this._selectionContent.reset();
  53270. for (var index = 0; index < this.blocks.length; index++) {
  53271. var block = this.blocks[index];
  53272. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  53273. }
  53274. if (allowDuplicate) {
  53275. this._selectionContent.concat(this.dynamicContent);
  53276. }
  53277. else {
  53278. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  53279. }
  53280. return this._selectionContent;
  53281. };
  53282. Octree.prototype.intersectsRay = function (ray) {
  53283. this._selectionContent.reset();
  53284. for (var index = 0; index < this.blocks.length; index++) {
  53285. var block = this.blocks[index];
  53286. block.intersectsRay(ray, this._selectionContent);
  53287. }
  53288. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  53289. return this._selectionContent;
  53290. };
  53291. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  53292. target.blocks = new Array();
  53293. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  53294. // Segmenting space
  53295. for (var x = 0; x < 2; x++) {
  53296. for (var y = 0; y < 2; y++) {
  53297. for (var z = 0; z < 2; z++) {
  53298. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  53299. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  53300. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  53301. block.addEntries(entries);
  53302. target.blocks.push(block);
  53303. }
  53304. }
  53305. }
  53306. };
  53307. Octree.CreationFuncForMeshes = function (entry, block) {
  53308. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  53309. block.entries.push(entry);
  53310. }
  53311. };
  53312. Octree.CreationFuncForSubMeshes = function (entry, block) {
  53313. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  53314. block.entries.push(entry);
  53315. }
  53316. };
  53317. return Octree;
  53318. })();
  53319. BABYLON.Octree = Octree;
  53320. })(BABYLON || (BABYLON = {}));
  53321. var BABYLON;
  53322. (function (BABYLON) {
  53323. var OctreeBlock = (function () {
  53324. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  53325. this.entries = new Array();
  53326. this._boundingVectors = new Array();
  53327. this._capacity = capacity;
  53328. this._depth = depth;
  53329. this._maxDepth = maxDepth;
  53330. this._creationFunc = creationFunc;
  53331. this._minPoint = minPoint;
  53332. this._maxPoint = maxPoint;
  53333. this._boundingVectors.push(minPoint.clone());
  53334. this._boundingVectors.push(maxPoint.clone());
  53335. this._boundingVectors.push(minPoint.clone());
  53336. this._boundingVectors[2].x = maxPoint.x;
  53337. this._boundingVectors.push(minPoint.clone());
  53338. this._boundingVectors[3].y = maxPoint.y;
  53339. this._boundingVectors.push(minPoint.clone());
  53340. this._boundingVectors[4].z = maxPoint.z;
  53341. this._boundingVectors.push(maxPoint.clone());
  53342. this._boundingVectors[5].z = minPoint.z;
  53343. this._boundingVectors.push(maxPoint.clone());
  53344. this._boundingVectors[6].x = minPoint.x;
  53345. this._boundingVectors.push(maxPoint.clone());
  53346. this._boundingVectors[7].y = minPoint.y;
  53347. }
  53348. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  53349. // Property
  53350. get: function () {
  53351. return this._capacity;
  53352. },
  53353. enumerable: true,
  53354. configurable: true
  53355. });
  53356. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  53357. get: function () {
  53358. return this._minPoint;
  53359. },
  53360. enumerable: true,
  53361. configurable: true
  53362. });
  53363. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  53364. get: function () {
  53365. return this._maxPoint;
  53366. },
  53367. enumerable: true,
  53368. configurable: true
  53369. });
  53370. // Methods
  53371. OctreeBlock.prototype.addEntry = function (entry) {
  53372. if (this.blocks) {
  53373. for (var index = 0; index < this.blocks.length; index++) {
  53374. var block = this.blocks[index];
  53375. block.addEntry(entry);
  53376. }
  53377. return;
  53378. }
  53379. this._creationFunc(entry, this);
  53380. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  53381. this.createInnerBlocks();
  53382. }
  53383. };
  53384. OctreeBlock.prototype.addEntries = function (entries) {
  53385. for (var index = 0; index < entries.length; index++) {
  53386. var mesh = entries[index];
  53387. this.addEntry(mesh);
  53388. }
  53389. };
  53390. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  53391. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  53392. if (this.blocks) {
  53393. for (var index = 0; index < this.blocks.length; index++) {
  53394. var block = this.blocks[index];
  53395. block.select(frustumPlanes, selection, allowDuplicate);
  53396. }
  53397. return;
  53398. }
  53399. if (allowDuplicate) {
  53400. selection.concat(this.entries);
  53401. }
  53402. else {
  53403. selection.concatWithNoDuplicate(this.entries);
  53404. }
  53405. }
  53406. };
  53407. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  53408. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  53409. if (this.blocks) {
  53410. for (var index = 0; index < this.blocks.length; index++) {
  53411. var block = this.blocks[index];
  53412. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  53413. }
  53414. return;
  53415. }
  53416. if (allowDuplicate) {
  53417. selection.concat(this.entries);
  53418. }
  53419. else {
  53420. selection.concatWithNoDuplicate(this.entries);
  53421. }
  53422. }
  53423. };
  53424. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  53425. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  53426. if (this.blocks) {
  53427. for (var index = 0; index < this.blocks.length; index++) {
  53428. var block = this.blocks[index];
  53429. block.intersectsRay(ray, selection);
  53430. }
  53431. return;
  53432. }
  53433. selection.concatWithNoDuplicate(this.entries);
  53434. }
  53435. };
  53436. OctreeBlock.prototype.createInnerBlocks = function () {
  53437. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  53438. };
  53439. return OctreeBlock;
  53440. })();
  53441. BABYLON.OctreeBlock = OctreeBlock;
  53442. })(BABYLON || (BABYLON = {}));
  53443. var BABYLON;
  53444. (function (BABYLON) {
  53445. var BlurPostProcess = (function (_super) {
  53446. __extends(BlurPostProcess, _super);
  53447. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  53448. var _this = this;
  53449. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53450. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  53451. this.direction = direction;
  53452. this.blurWidth = blurWidth;
  53453. this.onApplyObservable.add(function (effect) {
  53454. effect.setFloat2("screenSize", _this.width, _this.height);
  53455. effect.setVector2("direction", _this.direction);
  53456. effect.setFloat("blurWidth", _this.blurWidth);
  53457. });
  53458. }
  53459. return BlurPostProcess;
  53460. })(BABYLON.PostProcess);
  53461. BABYLON.BlurPostProcess = BlurPostProcess;
  53462. })(BABYLON || (BABYLON = {}));
  53463. var BABYLON;
  53464. (function (BABYLON) {
  53465. var RefractionPostProcess = (function (_super) {
  53466. __extends(RefractionPostProcess, _super);
  53467. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  53468. var _this = this;
  53469. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  53470. this.color = color;
  53471. this.depth = depth;
  53472. this.colorLevel = colorLevel;
  53473. this.onActivateObservable.add(function (cam) {
  53474. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  53475. });
  53476. this.onApplyObservable.add(function (effect) {
  53477. effect.setColor3("baseColor", _this.color);
  53478. effect.setFloat("depth", _this.depth);
  53479. effect.setFloat("colorLevel", _this.colorLevel);
  53480. effect.setTexture("refractionSampler", _this._refRexture);
  53481. });
  53482. }
  53483. // Methods
  53484. RefractionPostProcess.prototype.dispose = function (camera) {
  53485. if (this._refRexture) {
  53486. this._refRexture.dispose();
  53487. }
  53488. _super.prototype.dispose.call(this, camera);
  53489. };
  53490. return RefractionPostProcess;
  53491. })(BABYLON.PostProcess);
  53492. BABYLON.RefractionPostProcess = RefractionPostProcess;
  53493. })(BABYLON || (BABYLON = {}));
  53494. var BABYLON;
  53495. (function (BABYLON) {
  53496. var BlackAndWhitePostProcess = (function (_super) {
  53497. __extends(BlackAndWhitePostProcess, _super);
  53498. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  53499. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  53500. }
  53501. return BlackAndWhitePostProcess;
  53502. })(BABYLON.PostProcess);
  53503. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  53504. })(BABYLON || (BABYLON = {}));
  53505. var BABYLON;
  53506. (function (BABYLON) {
  53507. var ConvolutionPostProcess = (function (_super) {
  53508. __extends(ConvolutionPostProcess, _super);
  53509. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  53510. var _this = this;
  53511. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  53512. this.kernel = kernel;
  53513. this.onApply = function (effect) {
  53514. effect.setFloat2("screenSize", _this.width, _this.height);
  53515. effect.setArray("kernel", _this.kernel);
  53516. };
  53517. }
  53518. // Statics
  53519. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  53520. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  53521. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  53522. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  53523. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  53524. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  53525. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  53526. return ConvolutionPostProcess;
  53527. })(BABYLON.PostProcess);
  53528. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  53529. })(BABYLON || (BABYLON = {}));
  53530. var BABYLON;
  53531. (function (BABYLON) {
  53532. var FilterPostProcess = (function (_super) {
  53533. __extends(FilterPostProcess, _super);
  53534. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  53535. var _this = this;
  53536. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  53537. this.kernelMatrix = kernelMatrix;
  53538. this.onApply = function (effect) {
  53539. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  53540. };
  53541. }
  53542. return FilterPostProcess;
  53543. })(BABYLON.PostProcess);
  53544. BABYLON.FilterPostProcess = FilterPostProcess;
  53545. })(BABYLON || (BABYLON = {}));
  53546. var BABYLON;
  53547. (function (BABYLON) {
  53548. var FxaaPostProcess = (function (_super) {
  53549. __extends(FxaaPostProcess, _super);
  53550. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  53551. var _this = this;
  53552. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  53553. this.onSizeChangedObservable.add(function () {
  53554. _this.texelWidth = 1.0 / _this.width;
  53555. _this.texelHeight = 1.0 / _this.height;
  53556. });
  53557. this.onApplyObservable.add(function (effect) {
  53558. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  53559. });
  53560. }
  53561. return FxaaPostProcess;
  53562. })(BABYLON.PostProcess);
  53563. BABYLON.FxaaPostProcess = FxaaPostProcess;
  53564. })(BABYLON || (BABYLON = {}));
  53565. var BABYLON;
  53566. (function (BABYLON) {
  53567. var StereoscopicInterlacePostProcess = (function (_super) {
  53568. __extends(StereoscopicInterlacePostProcess, _super);
  53569. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  53570. var _this = this;
  53571. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  53572. this._passedProcess = rigCameras[0]._rigPostProcess;
  53573. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  53574. this.onSizeChangedObservable.add(function () {
  53575. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  53576. });
  53577. this.onApplyObservable.add(function (effect) {
  53578. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  53579. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  53580. });
  53581. }
  53582. return StereoscopicInterlacePostProcess;
  53583. })(BABYLON.PostProcess);
  53584. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  53585. })(BABYLON || (BABYLON = {}));
  53586. var BABYLON;
  53587. (function (BABYLON) {
  53588. var LensFlare = (function () {
  53589. function LensFlare(size, position, color, imgUrl, system) {
  53590. this.size = size;
  53591. this.position = position;
  53592. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  53593. this.dispose = function () {
  53594. if (this.texture) {
  53595. this.texture.dispose();
  53596. }
  53597. // Remove from scene
  53598. var index = this._system.lensFlares.indexOf(this);
  53599. this._system.lensFlares.splice(index, 1);
  53600. };
  53601. this.color = color || new BABYLON.Color3(1, 1, 1);
  53602. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  53603. this._system = system;
  53604. system.lensFlares.push(this);
  53605. }
  53606. return LensFlare;
  53607. })();
  53608. BABYLON.LensFlare = LensFlare;
  53609. })(BABYLON || (BABYLON = {}));
  53610. var BABYLON;
  53611. (function (BABYLON) {
  53612. var LensFlareSystem = (function () {
  53613. function LensFlareSystem(name, emitter, scene) {
  53614. this.name = name;
  53615. this.lensFlares = new Array();
  53616. this.borderLimit = 300;
  53617. this.layerMask = 0x0FFFFFFF;
  53618. this._vertexBuffers = {};
  53619. this._isEnabled = true;
  53620. this._scene = scene;
  53621. this._emitter = emitter;
  53622. this.id = name;
  53623. scene.lensFlareSystems.push(this);
  53624. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  53625. var engine = scene.getEngine();
  53626. // VBO
  53627. var vertices = [];
  53628. vertices.push(1, 1);
  53629. vertices.push(-1, 1);
  53630. vertices.push(-1, -1);
  53631. vertices.push(1, -1);
  53632. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  53633. // Indices
  53634. var indices = [];
  53635. indices.push(0);
  53636. indices.push(1);
  53637. indices.push(2);
  53638. indices.push(0);
  53639. indices.push(2);
  53640. indices.push(3);
  53641. this._indexBuffer = engine.createIndexBuffer(indices);
  53642. // Effects
  53643. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  53644. }
  53645. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  53646. get: function () {
  53647. return this._isEnabled;
  53648. },
  53649. set: function (value) {
  53650. this._isEnabled = value;
  53651. },
  53652. enumerable: true,
  53653. configurable: true
  53654. });
  53655. LensFlareSystem.prototype.getScene = function () {
  53656. return this._scene;
  53657. };
  53658. LensFlareSystem.prototype.getEmitter = function () {
  53659. return this._emitter;
  53660. };
  53661. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  53662. this._emitter = newEmitter;
  53663. };
  53664. LensFlareSystem.prototype.getEmitterPosition = function () {
  53665. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  53666. };
  53667. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  53668. var position = this.getEmitterPosition();
  53669. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  53670. this._positionX = position.x;
  53671. this._positionY = position.y;
  53672. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  53673. if (position.z > 0) {
  53674. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  53675. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  53676. return true;
  53677. }
  53678. }
  53679. return false;
  53680. };
  53681. LensFlareSystem.prototype._isVisible = function () {
  53682. if (!this._isEnabled) {
  53683. return false;
  53684. }
  53685. var emitterPosition = this.getEmitterPosition();
  53686. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  53687. var distance = direction.length();
  53688. direction.normalize();
  53689. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  53690. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  53691. return !pickInfo.hit || pickInfo.distance > distance;
  53692. };
  53693. LensFlareSystem.prototype.render = function () {
  53694. if (!this._effect.isReady())
  53695. return false;
  53696. var engine = this._scene.getEngine();
  53697. var viewport = this._scene.activeCamera.viewport;
  53698. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  53699. // Position
  53700. if (!this.computeEffectivePosition(globalViewport)) {
  53701. return false;
  53702. }
  53703. // Visibility
  53704. if (!this._isVisible()) {
  53705. return false;
  53706. }
  53707. // Intensity
  53708. var awayX;
  53709. var awayY;
  53710. if (this._positionX < this.borderLimit + globalViewport.x) {
  53711. awayX = this.borderLimit + globalViewport.x - this._positionX;
  53712. }
  53713. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  53714. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  53715. }
  53716. else {
  53717. awayX = 0;
  53718. }
  53719. if (this._positionY < this.borderLimit + globalViewport.y) {
  53720. awayY = this.borderLimit + globalViewport.y - this._positionY;
  53721. }
  53722. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  53723. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  53724. }
  53725. else {
  53726. awayY = 0;
  53727. }
  53728. var away = (awayX > awayY) ? awayX : awayY;
  53729. if (away > this.borderLimit) {
  53730. away = this.borderLimit;
  53731. }
  53732. var intensity = 1.0 - (away / this.borderLimit);
  53733. if (intensity < 0) {
  53734. return false;
  53735. }
  53736. if (intensity > 1.0) {
  53737. intensity = 1.0;
  53738. }
  53739. // Position
  53740. var centerX = globalViewport.x + globalViewport.width / 2;
  53741. var centerY = globalViewport.y + globalViewport.height / 2;
  53742. var distX = centerX - this._positionX;
  53743. var distY = centerY - this._positionY;
  53744. // Effects
  53745. engine.enableEffect(this._effect);
  53746. engine.setState(false);
  53747. engine.setDepthBuffer(false);
  53748. // VBOs
  53749. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  53750. // Flares
  53751. for (var index = 0; index < this.lensFlares.length; index++) {
  53752. var flare = this.lensFlares[index];
  53753. engine.setAlphaMode(flare.alphaMode);
  53754. var x = centerX - (distX * flare.position);
  53755. var y = centerY - (distY * flare.position);
  53756. var cw = flare.size;
  53757. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  53758. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  53759. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  53760. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  53761. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  53762. // Texture
  53763. this._effect.setTexture("textureSampler", flare.texture);
  53764. // Color
  53765. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  53766. // Draw order
  53767. engine.draw(true, 0, 6);
  53768. }
  53769. engine.setDepthBuffer(true);
  53770. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53771. return true;
  53772. };
  53773. LensFlareSystem.prototype.dispose = function () {
  53774. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  53775. if (vertexBuffer) {
  53776. vertexBuffer.dispose();
  53777. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  53778. }
  53779. if (this._indexBuffer) {
  53780. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53781. this._indexBuffer = null;
  53782. }
  53783. while (this.lensFlares.length) {
  53784. this.lensFlares[0].dispose();
  53785. }
  53786. // Remove from scene
  53787. var index = this._scene.lensFlareSystems.indexOf(this);
  53788. this._scene.lensFlareSystems.splice(index, 1);
  53789. };
  53790. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  53791. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  53792. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  53793. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  53794. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  53795. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  53796. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  53797. var parsedFlare = parsedLensFlareSystem.flares[index];
  53798. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  53799. }
  53800. return lensFlareSystem;
  53801. };
  53802. LensFlareSystem.prototype.serialize = function () {
  53803. var serializationObject = {};
  53804. serializationObject.id = this.id;
  53805. serializationObject.name = this.name;
  53806. serializationObject.emitterId = this.getEmitter().id;
  53807. serializationObject.borderLimit = this.borderLimit;
  53808. serializationObject.flares = [];
  53809. for (var index = 0; index < this.lensFlares.length; index++) {
  53810. var flare = this.lensFlares[index];
  53811. serializationObject.flares.push({
  53812. size: flare.size,
  53813. position: flare.position,
  53814. color: flare.color.asArray(),
  53815. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  53816. });
  53817. }
  53818. return serializationObject;
  53819. };
  53820. return LensFlareSystem;
  53821. })();
  53822. BABYLON.LensFlareSystem = LensFlareSystem;
  53823. })(BABYLON || (BABYLON = {}));
  53824. var BABYLON;
  53825. (function (BABYLON) {
  53826. // We're mainly based on the logic defined into the FreeCamera code
  53827. var DeviceOrientationCamera = (function (_super) {
  53828. __extends(DeviceOrientationCamera, _super);
  53829. function DeviceOrientationCamera(name, position, scene) {
  53830. _super.call(this, name, position, scene);
  53831. this.inputs.addDeviceOrientation();
  53832. }
  53833. DeviceOrientationCamera.prototype.getTypeName = function () {
  53834. return "DeviceOrientationCamera";
  53835. };
  53836. DeviceOrientationCamera.prototype._checkInputs = function () {
  53837. _super.prototype._checkInputs.call(this);
  53838. if (this._initialQuaternion) {
  53839. this._quaternionCache.copyFrom(this.rotationQuaternion);
  53840. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  53841. }
  53842. };
  53843. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  53844. var _this = this;
  53845. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  53846. //can only work if this camera has a rotation quaternion already.
  53847. if (!this.rotationQuaternion)
  53848. return;
  53849. if (!this._initialQuaternion) {
  53850. this._initialQuaternion = new BABYLON.Quaternion();
  53851. }
  53852. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  53853. ['x', 'y', 'z'].forEach(function (axisName) {
  53854. if (!axis[axisName]) {
  53855. _this._initialQuaternion[axisName] = 0;
  53856. }
  53857. else {
  53858. _this._initialQuaternion[axisName] *= -1;
  53859. }
  53860. });
  53861. this._initialQuaternion.normalize();
  53862. };
  53863. return DeviceOrientationCamera;
  53864. })(BABYLON.FreeCamera);
  53865. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  53866. })(BABYLON || (BABYLON = {}));
  53867. var BABYLON;
  53868. (function (BABYLON) {
  53869. var VRDeviceOrientationFreeCamera = (function (_super) {
  53870. __extends(VRDeviceOrientationFreeCamera, _super);
  53871. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  53872. if (compensateDistortion === void 0) { compensateDistortion = true; }
  53873. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  53874. _super.call(this, name, position, scene);
  53875. vrCameraMetrics.compensateDistortion = compensateDistortion;
  53876. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  53877. }
  53878. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  53879. return "VRDeviceOrientationFreeCamera";
  53880. };
  53881. return VRDeviceOrientationFreeCamera;
  53882. })(BABYLON.DeviceOrientationCamera);
  53883. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  53884. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  53885. __extends(VRDeviceOrientationArcRotateCamera, _super);
  53886. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
  53887. if (compensateDistortion === void 0) { compensateDistortion = true; }
  53888. _super.call(this, name, alpha, beta, radius, target, scene);
  53889. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  53890. metrics.compensateDistortion = compensateDistortion;
  53891. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  53892. this.inputs.addVRDeviceOrientation();
  53893. }
  53894. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  53895. return "VRDeviceOrientationArcRotateCamera";
  53896. };
  53897. return VRDeviceOrientationArcRotateCamera;
  53898. })(BABYLON.ArcRotateCamera);
  53899. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  53900. })(BABYLON || (BABYLON = {}));
  53901. var BABYLON;
  53902. (function (BABYLON) {
  53903. // We're mainly based on the logic defined into the FreeCamera code
  53904. var UniversalCamera = (function (_super) {
  53905. __extends(UniversalCamera, _super);
  53906. //-- end properties for backward compatibility for inputs
  53907. function UniversalCamera(name, position, scene) {
  53908. _super.call(this, name, position, scene);
  53909. this.inputs.addGamepad();
  53910. }
  53911. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  53912. //-- Begin properties for backward compatibility for inputs
  53913. get: function () {
  53914. var gamepad = this.inputs.attached["gamepad"];
  53915. if (gamepad)
  53916. return gamepad.gamepadAngularSensibility;
  53917. },
  53918. set: function (value) {
  53919. var gamepad = this.inputs.attached["gamepad"];
  53920. if (gamepad)
  53921. gamepad.gamepadAngularSensibility = value;
  53922. },
  53923. enumerable: true,
  53924. configurable: true
  53925. });
  53926. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  53927. get: function () {
  53928. var gamepad = this.inputs.attached["gamepad"];
  53929. if (gamepad)
  53930. return gamepad.gamepadMoveSensibility;
  53931. },
  53932. set: function (value) {
  53933. var gamepad = this.inputs.attached["gamepad"];
  53934. if (gamepad)
  53935. gamepad.gamepadMoveSensibility = value;
  53936. },
  53937. enumerable: true,
  53938. configurable: true
  53939. });
  53940. UniversalCamera.prototype.getTypeName = function () {
  53941. return "UniversalCamera";
  53942. };
  53943. return UniversalCamera;
  53944. })(BABYLON.TouchCamera);
  53945. BABYLON.UniversalCamera = UniversalCamera;
  53946. })(BABYLON || (BABYLON = {}));
  53947. var BABYLON;
  53948. (function (BABYLON) {
  53949. var Gamepads = (function () {
  53950. function Gamepads(ongamedpadconnected) {
  53951. var _this = this;
  53952. this.babylonGamepads = [];
  53953. this.oneGamepadConnected = false;
  53954. this.isMonitoring = false;
  53955. this.gamepadEventSupported = 'GamepadEvent' in window;
  53956. this.gamepadSupportAvailable = (navigator.getGamepads ||
  53957. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  53958. this._callbackGamepadConnected = ongamedpadconnected;
  53959. if (this.gamepadSupportAvailable) {
  53960. // Checking if the gamepad connected event is supported (like in Firefox)
  53961. if (this.gamepadEventSupported) {
  53962. this._onGamepadConnectedEvent = function (evt) {
  53963. _this._onGamepadConnected(evt);
  53964. };
  53965. this._onGamepadDisonnectedEvent = function (evt) {
  53966. _this._onGamepadDisconnected(evt);
  53967. };
  53968. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  53969. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  53970. }
  53971. else {
  53972. this._startMonitoringGamepads();
  53973. }
  53974. }
  53975. }
  53976. Gamepads.prototype.dispose = function () {
  53977. if (Gamepads.gamepadDOMInfo) {
  53978. document.body.removeChild(Gamepads.gamepadDOMInfo);
  53979. }
  53980. if (this._onGamepadConnectedEvent) {
  53981. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  53982. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  53983. this._onGamepadConnectedEvent = null;
  53984. this._onGamepadDisonnectedEvent = null;
  53985. }
  53986. };
  53987. Gamepads.prototype._onGamepadConnected = function (evt) {
  53988. var newGamepad = this._addNewGamepad(evt.gamepad);
  53989. if (this._callbackGamepadConnected)
  53990. this._callbackGamepadConnected(newGamepad);
  53991. this._startMonitoringGamepads();
  53992. };
  53993. Gamepads.prototype._addNewGamepad = function (gamepad) {
  53994. if (!this.oneGamepadConnected) {
  53995. this.oneGamepadConnected = true;
  53996. if (Gamepads.gamepadDOMInfo) {
  53997. document.body.removeChild(Gamepads.gamepadDOMInfo);
  53998. Gamepads.gamepadDOMInfo = null;
  53999. }
  54000. }
  54001. var newGamepad;
  54002. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  54003. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  54004. }
  54005. else {
  54006. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  54007. }
  54008. this.babylonGamepads.push(newGamepad);
  54009. return newGamepad;
  54010. };
  54011. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  54012. // Remove the gamepad from the list of gamepads to monitor.
  54013. for (var i in this.babylonGamepads) {
  54014. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  54015. this.babylonGamepads.splice(+i, 1);
  54016. break;
  54017. }
  54018. }
  54019. // If no gamepads are left, stop the polling loop.
  54020. if (this.babylonGamepads.length == 0) {
  54021. this._stopMonitoringGamepads();
  54022. }
  54023. };
  54024. Gamepads.prototype._startMonitoringGamepads = function () {
  54025. if (!this.isMonitoring) {
  54026. this.isMonitoring = true;
  54027. this._checkGamepadsStatus();
  54028. }
  54029. };
  54030. Gamepads.prototype._stopMonitoringGamepads = function () {
  54031. this.isMonitoring = false;
  54032. };
  54033. Gamepads.prototype._checkGamepadsStatus = function () {
  54034. var _this = this;
  54035. // updating gamepad objects
  54036. this._updateGamepadObjects();
  54037. for (var i in this.babylonGamepads) {
  54038. this.babylonGamepads[i].update();
  54039. }
  54040. if (this.isMonitoring) {
  54041. if (window.requestAnimationFrame) {
  54042. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  54043. }
  54044. else if (window.mozRequestAnimationFrame) {
  54045. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  54046. }
  54047. else if (window.webkitRequestAnimationFrame) {
  54048. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  54049. }
  54050. }
  54051. };
  54052. // This function is called only on Chrome, which does not yet support
  54053. // connection/disconnection events, but requires you to monitor
  54054. // an array for changes.
  54055. Gamepads.prototype._updateGamepadObjects = function () {
  54056. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  54057. for (var i = 0; i < gamepads.length; i++) {
  54058. if (gamepads[i]) {
  54059. if (!(gamepads[i].index in this.babylonGamepads)) {
  54060. var newGamepad = this._addNewGamepad(gamepads[i]);
  54061. if (this._callbackGamepadConnected) {
  54062. this._callbackGamepadConnected(newGamepad);
  54063. }
  54064. }
  54065. else {
  54066. this.babylonGamepads[i].browserGamepad = gamepads[i];
  54067. }
  54068. }
  54069. }
  54070. };
  54071. return Gamepads;
  54072. })();
  54073. BABYLON.Gamepads = Gamepads;
  54074. var StickValues = (function () {
  54075. function StickValues(x, y) {
  54076. this.x = x;
  54077. this.y = y;
  54078. }
  54079. return StickValues;
  54080. })();
  54081. BABYLON.StickValues = StickValues;
  54082. var Gamepad = (function () {
  54083. function Gamepad(id, index, browserGamepad) {
  54084. this.id = id;
  54085. this.index = index;
  54086. this.browserGamepad = browserGamepad;
  54087. if (this.browserGamepad.axes.length >= 2) {
  54088. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  54089. }
  54090. if (this.browserGamepad.axes.length >= 4) {
  54091. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  54092. }
  54093. }
  54094. Gamepad.prototype.onleftstickchanged = function (callback) {
  54095. this._onleftstickchanged = callback;
  54096. };
  54097. Gamepad.prototype.onrightstickchanged = function (callback) {
  54098. this._onrightstickchanged = callback;
  54099. };
  54100. Object.defineProperty(Gamepad.prototype, "leftStick", {
  54101. get: function () {
  54102. return this._leftStick;
  54103. },
  54104. set: function (newValues) {
  54105. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  54106. this._onleftstickchanged(newValues);
  54107. }
  54108. this._leftStick = newValues;
  54109. },
  54110. enumerable: true,
  54111. configurable: true
  54112. });
  54113. Object.defineProperty(Gamepad.prototype, "rightStick", {
  54114. get: function () {
  54115. return this._rightStick;
  54116. },
  54117. set: function (newValues) {
  54118. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  54119. this._onrightstickchanged(newValues);
  54120. }
  54121. this._rightStick = newValues;
  54122. },
  54123. enumerable: true,
  54124. configurable: true
  54125. });
  54126. Gamepad.prototype.update = function () {
  54127. if (this._leftStick) {
  54128. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  54129. }
  54130. if (this._rightStick) {
  54131. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  54132. }
  54133. };
  54134. return Gamepad;
  54135. })();
  54136. BABYLON.Gamepad = Gamepad;
  54137. var GenericPad = (function (_super) {
  54138. __extends(GenericPad, _super);
  54139. function GenericPad(id, index, gamepad) {
  54140. _super.call(this, id, index, gamepad);
  54141. this.id = id;
  54142. this.index = index;
  54143. this.gamepad = gamepad;
  54144. this._buttons = new Array(gamepad.buttons.length);
  54145. }
  54146. GenericPad.prototype.onbuttondown = function (callback) {
  54147. this._onbuttondown = callback;
  54148. };
  54149. GenericPad.prototype.onbuttonup = function (callback) {
  54150. this._onbuttonup = callback;
  54151. };
  54152. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  54153. if (newValue !== currentValue) {
  54154. if (this._onbuttondown && newValue === 1) {
  54155. this._onbuttondown(buttonIndex);
  54156. }
  54157. if (this._onbuttonup && newValue === 0) {
  54158. this._onbuttonup(buttonIndex);
  54159. }
  54160. }
  54161. return newValue;
  54162. };
  54163. GenericPad.prototype.update = function () {
  54164. _super.prototype.update.call(this);
  54165. for (var index = 0; index < this._buttons.length; index++) {
  54166. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  54167. }
  54168. };
  54169. return GenericPad;
  54170. })(Gamepad);
  54171. BABYLON.GenericPad = GenericPad;
  54172. (function (Xbox360Button) {
  54173. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  54174. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  54175. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  54176. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  54177. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  54178. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  54179. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  54180. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  54181. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  54182. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  54183. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  54184. var Xbox360Button = BABYLON.Xbox360Button;
  54185. (function (Xbox360Dpad) {
  54186. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  54187. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  54188. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  54189. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  54190. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  54191. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  54192. var Xbox360Pad = (function (_super) {
  54193. __extends(Xbox360Pad, _super);
  54194. function Xbox360Pad() {
  54195. _super.apply(this, arguments);
  54196. this._leftTrigger = 0;
  54197. this._rightTrigger = 0;
  54198. this._buttonA = 0;
  54199. this._buttonB = 0;
  54200. this._buttonX = 0;
  54201. this._buttonY = 0;
  54202. this._buttonBack = 0;
  54203. this._buttonStart = 0;
  54204. this._buttonLB = 0;
  54205. this._buttonRB = 0;
  54206. this._buttonLeftStick = 0;
  54207. this._buttonRightStick = 0;
  54208. this._dPadUp = 0;
  54209. this._dPadDown = 0;
  54210. this._dPadLeft = 0;
  54211. this._dPadRight = 0;
  54212. }
  54213. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  54214. this._onlefttriggerchanged = callback;
  54215. };
  54216. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  54217. this._onrighttriggerchanged = callback;
  54218. };
  54219. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  54220. get: function () {
  54221. return this._leftTrigger;
  54222. },
  54223. set: function (newValue) {
  54224. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  54225. this._onlefttriggerchanged(newValue);
  54226. }
  54227. this._leftTrigger = newValue;
  54228. },
  54229. enumerable: true,
  54230. configurable: true
  54231. });
  54232. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  54233. get: function () {
  54234. return this._rightTrigger;
  54235. },
  54236. set: function (newValue) {
  54237. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  54238. this._onrighttriggerchanged(newValue);
  54239. }
  54240. this._rightTrigger = newValue;
  54241. },
  54242. enumerable: true,
  54243. configurable: true
  54244. });
  54245. Xbox360Pad.prototype.onbuttondown = function (callback) {
  54246. this._onbuttondown = callback;
  54247. };
  54248. Xbox360Pad.prototype.onbuttonup = function (callback) {
  54249. this._onbuttonup = callback;
  54250. };
  54251. Xbox360Pad.prototype.ondpaddown = function (callback) {
  54252. this._ondpaddown = callback;
  54253. };
  54254. Xbox360Pad.prototype.ondpadup = function (callback) {
  54255. this._ondpadup = callback;
  54256. };
  54257. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  54258. if (newValue !== currentValue) {
  54259. if (this._onbuttondown && newValue === 1) {
  54260. this._onbuttondown(buttonType);
  54261. }
  54262. if (this._onbuttonup && newValue === 0) {
  54263. this._onbuttonup(buttonType);
  54264. }
  54265. }
  54266. return newValue;
  54267. };
  54268. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  54269. if (newValue !== currentValue) {
  54270. if (this._ondpaddown && newValue === 1) {
  54271. this._ondpaddown(buttonType);
  54272. }
  54273. if (this._ondpadup && newValue === 0) {
  54274. this._ondpadup(buttonType);
  54275. }
  54276. }
  54277. return newValue;
  54278. };
  54279. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  54280. get: function () {
  54281. return this._buttonA;
  54282. },
  54283. set: function (value) {
  54284. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  54285. },
  54286. enumerable: true,
  54287. configurable: true
  54288. });
  54289. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  54290. get: function () {
  54291. return this._buttonB;
  54292. },
  54293. set: function (value) {
  54294. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  54295. },
  54296. enumerable: true,
  54297. configurable: true
  54298. });
  54299. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  54300. get: function () {
  54301. return this._buttonX;
  54302. },
  54303. set: function (value) {
  54304. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  54305. },
  54306. enumerable: true,
  54307. configurable: true
  54308. });
  54309. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  54310. get: function () {
  54311. return this._buttonY;
  54312. },
  54313. set: function (value) {
  54314. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  54315. },
  54316. enumerable: true,
  54317. configurable: true
  54318. });
  54319. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  54320. get: function () {
  54321. return this._buttonStart;
  54322. },
  54323. set: function (value) {
  54324. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  54325. },
  54326. enumerable: true,
  54327. configurable: true
  54328. });
  54329. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  54330. get: function () {
  54331. return this._buttonBack;
  54332. },
  54333. set: function (value) {
  54334. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  54335. },
  54336. enumerable: true,
  54337. configurable: true
  54338. });
  54339. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  54340. get: function () {
  54341. return this._buttonLB;
  54342. },
  54343. set: function (value) {
  54344. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  54345. },
  54346. enumerable: true,
  54347. configurable: true
  54348. });
  54349. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  54350. get: function () {
  54351. return this._buttonRB;
  54352. },
  54353. set: function (value) {
  54354. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  54355. },
  54356. enumerable: true,
  54357. configurable: true
  54358. });
  54359. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  54360. get: function () {
  54361. return this._buttonLeftStick;
  54362. },
  54363. set: function (value) {
  54364. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  54365. },
  54366. enumerable: true,
  54367. configurable: true
  54368. });
  54369. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  54370. get: function () {
  54371. return this._buttonRightStick;
  54372. },
  54373. set: function (value) {
  54374. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  54375. },
  54376. enumerable: true,
  54377. configurable: true
  54378. });
  54379. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  54380. get: function () {
  54381. return this._dPadUp;
  54382. },
  54383. set: function (value) {
  54384. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  54385. },
  54386. enumerable: true,
  54387. configurable: true
  54388. });
  54389. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  54390. get: function () {
  54391. return this._dPadDown;
  54392. },
  54393. set: function (value) {
  54394. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  54395. },
  54396. enumerable: true,
  54397. configurable: true
  54398. });
  54399. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  54400. get: function () {
  54401. return this._dPadLeft;
  54402. },
  54403. set: function (value) {
  54404. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  54405. },
  54406. enumerable: true,
  54407. configurable: true
  54408. });
  54409. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  54410. get: function () {
  54411. return this._dPadRight;
  54412. },
  54413. set: function (value) {
  54414. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  54415. },
  54416. enumerable: true,
  54417. configurable: true
  54418. });
  54419. Xbox360Pad.prototype.update = function () {
  54420. _super.prototype.update.call(this);
  54421. this.buttonA = this.browserGamepad.buttons[0].value;
  54422. this.buttonB = this.browserGamepad.buttons[1].value;
  54423. this.buttonX = this.browserGamepad.buttons[2].value;
  54424. this.buttonY = this.browserGamepad.buttons[3].value;
  54425. this.buttonLB = this.browserGamepad.buttons[4].value;
  54426. this.buttonRB = this.browserGamepad.buttons[5].value;
  54427. this.leftTrigger = this.browserGamepad.buttons[6].value;
  54428. this.rightTrigger = this.browserGamepad.buttons[7].value;
  54429. this.buttonBack = this.browserGamepad.buttons[8].value;
  54430. this.buttonStart = this.browserGamepad.buttons[9].value;
  54431. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  54432. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  54433. this.dPadUp = this.browserGamepad.buttons[12].value;
  54434. this.dPadDown = this.browserGamepad.buttons[13].value;
  54435. this.dPadLeft = this.browserGamepad.buttons[14].value;
  54436. this.dPadRight = this.browserGamepad.buttons[15].value;
  54437. };
  54438. return Xbox360Pad;
  54439. })(Gamepad);
  54440. BABYLON.Xbox360Pad = Xbox360Pad;
  54441. })(BABYLON || (BABYLON = {}));
  54442. var BABYLON;
  54443. (function (BABYLON) {
  54444. // We're mainly based on the logic defined into the FreeCamera code
  54445. var GamepadCamera = (function (_super) {
  54446. __extends(GamepadCamera, _super);
  54447. //-- end properties for backward compatibility for inputs
  54448. function GamepadCamera(name, position, scene) {
  54449. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  54450. _super.call(this, name, position, scene);
  54451. }
  54452. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  54453. //-- Begin properties for backward compatibility for inputs
  54454. get: function () {
  54455. var gamepad = this.inputs.attached["gamepad"];
  54456. if (gamepad)
  54457. return gamepad.gamepadAngularSensibility;
  54458. },
  54459. set: function (value) {
  54460. var gamepad = this.inputs.attached["gamepad"];
  54461. if (gamepad)
  54462. gamepad.gamepadAngularSensibility = value;
  54463. },
  54464. enumerable: true,
  54465. configurable: true
  54466. });
  54467. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  54468. get: function () {
  54469. var gamepad = this.inputs.attached["gamepad"];
  54470. if (gamepad)
  54471. return gamepad.gamepadMoveSensibility;
  54472. },
  54473. set: function (value) {
  54474. var gamepad = this.inputs.attached["gamepad"];
  54475. if (gamepad)
  54476. gamepad.gamepadMoveSensibility = value;
  54477. },
  54478. enumerable: true,
  54479. configurable: true
  54480. });
  54481. GamepadCamera.prototype.getTypeName = function () {
  54482. return "GamepadCamera";
  54483. };
  54484. return GamepadCamera;
  54485. })(BABYLON.UniversalCamera);
  54486. BABYLON.GamepadCamera = GamepadCamera;
  54487. })(BABYLON || (BABYLON = {}));
  54488. var BABYLON;
  54489. (function (BABYLON) {
  54490. var Analyser = (function () {
  54491. function Analyser(scene) {
  54492. this.SMOOTHING = 0.75;
  54493. this.FFT_SIZE = 512;
  54494. this.BARGRAPHAMPLITUDE = 256;
  54495. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  54496. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  54497. this._scene = scene;
  54498. this._audioEngine = BABYLON.Engine.audioEngine;
  54499. if (this._audioEngine.canUseWebAudio) {
  54500. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  54501. this._webAudioAnalyser.minDecibels = -140;
  54502. this._webAudioAnalyser.maxDecibels = 0;
  54503. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  54504. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  54505. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  54506. }
  54507. }
  54508. Analyser.prototype.getFrequencyBinCount = function () {
  54509. if (this._audioEngine.canUseWebAudio) {
  54510. return this._webAudioAnalyser.frequencyBinCount;
  54511. }
  54512. else {
  54513. return 0;
  54514. }
  54515. };
  54516. Analyser.prototype.getByteFrequencyData = function () {
  54517. if (this._audioEngine.canUseWebAudio) {
  54518. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54519. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54520. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  54521. }
  54522. return this._byteFreqs;
  54523. };
  54524. Analyser.prototype.getByteTimeDomainData = function () {
  54525. if (this._audioEngine.canUseWebAudio) {
  54526. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54527. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54528. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  54529. }
  54530. return this._byteTime;
  54531. };
  54532. Analyser.prototype.getFloatFrequencyData = function () {
  54533. if (this._audioEngine.canUseWebAudio) {
  54534. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54535. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54536. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  54537. }
  54538. return this._floatFreqs;
  54539. };
  54540. Analyser.prototype.drawDebugCanvas = function () {
  54541. var _this = this;
  54542. if (this._audioEngine.canUseWebAudio) {
  54543. if (!this._debugCanvas) {
  54544. this._debugCanvas = document.createElement("canvas");
  54545. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  54546. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  54547. this._debugCanvas.style.position = "absolute";
  54548. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  54549. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  54550. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  54551. document.body.appendChild(this._debugCanvas);
  54552. this._registerFunc = function () {
  54553. _this.drawDebugCanvas();
  54554. };
  54555. this._scene.registerBeforeRender(this._registerFunc);
  54556. }
  54557. if (this._registerFunc) {
  54558. var workingArray = this.getByteFrequencyData();
  54559. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  54560. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  54561. // Draw the frequency domain chart.
  54562. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  54563. var value = workingArray[i];
  54564. var percent = value / this.BARGRAPHAMPLITUDE;
  54565. var height = this.DEBUGCANVASSIZE.height * percent;
  54566. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  54567. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  54568. var hue = i / this.getFrequencyBinCount() * 360;
  54569. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  54570. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  54571. }
  54572. }
  54573. }
  54574. };
  54575. Analyser.prototype.stopDebugCanvas = function () {
  54576. if (this._debugCanvas) {
  54577. this._scene.unregisterBeforeRender(this._registerFunc);
  54578. this._registerFunc = null;
  54579. document.body.removeChild(this._debugCanvas);
  54580. this._debugCanvas = null;
  54581. this._debugCanvasContext = null;
  54582. }
  54583. };
  54584. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  54585. if (this._audioEngine.canUseWebAudio) {
  54586. inputAudioNode.connect(this._webAudioAnalyser);
  54587. this._webAudioAnalyser.connect(outputAudioNode);
  54588. }
  54589. };
  54590. Analyser.prototype.dispose = function () {
  54591. if (this._audioEngine.canUseWebAudio) {
  54592. this._webAudioAnalyser.disconnect();
  54593. }
  54594. };
  54595. return Analyser;
  54596. })();
  54597. BABYLON.Analyser = Analyser;
  54598. })(BABYLON || (BABYLON = {}));
  54599. var BABYLON;
  54600. (function (BABYLON) {
  54601. var DepthRenderer = (function () {
  54602. function DepthRenderer(scene, type) {
  54603. var _this = this;
  54604. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  54605. this._viewMatrix = BABYLON.Matrix.Zero();
  54606. this._projectionMatrix = BABYLON.Matrix.Zero();
  54607. this._transformMatrix = BABYLON.Matrix.Zero();
  54608. this._worldViewProjection = BABYLON.Matrix.Zero();
  54609. this._scene = scene;
  54610. var engine = scene.getEngine();
  54611. // Render target
  54612. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  54613. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54614. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54615. this._depthMap.refreshRate = 1;
  54616. this._depthMap.renderParticles = false;
  54617. this._depthMap.renderList = null;
  54618. // set default depth value to 1.0 (far away)
  54619. this._depthMap.onClearObservable.add(function (engine) {
  54620. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  54621. });
  54622. // Custom render function
  54623. var renderSubMesh = function (subMesh) {
  54624. var mesh = subMesh.getRenderingMesh();
  54625. var scene = _this._scene;
  54626. var engine = scene.getEngine();
  54627. // Culling
  54628. engine.setState(subMesh.getMaterial().backFaceCulling);
  54629. // Managing instances
  54630. var batch = mesh._getInstancesRenderList(subMesh._id);
  54631. if (batch.mustReturn) {
  54632. return;
  54633. }
  54634. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  54635. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  54636. engine.enableEffect(_this._effect);
  54637. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  54638. var material = subMesh.getMaterial();
  54639. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  54640. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  54641. // Alpha test
  54642. if (material && material.needAlphaTesting()) {
  54643. var alphaTexture = material.getAlphaTestTexture();
  54644. _this._effect.setTexture("diffuseSampler", alphaTexture);
  54645. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  54646. }
  54647. // Bones
  54648. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54649. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  54650. }
  54651. // Draw
  54652. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  54653. }
  54654. };
  54655. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  54656. var index;
  54657. for (index = 0; index < opaqueSubMeshes.length; index++) {
  54658. renderSubMesh(opaqueSubMeshes.data[index]);
  54659. }
  54660. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  54661. renderSubMesh(alphaTestSubMeshes.data[index]);
  54662. }
  54663. };
  54664. }
  54665. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  54666. var material = subMesh.getMaterial();
  54667. if (material.disableDepthWrite) {
  54668. return false;
  54669. }
  54670. var defines = [];
  54671. var attribs = [BABYLON.VertexBuffer.PositionKind];
  54672. var mesh = subMesh.getMesh();
  54673. var scene = mesh.getScene();
  54674. // Alpha test
  54675. if (material && material.needAlphaTesting()) {
  54676. defines.push("#define ALPHATEST");
  54677. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54678. attribs.push(BABYLON.VertexBuffer.UVKind);
  54679. defines.push("#define UV1");
  54680. }
  54681. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  54682. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  54683. defines.push("#define UV2");
  54684. }
  54685. }
  54686. // Bones
  54687. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54688. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54689. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54690. if (mesh.numBoneInfluencers > 4) {
  54691. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54692. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54693. }
  54694. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54695. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54696. }
  54697. else {
  54698. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54699. }
  54700. // Instances
  54701. if (useInstances) {
  54702. defines.push("#define INSTANCES");
  54703. attribs.push("world0");
  54704. attribs.push("world1");
  54705. attribs.push("world2");
  54706. attribs.push("world3");
  54707. }
  54708. // Get correct effect
  54709. var join = defines.join("\n");
  54710. if (this._cachedDefines !== join) {
  54711. this._cachedDefines = join;
  54712. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  54713. }
  54714. return this._effect.isReady();
  54715. };
  54716. DepthRenderer.prototype.getDepthMap = function () {
  54717. return this._depthMap;
  54718. };
  54719. // Methods
  54720. DepthRenderer.prototype.dispose = function () {
  54721. this._depthMap.dispose();
  54722. };
  54723. return DepthRenderer;
  54724. })();
  54725. BABYLON.DepthRenderer = DepthRenderer;
  54726. })(BABYLON || (BABYLON = {}));
  54727. var BABYLON;
  54728. (function (BABYLON) {
  54729. var SSAORenderingPipeline = (function (_super) {
  54730. __extends(SSAORenderingPipeline, _super);
  54731. /**
  54732. * @constructor
  54733. * @param {string} name - The rendering pipeline name
  54734. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54735. * @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 }
  54736. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54737. */
  54738. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  54739. var _this = this;
  54740. _super.call(this, scene.getEngine(), name);
  54741. // Members
  54742. /**
  54743. * The PassPostProcess id in the pipeline that contains the original scene color
  54744. * @type {string}
  54745. */
  54746. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  54747. /**
  54748. * The SSAO PostProcess id in the pipeline
  54749. * @type {string}
  54750. */
  54751. this.SSAORenderEffect = "SSAORenderEffect";
  54752. /**
  54753. * The horizontal blur PostProcess id in the pipeline
  54754. * @type {string}
  54755. */
  54756. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  54757. /**
  54758. * The vertical blur PostProcess id in the pipeline
  54759. * @type {string}
  54760. */
  54761. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  54762. /**
  54763. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  54764. * @type {string}
  54765. */
  54766. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  54767. /**
  54768. * The output strength of the SSAO post-process. Default value is 1.0.
  54769. * @type {number}
  54770. */
  54771. this.totalStrength = 1.0;
  54772. /**
  54773. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  54774. * @type {number}
  54775. */
  54776. this.radius = 0.0001;
  54777. /**
  54778. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  54779. * Must not be equal to fallOff and superior to fallOff.
  54780. * Default value is 0.975
  54781. * @type {number}
  54782. */
  54783. this.area = 0.0075;
  54784. /**
  54785. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  54786. * Must not be equal to area and inferior to area.
  54787. * Default value is 0.0
  54788. * @type {number}
  54789. */
  54790. this.fallOff = 0.000001;
  54791. /**
  54792. * The base color of the SSAO post-process
  54793. * The final result is "base + ssao" between [0, 1]
  54794. * @type {number}
  54795. */
  54796. this.base = 0.5;
  54797. this._firstUpdate = true;
  54798. this._scene = scene;
  54799. // Set up assets
  54800. this._createRandomTexture();
  54801. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  54802. var ssaoRatio = ratio.ssaoRatio || ratio;
  54803. var combineRatio = ratio.combineRatio || ratio;
  54804. this._ratio = {
  54805. ssaoRatio: ssaoRatio,
  54806. combineRatio: combineRatio
  54807. };
  54808. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  54809. this._createSSAOPostProcess(ssaoRatio);
  54810. this._createBlurPostProcess(ssaoRatio);
  54811. this._createSSAOCombinePostProcess(combineRatio);
  54812. // Set up pipeline
  54813. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  54814. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  54815. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  54816. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  54817. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  54818. // Finish
  54819. scene.postProcessRenderPipelineManager.addPipeline(this);
  54820. if (cameras)
  54821. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54822. }
  54823. // Public Methods
  54824. /**
  54825. * Returns the horizontal blur PostProcess
  54826. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  54827. */
  54828. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  54829. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  54830. return null;
  54831. };
  54832. /**
  54833. * Returns the vertical blur PostProcess
  54834. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  54835. */
  54836. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  54837. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  54838. return null;
  54839. };
  54840. /**
  54841. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  54842. */
  54843. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  54844. if (disableDepthRender === void 0) { disableDepthRender = false; }
  54845. for (var i = 0; i < this._scene.cameras.length; i++) {
  54846. var camera = this._scene.cameras[i];
  54847. this._originalColorPostProcess.dispose(camera);
  54848. this._ssaoPostProcess.dispose(camera);
  54849. this._blurHPostProcess.dispose(camera);
  54850. this._blurVPostProcess.dispose(camera);
  54851. this._ssaoCombinePostProcess.dispose(camera);
  54852. }
  54853. this._randomTexture.dispose();
  54854. if (disableDepthRender)
  54855. this._scene.disableDepthRenderer();
  54856. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54857. };
  54858. // Private Methods
  54859. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  54860. var _this = this;
  54861. /*
  54862. var samplerOffsets = [
  54863. -8.0, -6.0, -4.0, -2.0,
  54864. 0.0,
  54865. 2.0, 4.0, 6.0, 8.0
  54866. ];
  54867. */
  54868. var samples = 16;
  54869. var samplerOffsets = [];
  54870. for (var i = -8; i < 8; i++) {
  54871. samplerOffsets.push(i * 2);
  54872. }
  54873. 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");
  54874. this._blurHPostProcess.onApply = function (effect) {
  54875. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  54876. effect.setTexture("depthSampler", _this._depthTexture);
  54877. if (_this._firstUpdate) {
  54878. effect.setArray("samplerOffsets", samplerOffsets);
  54879. }
  54880. };
  54881. 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");
  54882. this._blurVPostProcess.onApply = function (effect) {
  54883. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  54884. effect.setTexture("depthSampler", _this._depthTexture);
  54885. if (_this._firstUpdate) {
  54886. effect.setArray("samplerOffsets", samplerOffsets);
  54887. _this._firstUpdate = false;
  54888. }
  54889. };
  54890. };
  54891. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  54892. var _this = this;
  54893. var numSamples = 16;
  54894. var sampleSphere = [
  54895. 0.5381, 0.1856, -0.4319,
  54896. 0.1379, 0.2486, 0.4430,
  54897. 0.3371, 0.5679, -0.0057,
  54898. -0.6999, -0.0451, -0.0019,
  54899. 0.0689, -0.1598, -0.8547,
  54900. 0.0560, 0.0069, -0.1843,
  54901. -0.0146, 0.1402, 0.0762,
  54902. 0.0100, -0.1924, -0.0344,
  54903. -0.3577, -0.5301, -0.4358,
  54904. -0.3169, 0.1063, 0.0158,
  54905. 0.0103, -0.5869, 0.0046,
  54906. -0.0897, -0.4940, 0.3287,
  54907. 0.7119, -0.0154, -0.0918,
  54908. -0.0533, 0.0596, -0.5411,
  54909. 0.0352, -0.0631, 0.5460,
  54910. -0.4776, 0.2847, -0.0271
  54911. ];
  54912. var samplesFactor = 1.0 / numSamples;
  54913. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  54914. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  54915. "area", "fallOff", "base", "range", "viewport"
  54916. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  54917. var viewport = new BABYLON.Vector2(0, 0);
  54918. this._ssaoPostProcess.onApply = function (effect) {
  54919. if (_this._firstUpdate) {
  54920. effect.setArray3("sampleSphere", sampleSphere);
  54921. effect.setFloat("samplesFactor", samplesFactor);
  54922. effect.setFloat("randTextureTiles", 4.0);
  54923. }
  54924. effect.setFloat("totalStrength", _this.totalStrength);
  54925. effect.setFloat("radius", _this.radius);
  54926. effect.setFloat("area", _this.area);
  54927. effect.setFloat("fallOff", _this.fallOff);
  54928. effect.setFloat("base", _this.base);
  54929. effect.setTexture("textureSampler", _this._depthTexture);
  54930. effect.setTexture("randomSampler", _this._randomTexture);
  54931. };
  54932. };
  54933. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  54934. var _this = this;
  54935. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54936. this._ssaoCombinePostProcess.onApply = function (effect) {
  54937. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  54938. };
  54939. };
  54940. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  54941. var size = 512;
  54942. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  54943. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54944. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54945. var context = this._randomTexture.getContext();
  54946. var rand = function (min, max) {
  54947. return Math.random() * (max - min) + min;
  54948. };
  54949. var randVector = BABYLON.Vector3.Zero();
  54950. for (var x = 0; x < size; x++) {
  54951. for (var y = 0; y < size; y++) {
  54952. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  54953. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  54954. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  54955. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  54956. context.fillRect(x, y, 1, 1);
  54957. }
  54958. }
  54959. this._randomTexture.update(false);
  54960. };
  54961. __decorate([
  54962. BABYLON.serialize()
  54963. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  54964. __decorate([
  54965. BABYLON.serialize()
  54966. ], SSAORenderingPipeline.prototype, "radius", void 0);
  54967. __decorate([
  54968. BABYLON.serialize()
  54969. ], SSAORenderingPipeline.prototype, "area", void 0);
  54970. __decorate([
  54971. BABYLON.serialize()
  54972. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  54973. __decorate([
  54974. BABYLON.serialize()
  54975. ], SSAORenderingPipeline.prototype, "base", void 0);
  54976. __decorate([
  54977. BABYLON.serialize()
  54978. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  54979. return SSAORenderingPipeline;
  54980. })(BABYLON.PostProcessRenderPipeline);
  54981. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  54982. })(BABYLON || (BABYLON = {}));
  54983. var BABYLON;
  54984. (function (BABYLON) {
  54985. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  54986. var VolumetricLightScatteringPostProcess = (function (_super) {
  54987. __extends(VolumetricLightScatteringPostProcess, _super);
  54988. /**
  54989. * @constructor
  54990. * @param {string} name - The post-process name
  54991. * @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)
  54992. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  54993. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  54994. * @param {number} samples - The post-process quality, default 100
  54995. * @param {number} samplingMode - The post-process filtering mode
  54996. * @param {BABYLON.Engine} engine - The babylon engine
  54997. * @param {boolean} reusable - If the post-process is reusable
  54998. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  54999. */
  55000. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  55001. var _this = this;
  55002. if (samples === void 0) { samples = 100; }
  55003. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55004. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  55005. this._screenCoordinates = BABYLON.Vector2.Zero();
  55006. /**
  55007. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  55008. * @type {Vector3}
  55009. */
  55010. this.customMeshPosition = BABYLON.Vector3.Zero();
  55011. /**
  55012. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  55013. * @type {boolean}
  55014. */
  55015. this.useCustomMeshPosition = false;
  55016. /**
  55017. * If the post-process should inverse the light scattering direction
  55018. * @type {boolean}
  55019. */
  55020. this.invert = true;
  55021. /**
  55022. * Array containing the excluded meshes not rendered in the internal pass
  55023. */
  55024. this.excludedMeshes = new Array();
  55025. /**
  55026. * Controls the overall intensity of the post-process
  55027. * @type {number}
  55028. */
  55029. this.exposure = 0.3;
  55030. /**
  55031. * Dissipates each sample's contribution in range [0, 1]
  55032. * @type {number}
  55033. */
  55034. this.decay = 0.96815;
  55035. /**
  55036. * Controls the overall intensity of each sample
  55037. * @type {number}
  55038. */
  55039. this.weight = 0.58767;
  55040. /**
  55041. * Controls the density of each sample
  55042. * @type {number}
  55043. */
  55044. this.density = 0.926;
  55045. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  55046. var engine = scene.getEngine();
  55047. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  55048. // Configure mesh
  55049. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  55050. // Configure
  55051. this._createPass(scene, ratio.passRatio || ratio);
  55052. this.onActivate = function (camera) {
  55053. if (!_this.isSupported) {
  55054. _this.dispose(camera);
  55055. }
  55056. _this.onActivate = null;
  55057. };
  55058. this.onApplyObservable.add(function (effect) {
  55059. _this._updateMeshScreenCoordinates(scene);
  55060. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  55061. effect.setFloat("exposure", _this.exposure);
  55062. effect.setFloat("decay", _this.decay);
  55063. effect.setFloat("weight", _this.weight);
  55064. effect.setFloat("density", _this.density);
  55065. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  55066. });
  55067. }
  55068. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  55069. get: function () {
  55070. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  55071. return false;
  55072. },
  55073. set: function (useDiffuseColor) {
  55074. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  55075. },
  55076. enumerable: true,
  55077. configurable: true
  55078. });
  55079. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  55080. var mesh = subMesh.getMesh();
  55081. // Render this.mesh as default
  55082. if (mesh === this.mesh) {
  55083. return mesh.material.isReady(mesh);
  55084. }
  55085. var defines = [];
  55086. var attribs = [BABYLON.VertexBuffer.PositionKind];
  55087. var material = subMesh.getMaterial();
  55088. var needUV = false;
  55089. // Alpha test
  55090. if (material) {
  55091. if (material.needAlphaTesting()) {
  55092. defines.push("#define ALPHATEST");
  55093. }
  55094. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55095. attribs.push(BABYLON.VertexBuffer.UVKind);
  55096. defines.push("#define UV1");
  55097. }
  55098. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55099. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55100. defines.push("#define UV2");
  55101. }
  55102. }
  55103. // Bones
  55104. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55105. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55106. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55107. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55108. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55109. }
  55110. else {
  55111. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55112. }
  55113. // Instances
  55114. if (useInstances) {
  55115. defines.push("#define INSTANCES");
  55116. attribs.push("world0");
  55117. attribs.push("world1");
  55118. attribs.push("world2");
  55119. attribs.push("world3");
  55120. }
  55121. // Get correct effect
  55122. var join = defines.join("\n");
  55123. if (this._cachedDefines !== join) {
  55124. this._cachedDefines = join;
  55125. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  55126. }
  55127. return this._volumetricLightScatteringPass.isReady();
  55128. };
  55129. /**
  55130. * Sets the new light position for light scattering effect
  55131. * @param {BABYLON.Vector3} The new custom light position
  55132. */
  55133. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  55134. this.customMeshPosition = position;
  55135. };
  55136. /**
  55137. * Returns the light position for light scattering effect
  55138. * @return {BABYLON.Vector3} The custom light position
  55139. */
  55140. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  55141. return this.customMeshPosition;
  55142. };
  55143. /**
  55144. * Disposes the internal assets and detaches the post-process from the camera
  55145. */
  55146. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  55147. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  55148. if (rttIndex !== -1) {
  55149. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  55150. }
  55151. this._volumetricLightScatteringRTT.dispose();
  55152. _super.prototype.dispose.call(this, camera);
  55153. };
  55154. /**
  55155. * Returns the render target texture used by the post-process
  55156. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  55157. */
  55158. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  55159. return this._volumetricLightScatteringRTT;
  55160. };
  55161. // Private methods
  55162. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  55163. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  55164. return true;
  55165. }
  55166. return false;
  55167. };
  55168. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  55169. var _this = this;
  55170. var engine = scene.getEngine();
  55171. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  55172. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55173. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55174. this._volumetricLightScatteringRTT.renderList = null;
  55175. this._volumetricLightScatteringRTT.renderParticles = false;
  55176. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  55177. // Custom render function for submeshes
  55178. var renderSubMesh = function (subMesh) {
  55179. var mesh = subMesh.getRenderingMesh();
  55180. if (_this._meshExcluded(mesh)) {
  55181. return;
  55182. }
  55183. var scene = mesh.getScene();
  55184. var engine = scene.getEngine();
  55185. // Culling
  55186. engine.setState(subMesh.getMaterial().backFaceCulling);
  55187. // Managing instances
  55188. var batch = mesh._getInstancesRenderList(subMesh._id);
  55189. if (batch.mustReturn) {
  55190. return;
  55191. }
  55192. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  55193. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  55194. var effect = _this._volumetricLightScatteringPass;
  55195. if (mesh === _this.mesh) {
  55196. effect = subMesh.getMaterial().getEffect();
  55197. }
  55198. engine.enableEffect(effect);
  55199. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  55200. if (mesh === _this.mesh) {
  55201. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  55202. }
  55203. else {
  55204. var material = subMesh.getMaterial();
  55205. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  55206. // Alpha test
  55207. if (material && material.needAlphaTesting()) {
  55208. var alphaTexture = material.getAlphaTestTexture();
  55209. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  55210. if (alphaTexture) {
  55211. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  55212. }
  55213. }
  55214. // Bones
  55215. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55216. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  55217. }
  55218. }
  55219. // Draw
  55220. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  55221. }
  55222. };
  55223. // Render target texture callbacks
  55224. var savedSceneClearColor;
  55225. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  55226. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  55227. savedSceneClearColor = scene.clearColor;
  55228. scene.clearColor = sceneClearColor;
  55229. });
  55230. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  55231. scene.clearColor = savedSceneClearColor;
  55232. });
  55233. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  55234. var engine = scene.getEngine();
  55235. var index;
  55236. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55237. renderSubMesh(opaqueSubMeshes.data[index]);
  55238. }
  55239. engine.setAlphaTesting(true);
  55240. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55241. renderSubMesh(alphaTestSubMeshes.data[index]);
  55242. }
  55243. engine.setAlphaTesting(false);
  55244. if (transparentSubMeshes.length) {
  55245. // Sort sub meshes
  55246. for (index = 0; index < transparentSubMeshes.length; index++) {
  55247. var submesh = transparentSubMeshes.data[index];
  55248. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  55249. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  55250. }
  55251. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  55252. sortedArray.sort(function (a, b) {
  55253. // Alpha index first
  55254. if (a._alphaIndex > b._alphaIndex) {
  55255. return 1;
  55256. }
  55257. if (a._alphaIndex < b._alphaIndex) {
  55258. return -1;
  55259. }
  55260. // Then distance to camera
  55261. if (a._distanceToCamera < b._distanceToCamera) {
  55262. return 1;
  55263. }
  55264. if (a._distanceToCamera > b._distanceToCamera) {
  55265. return -1;
  55266. }
  55267. return 0;
  55268. });
  55269. // Render sub meshes
  55270. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55271. for (index = 0; index < sortedArray.length; index++) {
  55272. renderSubMesh(sortedArray[index]);
  55273. }
  55274. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55275. }
  55276. };
  55277. };
  55278. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  55279. var transform = scene.getTransformMatrix();
  55280. var meshPosition;
  55281. if (this.useCustomMeshPosition) {
  55282. meshPosition = this.customMeshPosition;
  55283. }
  55284. else if (this.attachedNode) {
  55285. meshPosition = this.attachedNode.position;
  55286. }
  55287. else {
  55288. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  55289. }
  55290. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  55291. this._screenCoordinates.x = pos.x / this._viewPort.width;
  55292. this._screenCoordinates.y = pos.y / this._viewPort.height;
  55293. if (this.invert)
  55294. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  55295. };
  55296. // Static methods
  55297. /**
  55298. * Creates a default mesh for the Volumeric Light Scattering post-process
  55299. * @param {string} The mesh name
  55300. * @param {BABYLON.Scene} The scene where to create the mesh
  55301. * @return {BABYLON.Mesh} the default mesh
  55302. */
  55303. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  55304. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  55305. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55306. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  55307. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  55308. mesh.material = material;
  55309. return mesh;
  55310. };
  55311. __decorate([
  55312. BABYLON.serializeAsVector3()
  55313. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  55314. __decorate([
  55315. BABYLON.serialize()
  55316. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  55317. __decorate([
  55318. BABYLON.serialize()
  55319. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  55320. __decorate([
  55321. BABYLON.serializeAsMeshReference()
  55322. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  55323. __decorate([
  55324. BABYLON.serialize()
  55325. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  55326. __decorate([
  55327. BABYLON.serialize()
  55328. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  55329. __decorate([
  55330. BABYLON.serialize()
  55331. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  55332. __decorate([
  55333. BABYLON.serialize()
  55334. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  55335. __decorate([
  55336. BABYLON.serialize()
  55337. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  55338. return VolumetricLightScatteringPostProcess;
  55339. })(BABYLON.PostProcess);
  55340. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  55341. })(BABYLON || (BABYLON = {}));
  55342. // BABYLON.JS Chromatic Aberration GLSL Shader
  55343. // Author: Olivier Guyot
  55344. // Separates very slightly R, G and B colors on the edges of the screen
  55345. // Inspired by Francois Tarlier & Martins Upitis
  55346. var BABYLON;
  55347. (function (BABYLON) {
  55348. var LensRenderingPipeline = (function (_super) {
  55349. __extends(LensRenderingPipeline, _super);
  55350. /**
  55351. * @constructor
  55352. *
  55353. * Effect parameters are as follow:
  55354. * {
  55355. * chromatic_aberration: number; // from 0 to x (1 for realism)
  55356. * edge_blur: number; // from 0 to x (1 for realism)
  55357. * distortion: number; // from 0 to x (1 for realism)
  55358. * grain_amount: number; // from 0 to 1
  55359. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  55360. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  55361. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  55362. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  55363. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  55364. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  55365. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  55366. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  55367. * }
  55368. * Note: if an effect parameter is unset, effect is disabled
  55369. *
  55370. * @param {string} name - The rendering pipeline name
  55371. * @param {object} parameters - An object containing all parameters (see above)
  55372. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55373. * @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)
  55374. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55375. */
  55376. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  55377. var _this = this;
  55378. if (ratio === void 0) { ratio = 1.0; }
  55379. _super.call(this, scene.getEngine(), name);
  55380. // Lens effects can be of the following:
  55381. // - chromatic aberration (slight shift of RGB colors)
  55382. // - blur on the edge of the lens
  55383. // - lens distortion
  55384. // - depth-of-field blur & highlights enhancing
  55385. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  55386. // - grain effect (noise or custom texture)
  55387. // Two additional texture samplers are needed:
  55388. // - depth map (for depth-of-field)
  55389. // - grain texture
  55390. /**
  55391. * The chromatic aberration PostProcess id in the pipeline
  55392. * @type {string}
  55393. */
  55394. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  55395. /**
  55396. * The highlights enhancing PostProcess id in the pipeline
  55397. * @type {string}
  55398. */
  55399. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  55400. /**
  55401. * The depth-of-field PostProcess id in the pipeline
  55402. * @type {string}
  55403. */
  55404. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  55405. this._scene = scene;
  55406. // Fetch texture samplers
  55407. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  55408. if (parameters.grain_texture) {
  55409. this._grainTexture = parameters.grain_texture;
  55410. }
  55411. else {
  55412. this._createGrainTexture();
  55413. }
  55414. // save parameters
  55415. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  55416. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  55417. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  55418. this._distortion = parameters.distortion ? parameters.distortion : 0;
  55419. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  55420. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  55421. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  55422. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  55423. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  55424. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  55425. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  55426. // Create effects
  55427. this._createChromaticAberrationPostProcess(ratio);
  55428. this._createHighlightsPostProcess(ratio);
  55429. this._createDepthOfFieldPostProcess(ratio / 4);
  55430. // Set up pipeline
  55431. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  55432. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  55433. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  55434. if (this._highlightsGain === -1) {
  55435. this._disableEffect(this.HighlightsEnhancingEffect, null);
  55436. }
  55437. // Finish
  55438. scene.postProcessRenderPipelineManager.addPipeline(this);
  55439. if (cameras) {
  55440. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55441. }
  55442. }
  55443. // public methods (self explanatory)
  55444. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  55445. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  55446. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  55447. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  55448. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  55449. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  55450. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  55451. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  55452. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  55453. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  55454. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  55455. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  55456. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  55457. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  55458. };
  55459. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  55460. this._highlightsPostProcess.updateEffect();
  55461. };
  55462. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  55463. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  55464. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  55465. this._highlightsGain = amount;
  55466. };
  55467. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  55468. if (this._highlightsGain === -1) {
  55469. this._highlightsGain = 1.0;
  55470. }
  55471. this._highlightsThreshold = amount;
  55472. };
  55473. LensRenderingPipeline.prototype.disableHighlights = function () {
  55474. this._highlightsGain = -1;
  55475. };
  55476. /**
  55477. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  55478. */
  55479. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  55480. if (disableDepthRender === void 0) { disableDepthRender = false; }
  55481. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55482. this._chromaticAberrationPostProcess = undefined;
  55483. this._highlightsPostProcess = undefined;
  55484. this._depthOfFieldPostProcess = undefined;
  55485. this._grainTexture.dispose();
  55486. if (disableDepthRender)
  55487. this._scene.disableDepthRenderer();
  55488. };
  55489. // colors shifting and distortion
  55490. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  55491. var _this = this;
  55492. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  55493. [], // samplers
  55494. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  55495. this._chromaticAberrationPostProcess.onApply = function (effect) {
  55496. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  55497. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  55498. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  55499. };
  55500. };
  55501. // highlights enhancing
  55502. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  55503. var _this = this;
  55504. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  55505. [], // samplers
  55506. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  55507. this._highlightsPostProcess.onApply = function (effect) {
  55508. effect.setFloat('gain', _this._highlightsGain);
  55509. effect.setFloat('threshold', _this._highlightsThreshold);
  55510. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  55511. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  55512. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  55513. };
  55514. };
  55515. // colors shifting and distortion
  55516. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  55517. var _this = this;
  55518. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  55519. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  55520. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  55521. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  55522. this._depthOfFieldPostProcess.onApply = function (effect) {
  55523. effect.setTexture("depthSampler", _this._depthTexture);
  55524. effect.setTexture("grainSampler", _this._grainTexture);
  55525. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  55526. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  55527. effect.setFloat('grain_amount', _this._grainAmount);
  55528. effect.setBool('blur_noise', _this._blurNoise);
  55529. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  55530. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  55531. effect.setFloat('distortion', _this._distortion);
  55532. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  55533. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  55534. effect.setFloat('aperture', _this._dofAperture);
  55535. effect.setFloat('darken', _this._dofDarken);
  55536. effect.setFloat('edge_blur', _this._edgeBlur);
  55537. effect.setBool('highlights', (_this._highlightsGain !== -1));
  55538. effect.setFloat('near', _this._scene.activeCamera.minZ);
  55539. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  55540. };
  55541. };
  55542. // creates a black and white random noise texture, 512x512
  55543. LensRenderingPipeline.prototype._createGrainTexture = function () {
  55544. var size = 512;
  55545. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55546. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55547. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55548. var context = this._grainTexture.getContext();
  55549. var rand = function (min, max) {
  55550. return Math.random() * (max - min) + min;
  55551. };
  55552. var value;
  55553. for (var x = 0; x < size; x++) {
  55554. for (var y = 0; y < size; y++) {
  55555. value = Math.floor(rand(0.42, 0.58) * 255);
  55556. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  55557. context.fillRect(x, y, 1, 1);
  55558. }
  55559. }
  55560. this._grainTexture.update(false);
  55561. };
  55562. return LensRenderingPipeline;
  55563. })(BABYLON.PostProcessRenderPipeline);
  55564. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  55565. })(BABYLON || (BABYLON = {}));
  55566. //
  55567. // This post-process allows the modification of rendered colors by using
  55568. // a 'look-up table' (LUT). This effect is also called Color Grading.
  55569. //
  55570. // The object needs to be provided an url to a texture containing the color
  55571. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  55572. // Use an image editing software to tweak the LUT to match your needs.
  55573. //
  55574. // For an example of a color LUT, see here:
  55575. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  55576. // For explanations on color grading, see here:
  55577. // http://udn.epicgames.com/Three/ColorGrading.html
  55578. //
  55579. var BABYLON;
  55580. (function (BABYLON) {
  55581. var ColorCorrectionPostProcess = (function (_super) {
  55582. __extends(ColorCorrectionPostProcess, _super);
  55583. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  55584. var _this = this;
  55585. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  55586. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  55587. this._colorTableTexture.anisotropicFilteringLevel = 1;
  55588. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55589. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55590. this.onApply = function (effect) {
  55591. effect.setTexture("colorTable", _this._colorTableTexture);
  55592. };
  55593. }
  55594. return ColorCorrectionPostProcess;
  55595. })(BABYLON.PostProcess);
  55596. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  55597. })(BABYLON || (BABYLON = {}));
  55598. var BABYLON;
  55599. (function (BABYLON) {
  55600. var AnaglyphFreeCamera = (function (_super) {
  55601. __extends(AnaglyphFreeCamera, _super);
  55602. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  55603. _super.call(this, name, position, scene);
  55604. this.interaxialDistance = interaxialDistance;
  55605. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  55606. }
  55607. AnaglyphFreeCamera.prototype.getTypeName = function () {
  55608. return "AnaglyphFreeCamera";
  55609. };
  55610. return AnaglyphFreeCamera;
  55611. })(BABYLON.FreeCamera);
  55612. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  55613. var AnaglyphArcRotateCamera = (function (_super) {
  55614. __extends(AnaglyphArcRotateCamera, _super);
  55615. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  55616. _super.call(this, name, alpha, beta, radius, target, scene);
  55617. this.interaxialDistance = interaxialDistance;
  55618. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  55619. }
  55620. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  55621. return "AnaglyphArcRotateCamera";
  55622. };
  55623. return AnaglyphArcRotateCamera;
  55624. })(BABYLON.ArcRotateCamera);
  55625. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  55626. var AnaglyphGamepadCamera = (function (_super) {
  55627. __extends(AnaglyphGamepadCamera, _super);
  55628. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  55629. _super.call(this, name, position, scene);
  55630. this.interaxialDistance = interaxialDistance;
  55631. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  55632. }
  55633. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  55634. return "AnaglyphGamepadCamera";
  55635. };
  55636. return AnaglyphGamepadCamera;
  55637. })(BABYLON.GamepadCamera);
  55638. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  55639. var AnaglyphUniversalCamera = (function (_super) {
  55640. __extends(AnaglyphUniversalCamera, _super);
  55641. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  55642. _super.call(this, name, position, scene);
  55643. this.interaxialDistance = interaxialDistance;
  55644. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  55645. }
  55646. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  55647. return "AnaglyphUniversalCamera";
  55648. };
  55649. return AnaglyphUniversalCamera;
  55650. })(BABYLON.UniversalCamera);
  55651. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  55652. var StereoscopicFreeCamera = (function (_super) {
  55653. __extends(StereoscopicFreeCamera, _super);
  55654. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  55655. _super.call(this, name, position, scene);
  55656. this.interaxialDistance = interaxialDistance;
  55657. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  55658. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  55659. }
  55660. StereoscopicFreeCamera.prototype.getTypeName = function () {
  55661. return "StereoscopicFreeCamera";
  55662. };
  55663. return StereoscopicFreeCamera;
  55664. })(BABYLON.FreeCamera);
  55665. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  55666. var StereoscopicArcRotateCamera = (function (_super) {
  55667. __extends(StereoscopicArcRotateCamera, _super);
  55668. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  55669. _super.call(this, name, alpha, beta, radius, target, scene);
  55670. this.interaxialDistance = interaxialDistance;
  55671. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  55672. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  55673. }
  55674. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  55675. return "StereoscopicArcRotateCamera";
  55676. };
  55677. return StereoscopicArcRotateCamera;
  55678. })(BABYLON.ArcRotateCamera);
  55679. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  55680. var StereoscopicGamepadCamera = (function (_super) {
  55681. __extends(StereoscopicGamepadCamera, _super);
  55682. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  55683. _super.call(this, name, position, scene);
  55684. this.interaxialDistance = interaxialDistance;
  55685. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  55686. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  55687. }
  55688. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  55689. return "StereoscopicGamepadCamera";
  55690. };
  55691. return StereoscopicGamepadCamera;
  55692. })(BABYLON.GamepadCamera);
  55693. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  55694. var StereoscopicUniversalCamera = (function (_super) {
  55695. __extends(StereoscopicUniversalCamera, _super);
  55696. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  55697. _super.call(this, name, position, scene);
  55698. this.interaxialDistance = interaxialDistance;
  55699. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  55700. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  55701. }
  55702. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  55703. return "StereoscopicUniversalCamera";
  55704. };
  55705. return StereoscopicUniversalCamera;
  55706. })(BABYLON.UniversalCamera);
  55707. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  55708. })(BABYLON || (BABYLON = {}));
  55709. var BABYLON;
  55710. (function (BABYLON) {
  55711. var HDRRenderingPipeline = (function (_super) {
  55712. __extends(HDRRenderingPipeline, _super);
  55713. /**
  55714. * @constructor
  55715. * @param {string} name - The rendering pipeline name
  55716. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55717. * @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)
  55718. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  55719. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55720. */
  55721. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  55722. var _this = this;
  55723. if (originalPostProcess === void 0) { originalPostProcess = null; }
  55724. _super.call(this, scene.getEngine(), name);
  55725. /**
  55726. * Public members
  55727. */
  55728. // Gaussian Blur
  55729. /**
  55730. * Gaussian blur coefficient
  55731. * @type {number}
  55732. */
  55733. this.gaussCoeff = 0.3;
  55734. /**
  55735. * Gaussian blur mean
  55736. * @type {number}
  55737. */
  55738. this.gaussMean = 1.0;
  55739. /**
  55740. * Gaussian blur standard deviation
  55741. * @type {number}
  55742. */
  55743. this.gaussStandDev = 0.8;
  55744. /**
  55745. * Gaussian blur multiplier. Multiplies the blur effect
  55746. * @type {number}
  55747. */
  55748. this.gaussMultiplier = 4.0;
  55749. // HDR
  55750. /**
  55751. * Exposure, controls the overall intensity of the pipeline
  55752. * @type {number}
  55753. */
  55754. this.exposure = 1.0;
  55755. /**
  55756. * Minimum luminance that the post-process can output. Luminance is >= 0
  55757. * @type {number}
  55758. */
  55759. this.minimumLuminance = 1.0;
  55760. /**
  55761. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  55762. * @type {number}
  55763. */
  55764. this.maximumLuminance = 1e20;
  55765. /**
  55766. * Increase rate for luminance: eye adaptation speed to dark
  55767. * @type {number}
  55768. */
  55769. this.luminanceIncreaserate = 0.5;
  55770. /**
  55771. * Decrease rate for luminance: eye adaptation speed to bright
  55772. * @type {number}
  55773. */
  55774. this.luminanceDecreaseRate = 0.5;
  55775. // Bright pass
  55776. /**
  55777. * Minimum luminance needed to compute HDR
  55778. * @type {number}
  55779. */
  55780. this.brightThreshold = 0.8;
  55781. this._needUpdate = true;
  55782. this._scene = scene;
  55783. // Bright pass
  55784. this._createBrightPassPostProcess(scene, ratio);
  55785. // Down sample X4
  55786. this._createDownSampleX4PostProcess(scene, ratio);
  55787. // Create gaussian blur post-processes
  55788. this._createGaussianBlurPostProcess(scene, ratio);
  55789. // Texture adder
  55790. this._createTextureAdderPostProcess(scene, ratio);
  55791. // Luminance generator
  55792. this._createLuminanceGeneratorPostProcess(scene);
  55793. // HDR
  55794. this._createHDRPostProcess(scene, ratio);
  55795. // Pass postprocess
  55796. if (originalPostProcess === null) {
  55797. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  55798. }
  55799. else {
  55800. this._originalPostProcess = originalPostProcess;
  55801. }
  55802. // Configure pipeline
  55803. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  55804. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  55805. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  55806. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  55807. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  55808. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  55809. var addDownSamplerPostProcess = function (id) {
  55810. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  55811. };
  55812. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  55813. addDownSamplerPostProcess(i);
  55814. }
  55815. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  55816. // Finish
  55817. scene.postProcessRenderPipelineManager.addPipeline(this);
  55818. if (cameras !== null) {
  55819. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55820. }
  55821. this.update();
  55822. }
  55823. /**
  55824. * Tells the pipeline to update its post-processes
  55825. */
  55826. HDRRenderingPipeline.prototype.update = function () {
  55827. this._needUpdate = true;
  55828. };
  55829. /**
  55830. * Returns the current calculated luminance
  55831. */
  55832. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  55833. return this._hdrCurrentLuminance;
  55834. };
  55835. /**
  55836. * Returns the currently drawn luminance
  55837. */
  55838. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  55839. return this._hdrOutputLuminance;
  55840. };
  55841. /**
  55842. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  55843. */
  55844. HDRRenderingPipeline.prototype.dispose = function () {
  55845. this._originalPostProcess = undefined;
  55846. this._brightPassPostProcess = undefined;
  55847. this._downSampleX4PostProcess = undefined;
  55848. this._guassianBlurHPostProcess = undefined;
  55849. this._guassianBlurVPostProcess = undefined;
  55850. this._textureAdderPostProcess = undefined;
  55851. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  55852. this._downSamplePostProcesses[i] = undefined;
  55853. }
  55854. this._hdrPostProcess = undefined;
  55855. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55856. };
  55857. /**
  55858. * Creates the HDR post-process and computes the luminance adaptation
  55859. */
  55860. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  55861. var _this = this;
  55862. var hdrLastLuminance = 0.0;
  55863. this._hdrOutputLuminance = -1.0;
  55864. this._hdrCurrentLuminance = 1.0;
  55865. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  55866. this._hdrPostProcess.onApply = function (effect) {
  55867. if (_this._hdrOutputLuminance < 0.0) {
  55868. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  55869. }
  55870. else {
  55871. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  55872. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  55873. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  55874. }
  55875. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  55876. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  55877. }
  55878. else {
  55879. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  55880. }
  55881. }
  55882. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  55883. hdrLastLuminance += scene.getEngine().getDeltaTime();
  55884. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  55885. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  55886. effect.setFloat("exposure", _this.exposure);
  55887. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  55888. _this._needUpdate = false;
  55889. };
  55890. };
  55891. /**
  55892. * Texture Adder post-process
  55893. */
  55894. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  55895. var _this = this;
  55896. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  55897. this._textureAdderPostProcess.onApply = function (effect) {
  55898. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  55899. };
  55900. };
  55901. /**
  55902. * Down sample X4 post-process
  55903. */
  55904. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  55905. var _this = this;
  55906. var downSampleX4Offsets = new Array(32);
  55907. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  55908. this._downSampleX4PostProcess.onApply = function (effect) {
  55909. if (_this._needUpdate) {
  55910. var id = 0;
  55911. for (var i = -2; i < 2; i++) {
  55912. for (var j = -2; j < 2; j++) {
  55913. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  55914. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  55915. id += 2;
  55916. }
  55917. }
  55918. }
  55919. effect.setArray2("dsOffsets", downSampleX4Offsets);
  55920. };
  55921. };
  55922. /**
  55923. * Bright pass post-process
  55924. */
  55925. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  55926. var _this = this;
  55927. var brightOffsets = new Array(8);
  55928. var brightPassCallback = function (effect) {
  55929. if (_this._needUpdate) {
  55930. var sU = (1.0 / _this._brightPassPostProcess.width);
  55931. var sV = (1.0 / _this._brightPassPostProcess.height);
  55932. brightOffsets[0] = -0.5 * sU;
  55933. brightOffsets[1] = 0.5 * sV;
  55934. brightOffsets[2] = 0.5 * sU;
  55935. brightOffsets[3] = 0.5 * sV;
  55936. brightOffsets[4] = -0.5 * sU;
  55937. brightOffsets[5] = -0.5 * sV;
  55938. brightOffsets[6] = 0.5 * sU;
  55939. brightOffsets[7] = -0.5 * sV;
  55940. }
  55941. effect.setArray2("dsOffsets", brightOffsets);
  55942. effect.setFloat("brightThreshold", _this.brightThreshold);
  55943. };
  55944. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  55945. this._brightPassPostProcess.onApply = brightPassCallback;
  55946. };
  55947. /**
  55948. * Luminance generator. Creates the luminance post-process and down sample post-processes
  55949. */
  55950. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  55951. var _this = this;
  55952. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  55953. var luminanceOffsets = new Array(8);
  55954. var downSampleOffsets = new Array(18);
  55955. var halfDestPixelSize;
  55956. this._downSamplePostProcesses = new Array(lumSteps);
  55957. // Utils for luminance
  55958. var luminanceUpdateSourceOffsets = function (width, height) {
  55959. var sU = (1.0 / width);
  55960. var sV = (1.0 / height);
  55961. luminanceOffsets[0] = -0.5 * sU;
  55962. luminanceOffsets[1] = 0.5 * sV;
  55963. luminanceOffsets[2] = 0.5 * sU;
  55964. luminanceOffsets[3] = 0.5 * sV;
  55965. luminanceOffsets[4] = -0.5 * sU;
  55966. luminanceOffsets[5] = -0.5 * sV;
  55967. luminanceOffsets[6] = 0.5 * sU;
  55968. luminanceOffsets[7] = -0.5 * sV;
  55969. };
  55970. var luminanceUpdateDestOffsets = function (width, height) {
  55971. var id = 0;
  55972. for (var x = -1; x < 2; x++) {
  55973. for (var y = -1; y < 2; y++) {
  55974. downSampleOffsets[id] = (x) / width;
  55975. downSampleOffsets[id + 1] = (y) / height;
  55976. id += 2;
  55977. }
  55978. }
  55979. };
  55980. // Luminance callback
  55981. var luminanceCallback = function (effect) {
  55982. if (_this._needUpdate) {
  55983. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  55984. }
  55985. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  55986. effect.setArray2("lumOffsets", luminanceOffsets);
  55987. };
  55988. // Down sample callbacks
  55989. var downSampleCallback = function (indice) {
  55990. var i = indice;
  55991. return function (effect) {
  55992. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  55993. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  55994. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  55995. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  55996. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  55997. effect.setArray2("dsOffsets", downSampleOffsets);
  55998. };
  55999. };
  56000. var downSampleAfterRenderCallback = function (effect) {
  56001. // Unpack result
  56002. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  56003. 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);
  56004. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  56005. };
  56006. // Create luminance post-process
  56007. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  56008. 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);
  56009. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  56010. // Create down sample post-processes
  56011. for (var i = lumSteps - 2; i >= 0; i--) {
  56012. var length = Math.pow(3, i);
  56013. ratio = { width: length, height: length };
  56014. var defines = "#define DOWN_SAMPLE\n";
  56015. if (i === 0) {
  56016. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  56017. }
  56018. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  56019. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  56020. if (i === 0) {
  56021. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  56022. }
  56023. }
  56024. };
  56025. /**
  56026. * Gaussian blur post-processes. Horizontal and Vertical
  56027. */
  56028. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  56029. var _this = this;
  56030. var blurOffsetsW = new Array(9);
  56031. var blurOffsetsH = new Array(9);
  56032. var blurWeights = new Array(9);
  56033. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  56034. // Utils for gaussian blur
  56035. var calculateBlurOffsets = function (height) {
  56036. var lastOutputDimensions = {
  56037. width: scene.getEngine().getRenderWidth(),
  56038. height: scene.getEngine().getRenderHeight()
  56039. };
  56040. for (var i = 0; i < 9; i++) {
  56041. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  56042. if (height) {
  56043. blurOffsetsH[i] = value;
  56044. }
  56045. else {
  56046. blurOffsetsW[i] = value;
  56047. }
  56048. }
  56049. };
  56050. var calculateWeights = function () {
  56051. var x = 0.0;
  56052. for (var i = 0; i < 9; i++) {
  56053. x = (i - 4.0) / 4.0;
  56054. 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));
  56055. }
  56056. };
  56057. // Callback
  56058. var gaussianBlurCallback = function (height) {
  56059. return function (effect) {
  56060. if (_this._needUpdate) {
  56061. calculateWeights();
  56062. calculateBlurOffsets(height);
  56063. }
  56064. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  56065. effect.setArray("blurWeights", blurWeights);
  56066. effect.setFloat("multiplier", _this.gaussMultiplier);
  56067. };
  56068. };
  56069. // Create horizontal gaussian blur post-processes
  56070. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  56071. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  56072. // Create vertical gaussian blur post-process
  56073. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  56074. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  56075. };
  56076. // Luminance generator
  56077. HDRRenderingPipeline.LUM_STEPS = 6;
  56078. return HDRRenderingPipeline;
  56079. })(BABYLON.PostProcessRenderPipeline);
  56080. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  56081. })(BABYLON || (BABYLON = {}));
  56082. var BABYLON;
  56083. (function (BABYLON) {
  56084. var FaceAdjacencies = (function () {
  56085. function FaceAdjacencies() {
  56086. this.edges = new Array();
  56087. this.edgesConnectedCount = 0;
  56088. }
  56089. return FaceAdjacencies;
  56090. })();
  56091. var EdgesRenderer = (function () {
  56092. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  56093. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  56094. if (epsilon === void 0) { epsilon = 0.95; }
  56095. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  56096. this.edgesWidthScalerForOrthographic = 1000.0;
  56097. this.edgesWidthScalerForPerspective = 50.0;
  56098. this._linesPositions = new Array();
  56099. this._linesNormals = new Array();
  56100. this._linesIndices = new Array();
  56101. this._buffers = {};
  56102. this._checkVerticesInsteadOfIndices = false;
  56103. this._source = source;
  56104. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  56105. this._epsilon = epsilon;
  56106. this._prepareRessources();
  56107. this._generateEdgesLines();
  56108. }
  56109. EdgesRenderer.prototype._prepareRessources = function () {
  56110. if (this._lineShader) {
  56111. return;
  56112. }
  56113. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  56114. attributes: ["position", "normal"],
  56115. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  56116. });
  56117. this._lineShader.disableDepthWrite = true;
  56118. this._lineShader.backFaceCulling = false;
  56119. };
  56120. EdgesRenderer.prototype.dispose = function () {
  56121. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  56122. if (buffer) {
  56123. buffer.dispose();
  56124. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  56125. }
  56126. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  56127. if (buffer) {
  56128. buffer.dispose();
  56129. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  56130. }
  56131. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  56132. this._lineShader.dispose();
  56133. };
  56134. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  56135. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  56136. return 0;
  56137. }
  56138. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  56139. return 1;
  56140. }
  56141. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  56142. return 2;
  56143. }
  56144. return -1;
  56145. };
  56146. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  56147. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  56148. return 0;
  56149. }
  56150. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  56151. return 1;
  56152. }
  56153. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  56154. return 2;
  56155. }
  56156. return -1;
  56157. };
  56158. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  56159. var needToCreateLine;
  56160. if (edge === undefined) {
  56161. needToCreateLine = true;
  56162. }
  56163. else {
  56164. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  56165. needToCreateLine = dotProduct < this._epsilon;
  56166. }
  56167. if (needToCreateLine) {
  56168. var offset = this._linesPositions.length / 3;
  56169. var normal = p0.subtract(p1);
  56170. normal.normalize();
  56171. // Positions
  56172. this._linesPositions.push(p0.x);
  56173. this._linesPositions.push(p0.y);
  56174. this._linesPositions.push(p0.z);
  56175. this._linesPositions.push(p0.x);
  56176. this._linesPositions.push(p0.y);
  56177. this._linesPositions.push(p0.z);
  56178. this._linesPositions.push(p1.x);
  56179. this._linesPositions.push(p1.y);
  56180. this._linesPositions.push(p1.z);
  56181. this._linesPositions.push(p1.x);
  56182. this._linesPositions.push(p1.y);
  56183. this._linesPositions.push(p1.z);
  56184. // Normals
  56185. this._linesNormals.push(p1.x);
  56186. this._linesNormals.push(p1.y);
  56187. this._linesNormals.push(p1.z);
  56188. this._linesNormals.push(-1);
  56189. this._linesNormals.push(p1.x);
  56190. this._linesNormals.push(p1.y);
  56191. this._linesNormals.push(p1.z);
  56192. this._linesNormals.push(1);
  56193. this._linesNormals.push(p0.x);
  56194. this._linesNormals.push(p0.y);
  56195. this._linesNormals.push(p0.z);
  56196. this._linesNormals.push(-1);
  56197. this._linesNormals.push(p0.x);
  56198. this._linesNormals.push(p0.y);
  56199. this._linesNormals.push(p0.z);
  56200. this._linesNormals.push(1);
  56201. // Indices
  56202. this._linesIndices.push(offset);
  56203. this._linesIndices.push(offset + 1);
  56204. this._linesIndices.push(offset + 2);
  56205. this._linesIndices.push(offset);
  56206. this._linesIndices.push(offset + 2);
  56207. this._linesIndices.push(offset + 3);
  56208. }
  56209. };
  56210. EdgesRenderer.prototype._generateEdgesLines = function () {
  56211. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56212. var indices = this._source.getIndices();
  56213. // First let's find adjacencies
  56214. var adjacencies = new Array();
  56215. var faceNormals = new Array();
  56216. var index;
  56217. var faceAdjacencies;
  56218. // Prepare faces
  56219. for (index = 0; index < indices.length; index += 3) {
  56220. faceAdjacencies = new FaceAdjacencies();
  56221. var p0Index = indices[index];
  56222. var p1Index = indices[index + 1];
  56223. var p2Index = indices[index + 2];
  56224. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  56225. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  56226. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  56227. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  56228. faceNormal.normalize();
  56229. faceNormals.push(faceNormal);
  56230. adjacencies.push(faceAdjacencies);
  56231. }
  56232. // Scan
  56233. for (index = 0; index < adjacencies.length; index++) {
  56234. faceAdjacencies = adjacencies[index];
  56235. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  56236. var otherFaceAdjacencies = adjacencies[otherIndex];
  56237. if (faceAdjacencies.edgesConnectedCount === 3) {
  56238. break;
  56239. }
  56240. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  56241. continue;
  56242. }
  56243. var otherP0 = indices[otherIndex * 3];
  56244. var otherP1 = indices[otherIndex * 3 + 1];
  56245. var otherP2 = indices[otherIndex * 3 + 2];
  56246. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  56247. var otherEdgeIndex;
  56248. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  56249. continue;
  56250. }
  56251. switch (edgeIndex) {
  56252. case 0:
  56253. if (this._checkVerticesInsteadOfIndices) {
  56254. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  56255. }
  56256. else {
  56257. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  56258. }
  56259. break;
  56260. case 1:
  56261. if (this._checkVerticesInsteadOfIndices) {
  56262. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  56263. }
  56264. else {
  56265. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  56266. }
  56267. break;
  56268. case 2:
  56269. if (this._checkVerticesInsteadOfIndices) {
  56270. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  56271. }
  56272. else {
  56273. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  56274. }
  56275. break;
  56276. }
  56277. if (otherEdgeIndex === -1) {
  56278. continue;
  56279. }
  56280. faceAdjacencies.edges[edgeIndex] = otherIndex;
  56281. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  56282. faceAdjacencies.edgesConnectedCount++;
  56283. otherFaceAdjacencies.edgesConnectedCount++;
  56284. if (faceAdjacencies.edgesConnectedCount === 3) {
  56285. break;
  56286. }
  56287. }
  56288. }
  56289. }
  56290. // Create lines
  56291. for (index = 0; index < adjacencies.length; index++) {
  56292. // 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
  56293. var current = adjacencies[index];
  56294. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  56295. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  56296. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  56297. }
  56298. // Merge into a single mesh
  56299. var engine = this._source.getScene().getEngine();
  56300. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  56301. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  56302. this._ib = engine.createIndexBuffer(this._linesIndices);
  56303. this._indicesCount = this._linesIndices.length;
  56304. };
  56305. EdgesRenderer.prototype.render = function () {
  56306. if (!this._lineShader.isReady()) {
  56307. return;
  56308. }
  56309. var scene = this._source.getScene();
  56310. var engine = scene.getEngine();
  56311. this._lineShader._preBind();
  56312. // VBOs
  56313. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  56314. scene.resetCachedMaterial();
  56315. this._lineShader.setColor4("color", this._source.edgesColor);
  56316. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  56317. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  56318. }
  56319. else {
  56320. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  56321. }
  56322. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  56323. this._lineShader.bind(this._source.getWorldMatrix());
  56324. // Draw order
  56325. engine.draw(true, 0, this._indicesCount);
  56326. this._lineShader.unbind();
  56327. engine.setDepthWrite(true);
  56328. };
  56329. return EdgesRenderer;
  56330. })();
  56331. BABYLON.EdgesRenderer = EdgesRenderer;
  56332. })(BABYLON || (BABYLON = {}));
  56333. var BABYLON;
  56334. (function (BABYLON) {
  56335. (function (TonemappingOperator) {
  56336. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  56337. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  56338. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  56339. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  56340. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  56341. var TonemappingOperator = BABYLON.TonemappingOperator;
  56342. ;
  56343. var TonemapPostProcess = (function (_super) {
  56344. __extends(TonemapPostProcess, _super);
  56345. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  56346. var _this = this;
  56347. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  56348. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56349. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  56350. this._operator = _operator;
  56351. this.exposureAdjustment = exposureAdjustment;
  56352. var defines = "#define ";
  56353. if (this._operator === TonemappingOperator.Hable)
  56354. defines += "HABLE_TONEMAPPING";
  56355. else if (this._operator === TonemappingOperator.Reinhard)
  56356. defines += "REINHARD_TONEMAPPING";
  56357. else if (this._operator === TonemappingOperator.HejiDawson)
  56358. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  56359. else if (this._operator === TonemappingOperator.Photographic)
  56360. defines += "PHOTOGRAPHIC_TONEMAPPING";
  56361. //sadly a second call to create the effect.
  56362. this.updateEffect(defines);
  56363. this.onApply = function (effect) {
  56364. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  56365. };
  56366. }
  56367. return TonemapPostProcess;
  56368. })(BABYLON.PostProcess);
  56369. BABYLON.TonemapPostProcess = TonemapPostProcess;
  56370. })(BABYLON || (BABYLON = {}));
  56371. var BABYLON;
  56372. (function (BABYLON) {
  56373. var ReflectionProbe = (function () {
  56374. function ReflectionProbe(name, size, scene, generateMipMaps) {
  56375. var _this = this;
  56376. if (generateMipMaps === void 0) { generateMipMaps = true; }
  56377. this.name = name;
  56378. this._viewMatrix = BABYLON.Matrix.Identity();
  56379. this._target = BABYLON.Vector3.Zero();
  56380. this._add = BABYLON.Vector3.Zero();
  56381. this.invertYAxis = false;
  56382. this.position = BABYLON.Vector3.Zero();
  56383. this._scene = scene;
  56384. this._scene.reflectionProbes.push(this);
  56385. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  56386. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  56387. switch (faceIndex) {
  56388. case 0:
  56389. _this._add.copyFromFloats(1, 0, 0);
  56390. break;
  56391. case 1:
  56392. _this._add.copyFromFloats(-1, 0, 0);
  56393. break;
  56394. case 2:
  56395. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  56396. break;
  56397. case 3:
  56398. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  56399. break;
  56400. case 4:
  56401. _this._add.copyFromFloats(0, 0, 1);
  56402. break;
  56403. case 5:
  56404. _this._add.copyFromFloats(0, 0, -1);
  56405. break;
  56406. }
  56407. if (_this._attachedMesh) {
  56408. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  56409. }
  56410. _this.position.addToRef(_this._add, _this._target);
  56411. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  56412. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  56413. });
  56414. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  56415. scene.updateTransformMatrix(true);
  56416. });
  56417. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  56418. }
  56419. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  56420. get: function () {
  56421. return this._renderTargetTexture.refreshRate;
  56422. },
  56423. set: function (value) {
  56424. this._renderTargetTexture.refreshRate = value;
  56425. },
  56426. enumerable: true,
  56427. configurable: true
  56428. });
  56429. ReflectionProbe.prototype.getScene = function () {
  56430. return this._scene;
  56431. };
  56432. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  56433. get: function () {
  56434. return this._renderTargetTexture;
  56435. },
  56436. enumerable: true,
  56437. configurable: true
  56438. });
  56439. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  56440. get: function () {
  56441. return this._renderTargetTexture.renderList;
  56442. },
  56443. enumerable: true,
  56444. configurable: true
  56445. });
  56446. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  56447. this._attachedMesh = mesh;
  56448. };
  56449. ReflectionProbe.prototype.dispose = function () {
  56450. var index = this._scene.reflectionProbes.indexOf(this);
  56451. if (index !== -1) {
  56452. // Remove from the scene if found
  56453. this._scene.reflectionProbes.splice(index, 1);
  56454. }
  56455. if (this._renderTargetTexture) {
  56456. this._renderTargetTexture.dispose();
  56457. this._renderTargetTexture = null;
  56458. }
  56459. };
  56460. return ReflectionProbe;
  56461. })();
  56462. BABYLON.ReflectionProbe = ReflectionProbe;
  56463. })(BABYLON || (BABYLON = {}));
  56464. var BABYLON;
  56465. (function (BABYLON) {
  56466. var SolidParticle = (function () {
  56467. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  56468. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  56469. this.position = BABYLON.Vector3.Zero(); // position
  56470. this.rotation = BABYLON.Vector3.Zero(); // rotation
  56471. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  56472. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  56473. this.velocity = BABYLON.Vector3.Zero(); // velocity
  56474. this.alive = true; // alive
  56475. this.isVisible = true; // visibility
  56476. this.idx = particleIndex;
  56477. this._pos = positionIndex;
  56478. this._model = model;
  56479. this.shapeId = shapeId;
  56480. this.idxInShape = idxInShape;
  56481. }
  56482. Object.defineProperty(SolidParticle.prototype, "scale", {
  56483. //legacy support, changed scale to scaling
  56484. get: function () {
  56485. return this.scaling;
  56486. },
  56487. set: function (scale) {
  56488. this.scaling = scale;
  56489. },
  56490. enumerable: true,
  56491. configurable: true
  56492. });
  56493. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  56494. //legacy support, changed quaternion to rotationQuaternion
  56495. get: function () {
  56496. return this.rotationQuaternion;
  56497. },
  56498. set: function (q) {
  56499. this.rotationQuaternion = q;
  56500. },
  56501. enumerable: true,
  56502. configurable: true
  56503. });
  56504. return SolidParticle;
  56505. })();
  56506. BABYLON.SolidParticle = SolidParticle;
  56507. var ModelShape = (function () {
  56508. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  56509. this.shapeID = id;
  56510. this._shape = shape;
  56511. this._shapeUV = shapeUV;
  56512. this._positionFunction = posFunction;
  56513. this._vertexFunction = vtxFunction;
  56514. }
  56515. return ModelShape;
  56516. })();
  56517. BABYLON.ModelShape = ModelShape;
  56518. })(BABYLON || (BABYLON = {}));
  56519. var BABYLON;
  56520. (function (BABYLON) {
  56521. /**
  56522. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  56523. */
  56524. var SolidParticleSystem = (function () {
  56525. /**
  56526. * Creates a SPS (Solid Particle System) object.
  56527. * `name` (String) is the SPS name, this will be the underlying mesh name.
  56528. * `scene` (Scene) is the scene in which the SPS is added.
  56529. * `updatable` (default true) : if the SPS must be updatable or immutable.
  56530. * `isPickable` (default false) : if the solid particles must be pickable.
  56531. */
  56532. function SolidParticleSystem(name, scene, options) {
  56533. // public members
  56534. /**
  56535. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  56536. * Example : var p = SPS.particles[i];
  56537. */
  56538. this.particles = new Array();
  56539. /**
  56540. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  56541. */
  56542. this.nbParticles = 0;
  56543. /**
  56544. * If the particles must ever face the camera (default false). Useful for planar particles.
  56545. */
  56546. this.billboard = false;
  56547. /**
  56548. * This a counter ofr your own usage. It's not set by any SPS functions.
  56549. */
  56550. this.counter = 0;
  56551. /**
  56552. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  56553. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  56554. */
  56555. this.vars = {};
  56556. this._positions = new Array();
  56557. this._indices = new Array();
  56558. this._normals = new Array();
  56559. this._colors = new Array();
  56560. this._uvs = new Array();
  56561. this._index = 0; // indices index
  56562. this._updatable = true;
  56563. this._pickable = false;
  56564. this._isVisibilityBoxLocked = false;
  56565. this._alwaysVisible = false;
  56566. this._shapeCounter = 0;
  56567. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  56568. this._color = new BABYLON.Color4(0, 0, 0, 0);
  56569. this._computeParticleColor = true;
  56570. this._computeParticleTexture = true;
  56571. this._computeParticleRotation = true;
  56572. this._computeParticleVertex = false;
  56573. this._computeBoundingBox = false;
  56574. this._cam_axisZ = BABYLON.Vector3.Zero();
  56575. this._cam_axisY = BABYLON.Vector3.Zero();
  56576. this._cam_axisX = BABYLON.Vector3.Zero();
  56577. this._axisX = BABYLON.Axis.X;
  56578. this._axisY = BABYLON.Axis.Y;
  56579. this._axisZ = BABYLON.Axis.Z;
  56580. this._camDir = BABYLON.Vector3.Zero();
  56581. this._rotMatrix = new BABYLON.Matrix();
  56582. this._invertMatrix = new BABYLON.Matrix();
  56583. this._rotated = BABYLON.Vector3.Zero();
  56584. this._quaternion = new BABYLON.Quaternion();
  56585. this._vertex = BABYLON.Vector3.Zero();
  56586. this._normal = BABYLON.Vector3.Zero();
  56587. this._yaw = 0.0;
  56588. this._pitch = 0.0;
  56589. this._roll = 0.0;
  56590. this._halfroll = 0.0;
  56591. this._halfpitch = 0.0;
  56592. this._halfyaw = 0.0;
  56593. this._sinRoll = 0.0;
  56594. this._cosRoll = 0.0;
  56595. this._sinPitch = 0.0;
  56596. this._cosPitch = 0.0;
  56597. this._sinYaw = 0.0;
  56598. this._cosYaw = 0.0;
  56599. this._w = 0.0;
  56600. this._minimum = BABYLON.Tmp.Vector3[0];
  56601. this._maximum = BABYLON.Tmp.Vector3[1];
  56602. this.name = name;
  56603. this._scene = scene;
  56604. this._camera = scene.activeCamera;
  56605. this._pickable = options ? options.isPickable : false;
  56606. if (options && options.updatable) {
  56607. this._updatable = options.updatable;
  56608. }
  56609. else {
  56610. this._updatable = true;
  56611. }
  56612. if (this._pickable) {
  56613. this.pickedParticles = [];
  56614. }
  56615. }
  56616. /**
  56617. * Builds the SPS underlying mesh. Returns a standard Mesh.
  56618. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  56619. */
  56620. SolidParticleSystem.prototype.buildMesh = function () {
  56621. if (this.nbParticles === 0) {
  56622. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  56623. this.addShape(triangle, 1);
  56624. triangle.dispose();
  56625. }
  56626. this._positions32 = new Float32Array(this._positions);
  56627. this._uvs32 = new Float32Array(this._uvs);
  56628. this._colors32 = new Float32Array(this._colors);
  56629. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  56630. this._normals32 = new Float32Array(this._normals);
  56631. this._fixedNormal32 = new Float32Array(this._normals);
  56632. var vertexData = new BABYLON.VertexData();
  56633. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  56634. vertexData.indices = this._indices;
  56635. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  56636. if (this._uvs32) {
  56637. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  56638. ;
  56639. }
  56640. if (this._colors32) {
  56641. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  56642. }
  56643. var mesh = new BABYLON.Mesh(this.name, this._scene);
  56644. vertexData.applyToMesh(mesh, this._updatable);
  56645. this.mesh = mesh;
  56646. this.mesh.isPickable = this._pickable;
  56647. // free memory
  56648. this._positions = null;
  56649. this._normals = null;
  56650. this._uvs = null;
  56651. this._colors = null;
  56652. if (!this._updatable) {
  56653. this.particles.length = 0;
  56654. }
  56655. return mesh;
  56656. };
  56657. /**
  56658. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  56659. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  56660. * Thus the particles generated from `digest()` have their property `position` set yet.
  56661. * `mesh` ( Mesh ) is the mesh to be digested
  56662. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  56663. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  56664. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  56665. */
  56666. SolidParticleSystem.prototype.digest = function (mesh, options) {
  56667. var size = (options && options.facetNb) || 1;
  56668. var number = (options && options.number);
  56669. var delta = (options && options.delta) || 0;
  56670. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56671. var meshInd = mesh.getIndices();
  56672. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56673. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56674. var f = 0; // facet counter
  56675. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  56676. // compute size from number
  56677. if (number) {
  56678. number = (number > totalFacets) ? totalFacets : number;
  56679. size = Math.round(totalFacets / number);
  56680. delta = 0;
  56681. }
  56682. else {
  56683. size = (size > totalFacets) ? totalFacets : size;
  56684. }
  56685. var facetPos = []; // submesh positions
  56686. var facetInd = []; // submesh indices
  56687. var facetUV = []; // submesh UV
  56688. var facetCol = []; // submesh colors
  56689. var barycenter = BABYLON.Tmp.Vector3[0];
  56690. var rand;
  56691. var sizeO = size;
  56692. while (f < totalFacets) {
  56693. size = sizeO + Math.floor((1 + delta) * Math.random());
  56694. if (f > totalFacets - size) {
  56695. size = totalFacets - f;
  56696. }
  56697. // reset temp arrays
  56698. facetPos.length = 0;
  56699. facetInd.length = 0;
  56700. facetUV.length = 0;
  56701. facetCol.length = 0;
  56702. // iterate over "size" facets
  56703. var fi = 0;
  56704. for (var j = f * 3; j < (f + size) * 3; j++) {
  56705. facetInd.push(fi);
  56706. var i = meshInd[j];
  56707. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  56708. if (meshUV) {
  56709. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  56710. }
  56711. if (meshCol) {
  56712. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  56713. }
  56714. fi++;
  56715. }
  56716. // create a model shape for each single particle
  56717. var idx = this.nbParticles;
  56718. var shape = this._posToShape(facetPos);
  56719. var shapeUV = this._uvsToShapeUV(facetUV);
  56720. // compute the barycenter of the shape
  56721. var v;
  56722. for (v = 0; v < shape.length; v++) {
  56723. barycenter.addInPlace(shape[v]);
  56724. }
  56725. barycenter.scaleInPlace(1 / shape.length);
  56726. // shift the shape from its barycenter to the origin
  56727. for (v = 0; v < shape.length; v++) {
  56728. shape[v].subtractInPlace(barycenter);
  56729. }
  56730. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  56731. // add the particle in the SPS
  56732. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  56733. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  56734. // initialize the particle position
  56735. this.particles[this.nbParticles].position.addInPlace(barycenter);
  56736. this._index += shape.length;
  56737. idx++;
  56738. this.nbParticles++;
  56739. this._shapeCounter++;
  56740. f += size;
  56741. }
  56742. return this;
  56743. };
  56744. //reset copy
  56745. SolidParticleSystem.prototype._resetCopy = function () {
  56746. this._copy.position.x = 0;
  56747. this._copy.position.y = 0;
  56748. this._copy.position.z = 0;
  56749. this._copy.rotation.x = 0;
  56750. this._copy.rotation.y = 0;
  56751. this._copy.rotation.z = 0;
  56752. this._copy.rotationQuaternion = null;
  56753. this._copy.scaling.x = 1;
  56754. this._copy.scaling.y = 1;
  56755. this._copy.scaling.z = 1;
  56756. this._copy.uvs.x = 0;
  56757. this._copy.uvs.y = 0;
  56758. this._copy.uvs.z = 1;
  56759. this._copy.uvs.w = 1;
  56760. this._copy.color = null;
  56761. };
  56762. // _meshBuilder : inserts the shape model in the global SPS mesh
  56763. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  56764. var i;
  56765. var u = 0;
  56766. var c = 0;
  56767. this._resetCopy();
  56768. if (options && options.positionFunction) {
  56769. options.positionFunction(this._copy, idx, idxInShape);
  56770. }
  56771. if (this._copy.rotationQuaternion) {
  56772. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  56773. }
  56774. else {
  56775. this._yaw = this._copy.rotation.y;
  56776. this._pitch = this._copy.rotation.x;
  56777. this._roll = this._copy.rotation.z;
  56778. this._quaternionRotationYPR();
  56779. }
  56780. this._quaternionToRotationMatrix();
  56781. for (i = 0; i < shape.length; i++) {
  56782. this._vertex.x = shape[i].x;
  56783. this._vertex.y = shape[i].y;
  56784. this._vertex.z = shape[i].z;
  56785. if (options && options.vertexFunction) {
  56786. options.vertexFunction(this._copy, this._vertex, i);
  56787. }
  56788. this._vertex.x *= this._copy.scaling.x;
  56789. this._vertex.y *= this._copy.scaling.y;
  56790. this._vertex.z *= this._copy.scaling.z;
  56791. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  56792. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  56793. if (meshUV) {
  56794. 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);
  56795. u += 2;
  56796. }
  56797. if (this._copy.color) {
  56798. this._color = this._copy.color;
  56799. }
  56800. else if (meshCol && meshCol[c] !== undefined) {
  56801. this._color.r = meshCol[c];
  56802. this._color.g = meshCol[c + 1];
  56803. this._color.b = meshCol[c + 2];
  56804. this._color.a = meshCol[c + 3];
  56805. }
  56806. else {
  56807. this._color.r = 1;
  56808. this._color.g = 1;
  56809. this._color.b = 1;
  56810. this._color.a = 1;
  56811. }
  56812. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  56813. c += 4;
  56814. }
  56815. for (i = 0; i < meshInd.length; i++) {
  56816. indices.push(p + meshInd[i]);
  56817. }
  56818. if (this._pickable) {
  56819. var nbfaces = meshInd.length / 3;
  56820. for (i = 0; i < nbfaces; i++) {
  56821. this.pickedParticles.push({ idx: idx, faceId: i });
  56822. }
  56823. }
  56824. };
  56825. // returns a shape array from positions array
  56826. SolidParticleSystem.prototype._posToShape = function (positions) {
  56827. var shape = [];
  56828. for (var i = 0; i < positions.length; i += 3) {
  56829. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  56830. }
  56831. return shape;
  56832. };
  56833. // returns a shapeUV array from a Vector4 uvs
  56834. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  56835. var shapeUV = [];
  56836. if (uvs) {
  56837. for (var i = 0; i < uvs.length; i++)
  56838. shapeUV.push(uvs[i]);
  56839. }
  56840. return shapeUV;
  56841. };
  56842. // adds a new particle object in the particles array
  56843. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  56844. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  56845. };
  56846. /**
  56847. * Adds some particles to the SPS from the model shape. Returns the shape id.
  56848. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  56849. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  56850. * `nb` (positive integer) the number of particles to be created from this model
  56851. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  56852. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  56853. */
  56854. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  56855. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56856. var meshInd = mesh.getIndices();
  56857. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56858. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56859. var shape = this._posToShape(meshPos);
  56860. var shapeUV = this._uvsToShapeUV(meshUV);
  56861. var posfunc = options ? options.positionFunction : null;
  56862. var vtxfunc = options ? options.vertexFunction : null;
  56863. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  56864. // particles
  56865. var idx = this.nbParticles;
  56866. for (var i = 0; i < nb; i++) {
  56867. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  56868. if (this._updatable) {
  56869. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  56870. }
  56871. this._index += shape.length;
  56872. idx++;
  56873. }
  56874. this.nbParticles += nb;
  56875. this._shapeCounter++;
  56876. return this._shapeCounter - 1;
  56877. };
  56878. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  56879. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  56880. this._resetCopy();
  56881. if (particle._model._positionFunction) {
  56882. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  56883. }
  56884. if (this._copy.rotationQuaternion) {
  56885. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  56886. }
  56887. else {
  56888. this._yaw = this._copy.rotation.y;
  56889. this._pitch = this._copy.rotation.x;
  56890. this._roll = this._copy.rotation.z;
  56891. this._quaternionRotationYPR();
  56892. }
  56893. this._quaternionToRotationMatrix();
  56894. this._shape = particle._model._shape;
  56895. for (var pt = 0; pt < this._shape.length; pt++) {
  56896. this._vertex.x = this._shape[pt].x;
  56897. this._vertex.y = this._shape[pt].y;
  56898. this._vertex.z = this._shape[pt].z;
  56899. if (particle._model._vertexFunction) {
  56900. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  56901. }
  56902. this._vertex.x *= this._copy.scaling.x;
  56903. this._vertex.y *= this._copy.scaling.y;
  56904. this._vertex.z *= this._copy.scaling.z;
  56905. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  56906. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  56907. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  56908. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  56909. }
  56910. particle.position.x = 0;
  56911. particle.position.y = 0;
  56912. particle.position.z = 0;
  56913. particle.rotation.x = 0;
  56914. particle.rotation.y = 0;
  56915. particle.rotation.z = 0;
  56916. particle.rotationQuaternion = null;
  56917. particle.scaling.x = 1;
  56918. particle.scaling.y = 1;
  56919. particle.scaling.z = 1;
  56920. };
  56921. /**
  56922. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  56923. */
  56924. SolidParticleSystem.prototype.rebuildMesh = function () {
  56925. for (var p = 0; p < this.particles.length; p++) {
  56926. this._rebuildParticle(this.particles[p]);
  56927. }
  56928. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  56929. };
  56930. /**
  56931. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  56932. * This method calls `updateParticle()` for each particle of the SPS.
  56933. * For an animated SPS, it is usually called within the render loop.
  56934. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  56935. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  56936. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  56937. */
  56938. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  56939. if (start === void 0) { start = 0; }
  56940. if (end === void 0) { end = this.nbParticles - 1; }
  56941. if (update === void 0) { update = true; }
  56942. if (!this._updatable) {
  56943. return;
  56944. }
  56945. // custom beforeUpdate
  56946. this.beforeUpdateParticles(start, end, update);
  56947. this._cam_axisX.x = 1.0;
  56948. this._cam_axisX.y = 0.0;
  56949. this._cam_axisX.z = 0.0;
  56950. this._cam_axisY.x = 0.0;
  56951. this._cam_axisY.y = 1.0;
  56952. this._cam_axisY.z = 0.0;
  56953. this._cam_axisZ.x = 0.0;
  56954. this._cam_axisZ.y = 0.0;
  56955. this._cam_axisZ.z = 1.0;
  56956. // if the particles will always face the camera
  56957. if (this.billboard) {
  56958. // compute the camera position and un-rotate it by the current mesh rotation
  56959. this._yaw = this.mesh.rotation.y;
  56960. this._pitch = this.mesh.rotation.x;
  56961. this._roll = this.mesh.rotation.z;
  56962. this._quaternionRotationYPR();
  56963. this._quaternionToRotationMatrix();
  56964. this._rotMatrix.invertToRef(this._invertMatrix);
  56965. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  56966. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  56967. this._cam_axisZ.normalize();
  56968. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  56969. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  56970. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  56971. this._cam_axisY.normalize();
  56972. this._cam_axisX.normalize();
  56973. }
  56974. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  56975. var idx = 0;
  56976. var index = 0;
  56977. var colidx = 0;
  56978. var colorIndex = 0;
  56979. var uvidx = 0;
  56980. var uvIndex = 0;
  56981. var pt = 0;
  56982. if (this._computeBoundingBox) {
  56983. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  56984. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  56985. }
  56986. // particle loop
  56987. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  56988. for (var p = start; p <= end; p++) {
  56989. this._particle = this.particles[p];
  56990. this._shape = this._particle._model._shape;
  56991. this._shapeUV = this._particle._model._shapeUV;
  56992. // call to custom user function to update the particle properties
  56993. this.updateParticle(this._particle);
  56994. if (this._particle.isVisible) {
  56995. // particle rotation matrix
  56996. if (this.billboard) {
  56997. this._particle.rotation.x = 0.0;
  56998. this._particle.rotation.y = 0.0;
  56999. }
  57000. if (this._computeParticleRotation || this.billboard) {
  57001. if (this._particle.rotationQuaternion) {
  57002. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57003. }
  57004. else {
  57005. this._yaw = this._particle.rotation.y;
  57006. this._pitch = this._particle.rotation.x;
  57007. this._roll = this._particle.rotation.z;
  57008. this._quaternionRotationYPR();
  57009. }
  57010. this._quaternionToRotationMatrix();
  57011. }
  57012. // particle vertex loop
  57013. for (pt = 0; pt < this._shape.length; pt++) {
  57014. idx = index + pt * 3;
  57015. colidx = colorIndex + pt * 4;
  57016. uvidx = uvIndex + pt * 2;
  57017. this._vertex.x = this._shape[pt].x;
  57018. this._vertex.y = this._shape[pt].y;
  57019. this._vertex.z = this._shape[pt].z;
  57020. if (this._computeParticleVertex) {
  57021. this.updateParticleVertex(this._particle, this._vertex, pt);
  57022. }
  57023. // positions
  57024. this._vertex.x *= this._particle.scaling.x;
  57025. this._vertex.y *= this._particle.scaling.y;
  57026. this._vertex.z *= this._particle.scaling.z;
  57027. 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];
  57028. 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;
  57029. 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;
  57030. 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;
  57031. 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;
  57032. 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;
  57033. 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;
  57034. if (this._computeBoundingBox) {
  57035. if (this._positions32[idx] < this._minimum.x) {
  57036. this._minimum.x = this._positions32[idx];
  57037. }
  57038. if (this._positions32[idx] > this._maximum.x) {
  57039. this._maximum.x = this._positions32[idx];
  57040. }
  57041. if (this._positions32[idx + 1] < this._minimum.y) {
  57042. this._minimum.y = this._positions32[idx + 1];
  57043. }
  57044. if (this._positions32[idx + 1] > this._maximum.y) {
  57045. this._maximum.y = this._positions32[idx + 1];
  57046. }
  57047. if (this._positions32[idx + 2] < this._minimum.z) {
  57048. this._minimum.z = this._positions32[idx + 2];
  57049. }
  57050. if (this._positions32[idx + 2] > this._maximum.z) {
  57051. this._maximum.z = this._positions32[idx + 2];
  57052. }
  57053. }
  57054. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  57055. if (!this._computeParticleVertex) {
  57056. this._normal.x = this._fixedNormal32[idx];
  57057. this._normal.y = this._fixedNormal32[idx + 1];
  57058. this._normal.z = this._fixedNormal32[idx + 2];
  57059. 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];
  57060. 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;
  57061. 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;
  57062. 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;
  57063. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  57064. 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;
  57065. 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;
  57066. }
  57067. if (this._computeParticleColor) {
  57068. this._colors32[colidx] = this._particle.color.r;
  57069. this._colors32[colidx + 1] = this._particle.color.g;
  57070. this._colors32[colidx + 2] = this._particle.color.b;
  57071. this._colors32[colidx + 3] = this._particle.color.a;
  57072. }
  57073. if (this._computeParticleTexture) {
  57074. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57075. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57076. }
  57077. }
  57078. }
  57079. else {
  57080. for (pt = 0; pt < this._shape.length; pt++) {
  57081. idx = index + pt * 3;
  57082. colidx = colorIndex + pt * 4;
  57083. uvidx = uvIndex + pt * 2;
  57084. this._positions32[idx] = this._camera.position.x;
  57085. this._positions32[idx + 1] = this._camera.position.y;
  57086. this._positions32[idx + 2] = this._camera.position.z;
  57087. this._normals32[idx] = 0.0;
  57088. this._normals32[idx + 1] = 0.0;
  57089. this._normals32[idx + 2] = 0.0;
  57090. if (this._computeParticleColor) {
  57091. this._colors32[colidx] = this._particle.color.r;
  57092. this._colors32[colidx + 1] = this._particle.color.g;
  57093. this._colors32[colidx + 2] = this._particle.color.b;
  57094. this._colors32[colidx + 3] = this._particle.color.a;
  57095. }
  57096. if (this._computeParticleTexture) {
  57097. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57098. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57099. }
  57100. }
  57101. }
  57102. // increment indexes for the next particle
  57103. index = idx + 3;
  57104. colorIndex = colidx + 4;
  57105. uvIndex = uvidx + 2;
  57106. }
  57107. // if the VBO must be updated
  57108. if (update) {
  57109. if (this._computeParticleColor) {
  57110. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  57111. }
  57112. if (this._computeParticleTexture) {
  57113. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  57114. }
  57115. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57116. if (!this.mesh.areNormalsFrozen) {
  57117. if (this._computeParticleVertex) {
  57118. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  57119. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  57120. for (var i = 0; i < this._normals32.length; i++) {
  57121. this._fixedNormal32[i] = this._normals32[i];
  57122. }
  57123. }
  57124. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  57125. }
  57126. }
  57127. if (this._computeBoundingBox) {
  57128. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  57129. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  57130. }
  57131. this.afterUpdateParticles(start, end, update);
  57132. };
  57133. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  57134. this._halfroll = this._roll * 0.5;
  57135. this._halfpitch = this._pitch * 0.5;
  57136. this._halfyaw = this._yaw * 0.5;
  57137. this._sinRoll = Math.sin(this._halfroll);
  57138. this._cosRoll = Math.cos(this._halfroll);
  57139. this._sinPitch = Math.sin(this._halfpitch);
  57140. this._cosPitch = Math.cos(this._halfpitch);
  57141. this._sinYaw = Math.sin(this._halfyaw);
  57142. this._cosYaw = Math.cos(this._halfyaw);
  57143. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  57144. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  57145. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  57146. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  57147. };
  57148. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  57149. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  57150. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  57151. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  57152. this._rotMatrix.m[3] = 0;
  57153. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  57154. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  57155. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  57156. this._rotMatrix.m[7] = 0;
  57157. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  57158. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  57159. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  57160. this._rotMatrix.m[11] = 0;
  57161. this._rotMatrix.m[12] = 0;
  57162. this._rotMatrix.m[13] = 0;
  57163. this._rotMatrix.m[14] = 0;
  57164. this._rotMatrix.m[15] = 1.0;
  57165. };
  57166. /**
  57167. * Disposes the SPS
  57168. */
  57169. SolidParticleSystem.prototype.dispose = function () {
  57170. this.mesh.dispose();
  57171. this.vars = null;
  57172. // drop references to internal big arrays for the GC
  57173. this._positions = null;
  57174. this._indices = null;
  57175. this._normals = null;
  57176. this._uvs = null;
  57177. this._colors = null;
  57178. this._positions32 = null;
  57179. this._normals32 = null;
  57180. this._fixedNormal32 = null;
  57181. this._uvs32 = null;
  57182. this._colors32 = null;
  57183. this.pickedParticles = null;
  57184. };
  57185. /**
  57186. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  57187. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57188. */
  57189. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  57190. if (!this._isVisibilityBoxLocked) {
  57191. this.mesh.refreshBoundingInfo();
  57192. }
  57193. };
  57194. /**
  57195. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  57196. * @param size the size (float) of the visibility box
  57197. * note : this doesn't lock the SPS mesh bounding box.
  57198. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57199. */
  57200. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  57201. var vis = size / 2;
  57202. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  57203. };
  57204. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  57205. // getter and setter
  57206. get: function () {
  57207. return this._alwaysVisible;
  57208. },
  57209. /**
  57210. * Sets the SPS as always visible or not
  57211. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57212. */
  57213. set: function (val) {
  57214. this._alwaysVisible = val;
  57215. this.mesh.alwaysSelectAsActiveMesh = val;
  57216. },
  57217. enumerable: true,
  57218. configurable: true
  57219. });
  57220. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  57221. get: function () {
  57222. return this._isVisibilityBoxLocked;
  57223. },
  57224. /**
  57225. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  57226. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57227. */
  57228. set: function (val) {
  57229. this._isVisibilityBoxLocked = val;
  57230. this.mesh.getBoundingInfo().isLocked = val;
  57231. },
  57232. enumerable: true,
  57233. configurable: true
  57234. });
  57235. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  57236. // getters
  57237. get: function () {
  57238. return this._computeParticleRotation;
  57239. },
  57240. // Optimizer setters
  57241. /**
  57242. * Tells to `setParticles()` to compute the particle rotations or not.
  57243. * Default value : true. The SPS is faster when it's set to false.
  57244. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  57245. */
  57246. set: function (val) {
  57247. this._computeParticleRotation = val;
  57248. },
  57249. enumerable: true,
  57250. configurable: true
  57251. });
  57252. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  57253. get: function () {
  57254. return this._computeParticleColor;
  57255. },
  57256. /**
  57257. * Tells to `setParticles()` to compute the particle colors or not.
  57258. * Default value : true. The SPS is faster when it's set to false.
  57259. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  57260. */
  57261. set: function (val) {
  57262. this._computeParticleColor = val;
  57263. },
  57264. enumerable: true,
  57265. configurable: true
  57266. });
  57267. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  57268. get: function () {
  57269. return this._computeParticleTexture;
  57270. },
  57271. /**
  57272. * Tells to `setParticles()` to compute the particle textures or not.
  57273. * Default value : true. The SPS is faster when it's set to false.
  57274. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  57275. */
  57276. set: function (val) {
  57277. this._computeParticleTexture = val;
  57278. },
  57279. enumerable: true,
  57280. configurable: true
  57281. });
  57282. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  57283. get: function () {
  57284. return this._computeParticleVertex;
  57285. },
  57286. /**
  57287. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  57288. * Default value : false. The SPS is faster when it's set to false.
  57289. * Note : the particle custom vertex positions aren't stored values.
  57290. */
  57291. set: function (val) {
  57292. this._computeParticleVertex = val;
  57293. },
  57294. enumerable: true,
  57295. configurable: true
  57296. });
  57297. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  57298. get: function () {
  57299. return this._computeBoundingBox;
  57300. },
  57301. /**
  57302. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  57303. */
  57304. set: function (val) {
  57305. this._computeBoundingBox = val;
  57306. },
  57307. enumerable: true,
  57308. configurable: true
  57309. });
  57310. // =======================================================================
  57311. // Particle behavior logic
  57312. // these following methods may be overwritten by the user to fit his needs
  57313. /**
  57314. * This function does nothing. It may be overwritten to set all the particle first values.
  57315. * The SPS doesn't call this function, you may have to call it by your own.
  57316. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57317. */
  57318. SolidParticleSystem.prototype.initParticles = function () {
  57319. };
  57320. /**
  57321. * This function does nothing. It may be overwritten to recycle a particle.
  57322. * The SPS doesn't call this function, you may have to call it by your own.
  57323. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57324. */
  57325. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  57326. return particle;
  57327. };
  57328. /**
  57329. * Updates a particle : this function should be overwritten by the user.
  57330. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  57331. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57332. * ex : just set a particle position or velocity and recycle conditions
  57333. */
  57334. SolidParticleSystem.prototype.updateParticle = function (particle) {
  57335. return particle;
  57336. };
  57337. /**
  57338. * Updates a vertex of a particle : it can be overwritten by the user.
  57339. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  57340. * @param particle the current particle
  57341. * @param vertex the current index of the current particle
  57342. * @param pt the index of the current vertex in the particle shape
  57343. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  57344. * ex : just set a vertex particle position
  57345. */
  57346. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  57347. return vertex;
  57348. };
  57349. /**
  57350. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  57351. * This does nothing and may be overwritten by the user.
  57352. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57353. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57354. * @param update the boolean update value actually passed to setParticles()
  57355. */
  57356. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  57357. };
  57358. /**
  57359. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  57360. * This will be passed three parameters.
  57361. * This does nothing and may be overwritten by the user.
  57362. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57363. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57364. * @param update the boolean update value actually passed to setParticles()
  57365. */
  57366. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  57367. };
  57368. return SolidParticleSystem;
  57369. })();
  57370. BABYLON.SolidParticleSystem = SolidParticleSystem;
  57371. })(BABYLON || (BABYLON = {}));
  57372. var BABYLON;
  57373. (function (BABYLON) {
  57374. var Internals;
  57375. (function (Internals) {
  57376. var FileFaceOrientation = (function () {
  57377. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  57378. this.name = name;
  57379. this.worldAxisForNormal = worldAxisForNormal;
  57380. this.worldAxisForFileX = worldAxisForFileX;
  57381. this.worldAxisForFileY = worldAxisForFileY;
  57382. }
  57383. return FileFaceOrientation;
  57384. })();
  57385. ;
  57386. /**
  57387. * Helper class dealing with the extraction of spherical polynomial dataArray
  57388. * from a cube map.
  57389. */
  57390. var CubeMapToSphericalPolynomialTools = (function () {
  57391. function CubeMapToSphericalPolynomialTools() {
  57392. }
  57393. /**
  57394. * Converts a cubemap to the according Spherical Polynomial data.
  57395. * This extracts the first 3 orders only as they are the only one used in the lighting.
  57396. *
  57397. * @param cubeInfo The Cube map to extract the information from.
  57398. * @return The Spherical Polynomial data.
  57399. */
  57400. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  57401. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  57402. var totalSolidAngle = 0.0;
  57403. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  57404. var du = 2.0 / cubeInfo.size;
  57405. var dv = du;
  57406. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  57407. var minUV = du * 0.5 - 1.0;
  57408. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57409. var fileFace = this.FileFaces[faceIndex];
  57410. var dataArray = cubeInfo[fileFace.name];
  57411. var v = minUV;
  57412. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  57413. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  57414. // Because SP is still linear, so summation is fine in that basis.
  57415. for (var y = 0; y < cubeInfo.size; y++) {
  57416. var u = minUV;
  57417. for (var x = 0; x < cubeInfo.size; x++) {
  57418. // World direction (not normalised)
  57419. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  57420. worldDirection.normalize();
  57421. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  57422. if (1) {
  57423. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  57424. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  57425. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  57426. var color = new BABYLON.Color3(r, g, b);
  57427. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  57428. }
  57429. else {
  57430. if (faceIndex == 0) {
  57431. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  57432. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  57433. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  57434. }
  57435. else if (faceIndex == 1) {
  57436. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  57437. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  57438. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  57439. }
  57440. else if (faceIndex == 2) {
  57441. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  57442. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  57443. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  57444. }
  57445. else if (faceIndex == 3) {
  57446. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  57447. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  57448. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  57449. }
  57450. else if (faceIndex == 4) {
  57451. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  57452. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  57453. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  57454. }
  57455. else if (faceIndex == 5) {
  57456. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  57457. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  57458. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  57459. }
  57460. 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]);
  57461. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  57462. }
  57463. totalSolidAngle += deltaSolidAngle;
  57464. u += du;
  57465. }
  57466. v += dv;
  57467. }
  57468. }
  57469. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  57470. var correction = correctSolidAngle / totalSolidAngle;
  57471. sphericalHarmonics.scale(correction);
  57472. // Additionally scale by pi -- audit needed
  57473. sphericalHarmonics.scale(1.0 / Math.PI);
  57474. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  57475. };
  57476. CubeMapToSphericalPolynomialTools.FileFaces = [
  57477. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  57478. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  57479. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  57480. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  57481. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  57482. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  57483. ];
  57484. return CubeMapToSphericalPolynomialTools;
  57485. })();
  57486. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  57487. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57488. })(BABYLON || (BABYLON = {}));
  57489. var BABYLON;
  57490. (function (BABYLON) {
  57491. var Internals;
  57492. (function (Internals) {
  57493. /**
  57494. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  57495. */
  57496. var PanoramaToCubeMapTools = (function () {
  57497. function PanoramaToCubeMapTools() {
  57498. }
  57499. /**
  57500. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  57501. *
  57502. * @param float32Array The source data.
  57503. * @param inputWidth The width of the input panorama.
  57504. * @param inputhHeight The height of the input panorama.
  57505. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  57506. * @return The cubemap data
  57507. */
  57508. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  57509. if (!float32Array) {
  57510. throw "ConvertPanoramaToCubemap: input cannot be null";
  57511. }
  57512. if (float32Array.length != inputWidth * inputHeight * 3) {
  57513. throw "ConvertPanoramaToCubemap: input size is wrong";
  57514. }
  57515. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  57516. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  57517. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  57518. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  57519. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  57520. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  57521. return {
  57522. front: textureFront,
  57523. back: textureBack,
  57524. left: textureLeft,
  57525. right: textureRight,
  57526. up: textureUp,
  57527. down: textureDown,
  57528. size: size
  57529. };
  57530. };
  57531. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  57532. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  57533. var textureArray = new Float32Array(buffer);
  57534. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  57535. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  57536. var dy = 1 / texSize;
  57537. var fy = 0;
  57538. for (var y = 0; y < texSize; y++) {
  57539. var xv1 = faceData[0];
  57540. var xv2 = faceData[2];
  57541. for (var x = 0; x < texSize; x++) {
  57542. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  57543. v.normalize();
  57544. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  57545. // 3 channels per pixels
  57546. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  57547. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  57548. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  57549. xv1 = xv1.add(rotDX1);
  57550. xv2 = xv2.add(rotDX2);
  57551. }
  57552. fy += dy;
  57553. }
  57554. return textureArray;
  57555. };
  57556. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  57557. var theta = Math.atan2(vDir.z, vDir.x);
  57558. var phi = Math.acos(vDir.y);
  57559. while (theta < -Math.PI)
  57560. theta += 2 * Math.PI;
  57561. while (theta > Math.PI)
  57562. theta -= 2 * Math.PI;
  57563. var dx = theta / Math.PI;
  57564. var dy = phi / Math.PI;
  57565. // recenter.
  57566. dx = dx * 0.5 + 0.5;
  57567. var px = Math.round(dx * inputWidth);
  57568. if (px < 0)
  57569. px = 0;
  57570. else if (px >= inputWidth)
  57571. px = inputWidth - 1;
  57572. var py = Math.round(dy * inputHeight);
  57573. if (py < 0)
  57574. py = 0;
  57575. else if (py >= inputHeight)
  57576. py = inputHeight - 1;
  57577. var inputY = (inputHeight - py - 1);
  57578. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  57579. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  57580. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  57581. return {
  57582. r: r,
  57583. g: g,
  57584. b: b
  57585. };
  57586. };
  57587. PanoramaToCubeMapTools.FACE_FRONT = [
  57588. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  57589. new BABYLON.Vector3(1.0, -1.0, -1.0),
  57590. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  57591. new BABYLON.Vector3(1.0, 1.0, -1.0)
  57592. ];
  57593. PanoramaToCubeMapTools.FACE_BACK = [
  57594. new BABYLON.Vector3(1.0, -1.0, 1.0),
  57595. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57596. new BABYLON.Vector3(1.0, 1.0, 1.0),
  57597. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  57598. ];
  57599. PanoramaToCubeMapTools.FACE_RIGHT = [
  57600. new BABYLON.Vector3(1.0, -1.0, -1.0),
  57601. new BABYLON.Vector3(1.0, -1.0, 1.0),
  57602. new BABYLON.Vector3(1.0, 1.0, -1.0),
  57603. new BABYLON.Vector3(1.0, 1.0, 1.0)
  57604. ];
  57605. PanoramaToCubeMapTools.FACE_LEFT = [
  57606. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57607. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  57608. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  57609. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  57610. ];
  57611. PanoramaToCubeMapTools.FACE_DOWN = [
  57612. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  57613. new BABYLON.Vector3(1.0, 1.0, -1.0),
  57614. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  57615. new BABYLON.Vector3(1.0, 1.0, 1.0)
  57616. ];
  57617. PanoramaToCubeMapTools.FACE_UP = [
  57618. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57619. new BABYLON.Vector3(1.0, -1.0, 1.0),
  57620. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  57621. new BABYLON.Vector3(1.0, -1.0, -1.0)
  57622. ];
  57623. return PanoramaToCubeMapTools;
  57624. })();
  57625. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  57626. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57627. })(BABYLON || (BABYLON = {}));
  57628. var BABYLON;
  57629. (function (BABYLON) {
  57630. var Internals;
  57631. (function (Internals) {
  57632. ;
  57633. /**
  57634. * This groups tools to convert HDR texture to native colors array.
  57635. */
  57636. var HDRTools = (function () {
  57637. function HDRTools() {
  57638. }
  57639. HDRTools.Ldexp = function (mantissa, exponent) {
  57640. if (exponent > 1023) {
  57641. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  57642. }
  57643. if (exponent < -1074) {
  57644. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  57645. }
  57646. return mantissa * Math.pow(2, exponent);
  57647. };
  57648. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  57649. if (exponent > 0) {
  57650. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  57651. float32array[index + 0] = red * exponent;
  57652. float32array[index + 1] = green * exponent;
  57653. float32array[index + 2] = blue * exponent;
  57654. }
  57655. else {
  57656. float32array[index + 0] = 0;
  57657. float32array[index + 1] = 0;
  57658. float32array[index + 2] = 0;
  57659. }
  57660. };
  57661. HDRTools.readStringLine = function (uint8array, startIndex) {
  57662. var line = "";
  57663. var character = "";
  57664. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  57665. character = String.fromCharCode(uint8array[i]);
  57666. if (character == "\n") {
  57667. break;
  57668. }
  57669. line += character;
  57670. }
  57671. return line;
  57672. };
  57673. /**
  57674. * Reads header information from an RGBE texture stored in a native array.
  57675. * More information on this format are available here:
  57676. * https://en.wikipedia.org/wiki/RGBE_image_format
  57677. *
  57678. * @param uint8array The binary file stored in native array.
  57679. * @return The header information.
  57680. */
  57681. HDRTools.RGBE_ReadHeader = function (uint8array) {
  57682. var height = 0;
  57683. var width = 0;
  57684. var line = this.readStringLine(uint8array, 0);
  57685. if (line[0] != '#' || line[1] != '?') {
  57686. throw "Bad HDR Format.";
  57687. }
  57688. var endOfHeader = false;
  57689. var findFormat = false;
  57690. var lineIndex = 0;
  57691. do {
  57692. lineIndex += (line.length + 1);
  57693. line = this.readStringLine(uint8array, lineIndex);
  57694. if (line == "FORMAT=32-bit_rle_rgbe") {
  57695. findFormat = true;
  57696. }
  57697. else if (line.length == 0) {
  57698. endOfHeader = true;
  57699. }
  57700. } while (!endOfHeader);
  57701. if (!findFormat) {
  57702. throw "HDR Bad header format, unsupported FORMAT";
  57703. }
  57704. lineIndex += (line.length + 1);
  57705. line = this.readStringLine(uint8array, lineIndex);
  57706. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  57707. var match = sizeRegexp.exec(line);
  57708. // TODO. Support +Y and -X if needed.
  57709. if (match.length < 3) {
  57710. throw "HDR Bad header format, no size";
  57711. }
  57712. width = parseInt(match[2]);
  57713. height = parseInt(match[1]);
  57714. if (width < 8 || width > 0x7fff) {
  57715. throw "HDR Bad header format, unsupported size";
  57716. }
  57717. lineIndex += (line.length + 1);
  57718. return {
  57719. height: height,
  57720. width: width,
  57721. dataPosition: lineIndex
  57722. };
  57723. };
  57724. /**
  57725. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  57726. * This RGBE texture needs to store the information as a panorama.
  57727. *
  57728. * More information on this format are available here:
  57729. * https://en.wikipedia.org/wiki/RGBE_image_format
  57730. *
  57731. * @param buffer The binary file stored in an array buffer.
  57732. * @param size The expected size of the extracted cubemap.
  57733. * @return The Cube Map information.
  57734. */
  57735. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  57736. var uint8array = new Uint8Array(buffer);
  57737. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  57738. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  57739. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  57740. return cubeMapData;
  57741. };
  57742. /**
  57743. * Returns the pixels data extracted from an RGBE texture.
  57744. * This pixels will be stored left to right up to down in the R G B order in one array.
  57745. *
  57746. * More information on this format are available here:
  57747. * https://en.wikipedia.org/wiki/RGBE_image_format
  57748. *
  57749. * @param uint8array The binary file stored in an array buffer.
  57750. * @param hdrInfo The header information of the file.
  57751. * @return The pixels data in RGB right to left up to down order.
  57752. */
  57753. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  57754. // Keep for multi format supports.
  57755. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  57756. };
  57757. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  57758. var num_scanlines = hdrInfo.height;
  57759. var scanline_width = hdrInfo.width;
  57760. var a, b, c, d, count;
  57761. var dataIndex = hdrInfo.dataPosition;
  57762. var index = 0, endIndex = 0, i = 0;
  57763. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  57764. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  57765. // 3 channels of 4 bytes per pixel in float.
  57766. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  57767. var resultArray = new Float32Array(resultBuffer);
  57768. // read in each successive scanline
  57769. while (num_scanlines > 0) {
  57770. a = uint8array[dataIndex++];
  57771. b = uint8array[dataIndex++];
  57772. c = uint8array[dataIndex++];
  57773. d = uint8array[dataIndex++];
  57774. if (a != 2 || b != 2 || (c & 0x80)) {
  57775. // this file is not run length encoded
  57776. throw "HDR Bad header format, not RLE";
  57777. }
  57778. if (((c << 8) | d) != scanline_width) {
  57779. throw "HDR Bad header format, wrong scan line width";
  57780. }
  57781. index = 0;
  57782. // read each of the four channels for the scanline into the buffer
  57783. for (i = 0; i < 4; i++) {
  57784. endIndex = (i + 1) * scanline_width;
  57785. while (index < endIndex) {
  57786. a = uint8array[dataIndex++];
  57787. b = uint8array[dataIndex++];
  57788. if (a > 128) {
  57789. // a run of the same value
  57790. count = a - 128;
  57791. if ((count == 0) || (count > endIndex - index)) {
  57792. throw "HDR Bad Format, bad scanline data (run)";
  57793. }
  57794. while (count-- > 0) {
  57795. scanLineArray[index++] = b;
  57796. }
  57797. }
  57798. else {
  57799. // a non-run
  57800. count = a;
  57801. if ((count == 0) || (count > endIndex - index)) {
  57802. throw "HDR Bad Format, bad scanline data (non-run)";
  57803. }
  57804. scanLineArray[index++] = b;
  57805. if (--count > 0) {
  57806. for (var j = 0; j < count; j++) {
  57807. scanLineArray[index++] = uint8array[dataIndex++];
  57808. }
  57809. }
  57810. }
  57811. }
  57812. }
  57813. // now convert data from buffer into floats
  57814. for (i = 0; i < scanline_width; i++) {
  57815. a = scanLineArray[i];
  57816. b = scanLineArray[i + scanline_width];
  57817. c = scanLineArray[i + 2 * scanline_width];
  57818. d = scanLineArray[i + 3 * scanline_width];
  57819. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  57820. }
  57821. num_scanlines--;
  57822. }
  57823. return resultArray;
  57824. };
  57825. return HDRTools;
  57826. })();
  57827. Internals.HDRTools = HDRTools;
  57828. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57829. })(BABYLON || (BABYLON = {}));
  57830. //_______________________________________________________________
  57831. // Extracted from CubeMapGen:
  57832. // https://code.google.com/archive/p/cubemapgen/
  57833. //
  57834. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  57835. //_______________________________________________________________
  57836. var BABYLON;
  57837. (function (BABYLON) {
  57838. var Internals;
  57839. (function (Internals) {
  57840. /**
  57841. * The bounding box information used during the conversion process.
  57842. */
  57843. var CMGBoundinBox = (function () {
  57844. function CMGBoundinBox() {
  57845. this.min = new BABYLON.Vector3(0, 0, 0);
  57846. this.max = new BABYLON.Vector3(0, 0, 0);
  57847. this.clear();
  57848. }
  57849. CMGBoundinBox.prototype.clear = function () {
  57850. this.min.x = CMGBoundinBox.MAX;
  57851. this.min.y = CMGBoundinBox.MAX;
  57852. this.min.z = CMGBoundinBox.MAX;
  57853. this.max.x = CMGBoundinBox.MIN;
  57854. this.max.y = CMGBoundinBox.MIN;
  57855. this.max.z = CMGBoundinBox.MIN;
  57856. };
  57857. CMGBoundinBox.prototype.augment = function (x, y, z) {
  57858. this.min.x = Math.min(this.min.x, x);
  57859. this.min.y = Math.min(this.min.y, y);
  57860. this.min.z = Math.min(this.min.z, z);
  57861. this.max.x = Math.max(this.max.x, x);
  57862. this.max.y = Math.max(this.max.y, y);
  57863. this.max.z = Math.max(this.max.z, z);
  57864. };
  57865. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  57866. this.min.x = Math.max(this.min.x, x);
  57867. this.min.y = Math.max(this.min.y, y);
  57868. this.min.z = Math.max(this.min.z, z);
  57869. };
  57870. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  57871. this.max.x = Math.min(this.max.x, x);
  57872. this.max.y = Math.min(this.max.y, y);
  57873. this.max.z = Math.min(this.max.z, z);
  57874. };
  57875. CMGBoundinBox.prototype.empty = function () {
  57876. if ((this.min.x > this.max.y) ||
  57877. (this.min.y > this.max.y) ||
  57878. (this.min.z > this.max.y)) {
  57879. return true;
  57880. }
  57881. else {
  57882. return false;
  57883. }
  57884. };
  57885. CMGBoundinBox.MAX = Number.MAX_VALUE;
  57886. CMGBoundinBox.MIN = Number.MIN_VALUE;
  57887. return CMGBoundinBox;
  57888. })();
  57889. /**
  57890. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  57891. * required by the glossinees of a material.
  57892. *
  57893. * This only supports the cosine drop power as well as Warp fixup generation method.
  57894. *
  57895. * This is using the process from CubeMapGen described here:
  57896. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  57897. */
  57898. var PMREMGenerator = (function () {
  57899. /**
  57900. * Constructor of the generator.
  57901. *
  57902. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  57903. * @param inputSize The size of the cubemap faces
  57904. * @param outputSize The size of the output cubemap faces
  57905. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  57906. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  57907. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  57908. * @param specularPower The max specular level of the desired cubemap
  57909. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  57910. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  57911. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  57912. */
  57913. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  57914. this.input = input;
  57915. this.inputSize = inputSize;
  57916. this.outputSize = outputSize;
  57917. this.maxNumMipLevels = maxNumMipLevels;
  57918. this.numChannels = numChannels;
  57919. this.isFloat = isFloat;
  57920. this.specularPower = specularPower;
  57921. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  57922. this.excludeBase = excludeBase;
  57923. this.fixup = fixup;
  57924. this._outputSurface = [];
  57925. this._numMipLevels = 0;
  57926. }
  57927. /**
  57928. * Launches the filter process and return the result.
  57929. *
  57930. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  57931. */
  57932. PMREMGenerator.prototype.filterCubeMap = function () {
  57933. // Init cubemap processor
  57934. this.init();
  57935. // Filters the cubemap
  57936. this.filterCubeMapMipChain();
  57937. // Returns the filtered mips.
  57938. return this._outputSurface;
  57939. };
  57940. PMREMGenerator.prototype.init = function () {
  57941. var i;
  57942. var j;
  57943. var mipLevelSize;
  57944. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  57945. if (this.maxNumMipLevels == 0) {
  57946. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  57947. }
  57948. //first miplevel size
  57949. mipLevelSize = this.outputSize;
  57950. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  57951. for (j = 0; j < this.maxNumMipLevels; j++) {
  57952. this._outputSurface.length++;
  57953. this._outputSurface[j] = [];
  57954. //Iterate over faces for output images
  57955. for (i = 0; i < 6; i++) {
  57956. this._outputSurface[j].length++;
  57957. // Initializes a new array for the output.
  57958. if (this.isFloat) {
  57959. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  57960. }
  57961. else {
  57962. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  57963. }
  57964. }
  57965. //next mip level is half size
  57966. mipLevelSize >>= 1;
  57967. this._numMipLevels++;
  57968. //terminate if mip chain becomes too small
  57969. if (mipLevelSize == 0) {
  57970. this.maxNumMipLevels = j;
  57971. return;
  57972. }
  57973. }
  57974. };
  57975. //--------------------------------------------------------------------------------------
  57976. //Cube map filtering and mip chain generation.
  57977. // the cube map filtereing is specified using a number of parameters:
  57978. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  57979. // indicates the region of the hemisphere to filter over for each tap.
  57980. //
  57981. // Note that the top mip level is also a filtered version of the original input images
  57982. // as well in order to create mip chains for diffuse environment illumination.
  57983. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  57984. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  57985. //
  57986. // Then the mip angle used to genreate the next level of the mip chain from the first level
  57987. // is a_InitialMipAngle
  57988. //
  57989. // The angle for the subsequent levels of the mip chain are specified by their parents
  57990. // filtering angle and a per-level scale and bias
  57991. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  57992. //
  57993. //--------------------------------------------------------------------------------------
  57994. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  57995. // First, take count of the lighting model to modify SpecularPower
  57996. // 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;
  57997. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  57998. //Cone angle start (for generating subsequent mip levels)
  57999. var currentSpecularPower = this.specularPower;
  58000. //Build filter lookup tables based on the source miplevel size
  58001. this.precomputeFilterLookupTables(this.inputSize);
  58002. // Note that we need to filter the first level before generating mipmap
  58003. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  58004. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  58005. // TODO : Write a function to copy and scale the base mipmap in output
  58006. // I am just lazy here and just put a high specular power value, and do some if.
  58007. if (this.excludeBase && (levelIndex == 0)) {
  58008. // 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).
  58009. currentSpecularPower = 100000.0;
  58010. }
  58011. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  58012. var srcCubeImage = this.input;
  58013. var dstCubeImage = this._outputSurface[levelIndex];
  58014. var dstSize = this.outputSize >> levelIndex;
  58015. // Compute required angle.
  58016. var angle = this.getBaseFilterAngle(currentSpecularPower);
  58017. // filter cube surfaces
  58018. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  58019. // fix seams
  58020. if (this.fixup) {
  58021. this.fixupCubeEdges(dstCubeImage, dstSize);
  58022. }
  58023. // Decrease the specular power to generate the mipmap chain
  58024. // TODO : Use another method for Exclude (see first comment at start of the function
  58025. if (this.excludeBase && (levelIndex == 0)) {
  58026. currentSpecularPower = this.specularPower;
  58027. }
  58028. currentSpecularPower *= this.cosinePowerDropPerMip;
  58029. }
  58030. };
  58031. //--------------------------------------------------------------------------------------
  58032. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  58033. // It allow to optimize the texel to access base on the specular power.
  58034. //--------------------------------------------------------------------------------------
  58035. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  58036. // We want to find the alpha such that:
  58037. // cos(alpha)^cosinePower = epsilon
  58038. // That's: acos(epsilon^(1/cosinePower))
  58039. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  58040. var angle = 180.0;
  58041. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  58042. angle *= 180.0 / Math.PI; // Convert to degree
  58043. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  58044. return angle;
  58045. };
  58046. //--------------------------------------------------------------------------------------
  58047. //Builds the following lookup tables prior to filtering:
  58048. // -normalizer cube map
  58049. // -tap weight lookup table
  58050. //
  58051. //--------------------------------------------------------------------------------------
  58052. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  58053. var srcTexelAngle;
  58054. var iCubeFace;
  58055. //clear pre-existing normalizer cube map
  58056. this._normCubeMap = [];
  58057. //Normalized vectors per cubeface and per-texel solid angle
  58058. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  58059. };
  58060. //--------------------------------------------------------------------------------------
  58061. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  58062. //
  58063. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  58064. //
  58065. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  58066. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  58067. // below
  58068. //--------------------------------------------------------------------------------------
  58069. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  58070. var iCubeFace;
  58071. var u;
  58072. var v;
  58073. //iterate over cube faces
  58074. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  58075. //First three channels for norm cube, and last channel for solid angle
  58076. this._normCubeMap.push(new Float32Array(size * size * 4));
  58077. //fast texture walk, build normalizer cube map
  58078. var facesData = this.input[iCubeFace];
  58079. for (v = 0; v < size; v++) {
  58080. for (u = 0; u < size; u++) {
  58081. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  58082. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  58083. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  58084. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  58085. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  58086. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  58087. }
  58088. }
  58089. }
  58090. };
  58091. //--------------------------------------------------------------------------------------
  58092. // Convert cubemap face texel coordinates and face idx to 3D vector
  58093. // note the U and V coords are integer coords and range from 0 to size-1
  58094. // this routine can be used to generate a normalizer cube map
  58095. //--------------------------------------------------------------------------------------
  58096. // SL BEGIN
  58097. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  58098. var nvcU;
  58099. var nvcV;
  58100. var tempVec;
  58101. // Change from original AMD code
  58102. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  58103. // + 0.5f is for texel center addressing
  58104. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  58105. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  58106. // warp fixup
  58107. if (fixup && size > 1) {
  58108. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  58109. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  58110. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  58111. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  58112. }
  58113. // Get current vector
  58114. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  58115. // U contribution
  58116. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  58117. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  58118. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  58119. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  58120. // V contribution and Sum
  58121. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  58122. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  58123. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  58124. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  58125. //add face axis
  58126. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  58127. PMREMGenerator._vectorTemp.x += faceAxis[0];
  58128. PMREMGenerator._vectorTemp.y += faceAxis[1];
  58129. PMREMGenerator._vectorTemp.z += faceAxis[2];
  58130. //normalize vector
  58131. PMREMGenerator._vectorTemp.normalize();
  58132. return PMREMGenerator._vectorTemp;
  58133. };
  58134. //--------------------------------------------------------------------------------------
  58135. // Convert 3D vector to cubemap face texel coordinates and face idx
  58136. // note the U and V coords are integer coords and range from 0 to size-1
  58137. // this routine can be used to generate a normalizer cube map
  58138. //
  58139. // returns face IDX and texel coords
  58140. //--------------------------------------------------------------------------------------
  58141. // SL BEGIN
  58142. /*
  58143. Mapping Texture Coordinates to Cube Map Faces
  58144. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  58145. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  58146. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  58147. map arrangement in Pixar's RenderMan package.
  58148. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  58149. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  58150. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  58151. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  58152. the major axis direction). The target column in the table below explains how the major axis direction
  58153. maps to the 2D image of a particular cube map target.
  58154. major axis
  58155. direction target sc tc ma
  58156. ---------- --------------------------------- --- --- ---
  58157. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  58158. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  58159. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  58160. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  58161. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  58162. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  58163. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  58164. an updated (s,t) is calculated as follows
  58165. s = ( sc/|ma| + 1 ) / 2
  58166. t = ( tc/|ma| + 1 ) / 2
  58167. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  58168. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  58169. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  58170. */
  58171. // Note this method return U and V in range from 0 to size-1
  58172. // SL END
  58173. // Store the information in vector3 for convenience (faceindex, u, v)
  58174. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  58175. var maxCoord;
  58176. var faceIdx;
  58177. //absolute value 3
  58178. var absX = Math.abs(x);
  58179. var absY = Math.abs(y);
  58180. var absZ = Math.abs(z);
  58181. if (absX >= absY && absX >= absZ) {
  58182. maxCoord = absX;
  58183. if (x >= 0) {
  58184. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  58185. }
  58186. else {
  58187. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  58188. }
  58189. }
  58190. else if (absY >= absX && absY >= absZ) {
  58191. maxCoord = absY;
  58192. if (y >= 0) {
  58193. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  58194. }
  58195. else {
  58196. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  58197. }
  58198. }
  58199. else {
  58200. maxCoord = absZ;
  58201. if (z >= 0) {
  58202. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  58203. }
  58204. else {
  58205. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  58206. }
  58207. }
  58208. //divide through by max coord so face vector lies on cube face
  58209. var scale = 1 / maxCoord;
  58210. x *= scale;
  58211. y *= scale;
  58212. z *= scale;
  58213. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  58214. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  58215. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  58216. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  58217. // Modify original AMD code to return value from 0 to Size - 1
  58218. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  58219. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  58220. PMREMGenerator._vectorTemp.x = faceIdx;
  58221. PMREMGenerator._vectorTemp.y = u;
  58222. PMREMGenerator._vectorTemp.z = v;
  58223. return PMREMGenerator._vectorTemp;
  58224. };
  58225. //--------------------------------------------------------------------------------------
  58226. //Original code from Ignacio CastaÒo
  58227. // This formula is from Manne ÷hrstrˆm's thesis.
  58228. // Take two coordiantes in the range [-1, 1] that define a portion of a
  58229. // cube face and return the area of the projection of that portion on the
  58230. // surface of the sphere.
  58231. //--------------------------------------------------------------------------------------
  58232. PMREMGenerator.prototype.areaElement = function (x, y) {
  58233. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  58234. };
  58235. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  58236. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  58237. // (+ 0.5f is for texel center addressing)
  58238. u = (2.0 * (u + 0.5) / size) - 1.0;
  58239. v = (2.0 * (v + 0.5) / size) - 1.0;
  58240. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  58241. var invResolution = 1.0 / size;
  58242. // U and V are the -1..1 texture coordinate on the current face.
  58243. // Get projected area for this texel
  58244. var x0 = u - invResolution;
  58245. var y0 = v - invResolution;
  58246. var x1 = u + invResolution;
  58247. var y1 = v + invResolution;
  58248. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  58249. return solidAngle;
  58250. };
  58251. //--------------------------------------------------------------------------------------
  58252. //The key to the speed of these filtering routines is to quickly define a per-face
  58253. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  58254. // Later these pixels are selectively processed based on their dot products to see if
  58255. // they reside within the filtering cone.
  58256. //
  58257. //This is done by computing the smallest per-texel angle to get a conservative estimate
  58258. // of the number of texels needed to be covered in width and height order to filter the
  58259. // region. the bounding box for the center taps face is defined first, and if the
  58260. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  58261. // defined next
  58262. //--------------------------------------------------------------------------------------
  58263. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  58264. // note that pixels within these regions may be rejected
  58265. // based on the anlge
  58266. var iCubeFace;
  58267. var u;
  58268. var v;
  58269. // bounding box per face to specify region to process
  58270. var filterExtents = [];
  58271. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  58272. filterExtents.push(new CMGBoundinBox());
  58273. }
  58274. // min angle a src texel can cover (in degrees)
  58275. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  58276. // angle about center tap to define filter cone
  58277. // filter angle is 1/2 the cone angle
  58278. var filterAngle = filterConeAngle / 2.0;
  58279. //ensure filter angle is larger than a texel
  58280. if (filterAngle < srcTexelAngle) {
  58281. filterAngle = srcTexelAngle;
  58282. }
  58283. //ensure filter cone is always smaller than the hemisphere
  58284. if (filterAngle > 90.0) {
  58285. filterAngle = 90.0;
  58286. }
  58287. // the maximum number of texels in 1D the filter cone angle will cover
  58288. // used to determine bounding box size for filter extents
  58289. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  58290. // ensure conservative region always covers at least one texel
  58291. if (filterSize < 1) {
  58292. filterSize = 1;
  58293. }
  58294. // dotProdThresh threshold based on cone angle to determine whether or not taps
  58295. // reside within the cone angle
  58296. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  58297. // process required faces
  58298. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  58299. //iterate over dst cube map face texel
  58300. for (v = 0; v < dstSize; v++) {
  58301. for (u = 0; u < dstSize; u++) {
  58302. //get center tap direction
  58303. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  58304. //clear old per-face filter extents
  58305. this.clearFilterExtents(filterExtents);
  58306. //define per-face filter extents
  58307. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  58308. //perform filtering of src faces using filter extents
  58309. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  58310. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  58311. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  58312. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  58313. }
  58314. }
  58315. }
  58316. };
  58317. //--------------------------------------------------------------------------------------
  58318. //Clear filter extents for the 6 cube map faces
  58319. //--------------------------------------------------------------------------------------
  58320. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  58321. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  58322. filterExtents[iCubeFaces].clear();
  58323. }
  58324. };
  58325. //--------------------------------------------------------------------------------------
  58326. //Define per-face bounding box filter extents
  58327. //
  58328. // These define conservative texel regions in each of the faces the filter can possibly
  58329. // process. When the pixels in the regions are actually processed, the dot product
  58330. // between the tap vector and the center tap vector is used to determine the weight of
  58331. // the tap and whether or not the tap is within the cone.
  58332. //
  58333. //--------------------------------------------------------------------------------------
  58334. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  58335. //neighboring face and bleed over amount, and width of BBOX for
  58336. // left, right, top, and bottom edges of this face
  58337. var bleedOverAmount = [0, 0, 0, 0];
  58338. var bleedOverBBoxMin = [0, 0, 0, 0];
  58339. var bleedOverBBoxMax = [0, 0, 0, 0];
  58340. var neighborFace;
  58341. var neighborEdge;
  58342. var oppositeFaceIdx;
  58343. //get face idx, and u, v info from center tap dir
  58344. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  58345. var faceIdx = result.x;
  58346. var u = result.y;
  58347. var v = result.z;
  58348. //define bbox size within face
  58349. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  58350. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  58351. filterExtents[faceIdx].clampMin(0, 0, 0);
  58352. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  58353. //u and v extent in face corresponding to center tap
  58354. var minU = filterExtents[faceIdx].min.x;
  58355. var minV = filterExtents[faceIdx].min.y;
  58356. var maxU = filterExtents[faceIdx].max.x;
  58357. var maxV = filterExtents[faceIdx].max.y;
  58358. //bleed over amounts for face across u=0 edge (left)
  58359. bleedOverAmount[0] = (bboxSize - u);
  58360. bleedOverBBoxMin[0] = minV;
  58361. bleedOverBBoxMax[0] = maxV;
  58362. //bleed over amounts for face across u=1 edge (right)
  58363. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  58364. bleedOverBBoxMin[1] = minV;
  58365. bleedOverBBoxMax[1] = maxV;
  58366. //bleed over to face across v=0 edge (up)
  58367. bleedOverAmount[2] = (bboxSize - v);
  58368. bleedOverBBoxMin[2] = minU;
  58369. bleedOverBBoxMax[2] = maxU;
  58370. //bleed over to face across v=1 edge (down)
  58371. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  58372. bleedOverBBoxMin[3] = minU;
  58373. bleedOverBBoxMax[3] = maxU;
  58374. //compute bleed over regions in neighboring faces
  58375. for (var i = 0; i < 4; i++) {
  58376. if (bleedOverAmount[i] > 0) {
  58377. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  58378. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  58379. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  58380. // be flipped: the cases are
  58381. // if a left edge mates with a left or bottom edge on the neighbor
  58382. // if a top edge mates with a top or right edge on the neighbor
  58383. // if a right edge mates with a right or top edge on the neighbor
  58384. // if a bottom edge mates with a bottom or left edge on the neighbor
  58385. //Seeing as the edges are enumerated as follows
  58386. // left =0
  58387. // right =1
  58388. // top =2
  58389. // bottom =3
  58390. //
  58391. // so if the edge enums are the same, or the sum of the enums == 3,
  58392. // the bbox needs to be flipped
  58393. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  58394. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  58395. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  58396. }
  58397. //The way the bounding box is extended onto the neighboring face
  58398. // depends on which edge of neighboring face abuts with this one
  58399. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  58400. case PMREMGenerator.CP_EDGE_LEFT:
  58401. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  58402. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  58403. break;
  58404. case PMREMGenerator.CP_EDGE_RIGHT:
  58405. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  58406. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  58407. break;
  58408. case PMREMGenerator.CP_EDGE_TOP:
  58409. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  58410. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  58411. break;
  58412. case PMREMGenerator.CP_EDGE_BOTTOM:
  58413. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  58414. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  58415. break;
  58416. }
  58417. //clamp filter extents in non-center tap faces to remain within surface
  58418. filterExtents[neighborFace].clampMin(0, 0, 0);
  58419. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  58420. }
  58421. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  58422. // from the center tap face, then process the opposite face entirely for now.
  58423. //Note that the cases in which this happens, what usually happens is that
  58424. // more than one edge bleeds onto the opposite face, and the bounding box
  58425. // encompasses the entire cube map face.
  58426. if (bleedOverAmount[i] > srcSize) {
  58427. //determine opposite face
  58428. switch (faceIdx) {
  58429. case PMREMGenerator.CP_FACE_X_POS:
  58430. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  58431. break;
  58432. case PMREMGenerator.CP_FACE_X_NEG:
  58433. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  58434. break;
  58435. case PMREMGenerator.CP_FACE_Y_POS:
  58436. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  58437. break;
  58438. case PMREMGenerator.CP_FACE_Y_NEG:
  58439. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  58440. break;
  58441. case PMREMGenerator.CP_FACE_Z_POS:
  58442. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  58443. break;
  58444. case PMREMGenerator.CP_FACE_Z_NEG:
  58445. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  58446. break;
  58447. default:
  58448. break;
  58449. }
  58450. //just encompass entire face for now
  58451. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  58452. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  58453. }
  58454. }
  58455. };
  58456. //--------------------------------------------------------------------------------------
  58457. //ProcessFilterExtents
  58458. // Process bounding box in each cube face
  58459. //
  58460. //--------------------------------------------------------------------------------------
  58461. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  58462. //accumulators are 64-bit floats in order to have the precision needed
  58463. // over a summation of a large number of pixels
  58464. var dstAccum = [0, 0, 0, 0];
  58465. var weightAccum = 0;
  58466. var k = 0;
  58467. var nSrcChannels = this.numChannels;
  58468. // norm cube map and srcCubeMap have same face width
  58469. var faceWidth = srcSize;
  58470. //amount to add to pointer to move to next scanline in images
  58471. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  58472. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  58473. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  58474. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  58475. // iterate over cubefaces
  58476. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  58477. //if bbox is non empty
  58478. if (!filterExtents[iFaceIdx].empty()) {
  58479. var uStart = filterExtents[iFaceIdx].min.x;
  58480. var vStart = filterExtents[iFaceIdx].min.y;
  58481. var uEnd = filterExtents[iFaceIdx].max.x;
  58482. var vEnd = filterExtents[iFaceIdx].max.y;
  58483. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  58484. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  58485. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  58486. for (var v = vStart; v <= vEnd; v++) {
  58487. var normCubeRowWalk = 0;
  58488. var srcCubeRowWalk = 0;
  58489. for (var u = uStart; u <= uEnd; u++) {
  58490. //pointer to direction in cube map associated with texel
  58491. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  58492. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  58493. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  58494. //check dot product to see if texel is within cone
  58495. var tapDotProd = texelVectX * centerTapDir.x +
  58496. texelVectY * centerTapDir.y +
  58497. texelVectZ * centerTapDir.z;
  58498. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  58499. //solid angle stored in 4th channel of normalizer/solid angle cube map
  58500. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  58501. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  58502. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  58503. // so just adding one to specularpower do the trick.
  58504. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  58505. //iterate over channels
  58506. for (k = 0; k < nSrcChannels; k++) {
  58507. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  58508. srcCubeRowWalk++;
  58509. }
  58510. weightAccum += weight; //accumulate weight
  58511. }
  58512. else {
  58513. //step across source pixel
  58514. srcCubeRowWalk += nSrcChannels;
  58515. }
  58516. normCubeRowWalk += 4; // 4 channels per norm cube map.
  58517. }
  58518. startIndexNormCubeMap += normCubePitch;
  58519. startIndexSrcCubeMap += srcCubePitch;
  58520. }
  58521. }
  58522. }
  58523. //divide through by weights if weight is non zero
  58524. if (weightAccum != 0.0) {
  58525. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  58526. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  58527. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  58528. if (this.numChannels > 3) {
  58529. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  58530. }
  58531. }
  58532. else {
  58533. // otherwise sample nearest
  58534. // get face idx and u, v texel coordinate in face
  58535. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  58536. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  58537. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  58538. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  58539. if (this.numChannels > 3) {
  58540. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  58541. }
  58542. }
  58543. return PMREMGenerator._vectorTemp;
  58544. };
  58545. //--------------------------------------------------------------------------------------
  58546. // Fixup cube edges
  58547. //
  58548. // average texels on cube map faces across the edges
  58549. // WARP/BENT Method Only.
  58550. //--------------------------------------------------------------------------------------
  58551. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  58552. var k;
  58553. var j;
  58554. var i;
  58555. var iFace;
  58556. var iCorner = 0;
  58557. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  58558. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  58559. // note that if functionality to filter across the three texels for each corner, then
  58560. //indexed by corner and face idx. the array contains the face the start points belongs to.
  58561. var cornerPtr = [
  58562. [[], [], []],
  58563. [[], [], []],
  58564. [[], [], []],
  58565. [[], [], []],
  58566. [[], [], []],
  58567. [[], [], []],
  58568. [[], [], []],
  58569. [[], [], []]
  58570. ];
  58571. //if there is no fixup, or fixup width = 0, do nothing
  58572. if (cubeMapSize < 1) {
  58573. return;
  58574. }
  58575. //special case 1x1 cubemap, average face colors
  58576. if (cubeMapSize == 1) {
  58577. //iterate over channels
  58578. for (k = 0; k < this.numChannels; k++) {
  58579. var accum = 0.0;
  58580. //iterate over faces to accumulate face colors
  58581. for (iFace = 0; iFace < 6; iFace++) {
  58582. accum += cubeMap[iFace][k];
  58583. }
  58584. //compute average over 6 face colors
  58585. accum /= 6.0;
  58586. //iterate over faces to distribute face colors
  58587. for (iFace = 0; iFace < 6; iFace++) {
  58588. cubeMap[iFace][k] = accum;
  58589. }
  58590. }
  58591. return;
  58592. }
  58593. //iterate over faces to collect list of corner texel pointers
  58594. for (iFace = 0; iFace < 6; iFace++) {
  58595. //the 4 corner pointers for this face
  58596. faceCornerStartIndicies[0] = [iFace, 0];
  58597. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  58598. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  58599. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  58600. //iterate over face corners to collect cube corner pointers
  58601. for (iCorner = 0; iCorner < 4; iCorner++) {
  58602. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  58603. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  58604. cornerNumPtrs[corner]++;
  58605. }
  58606. }
  58607. //iterate over corners to average across corner tap values
  58608. for (iCorner = 0; iCorner < 8; iCorner++) {
  58609. for (k = 0; k < this.numChannels; k++) {
  58610. var cornerTapAccum = 0.0;
  58611. //iterate over corner texels and average results
  58612. for (i = 0; i < 3; i++) {
  58613. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  58614. }
  58615. //divide by 3 to compute average of corner tap values
  58616. cornerTapAccum *= (1.0 / 3.0);
  58617. //iterate over corner texels and average results
  58618. for (i = 0; i < 3; i++) {
  58619. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  58620. }
  58621. }
  58622. }
  58623. //iterate over the twelve edges of the cube to average across edges
  58624. for (i = 0; i < 12; i++) {
  58625. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  58626. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  58627. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  58628. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  58629. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  58630. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  58631. var edgeWalk = 0;
  58632. var neighborEdgeWalk = 0;
  58633. //Determine walking pointers based on edge type
  58634. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  58635. switch (edge) {
  58636. case PMREMGenerator.CP_EDGE_LEFT:
  58637. // no change to faceEdgeStartPtr
  58638. edgeWalk = this.numChannels * cubeMapSize;
  58639. break;
  58640. case PMREMGenerator.CP_EDGE_RIGHT:
  58641. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  58642. edgeWalk = this.numChannels * cubeMapSize;
  58643. break;
  58644. case PMREMGenerator.CP_EDGE_TOP:
  58645. // no change to faceEdgeStartPtr
  58646. edgeWalk = this.numChannels;
  58647. break;
  58648. case PMREMGenerator.CP_EDGE_BOTTOM:
  58649. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  58650. edgeWalk = this.numChannels;
  58651. break;
  58652. }
  58653. //For certain types of edge abutments, the neighbor edge walk needs to
  58654. // be flipped: the cases are
  58655. // if a left edge mates with a left or bottom edge on the neighbor
  58656. // if a top edge mates with a top or right edge on the neighbor
  58657. // if a right edge mates with a right or top edge on the neighbor
  58658. // if a bottom edge mates with a bottom or left edge on the neighbor
  58659. //Seeing as the edges are enumerated as follows
  58660. // left =0
  58661. // right =1
  58662. // top =2
  58663. // bottom =3
  58664. //
  58665. //If the edge enums are the same, or the sum of the enums == 3,
  58666. // the neighbor edge walk needs to be flipped
  58667. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  58668. switch (neighborEdge) {
  58669. case PMREMGenerator.CP_EDGE_LEFT:
  58670. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  58671. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  58672. break;
  58673. case PMREMGenerator.CP_EDGE_RIGHT:
  58674. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  58675. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  58676. break;
  58677. case PMREMGenerator.CP_EDGE_TOP:
  58678. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  58679. neighborEdgeWalk = -this.numChannels;
  58680. break;
  58681. case PMREMGenerator.CP_EDGE_BOTTOM:
  58682. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  58683. neighborEdgeWalk = -this.numChannels;
  58684. break;
  58685. }
  58686. }
  58687. else {
  58688. //swapped direction neighbor edge walk
  58689. switch (neighborEdge) {
  58690. case PMREMGenerator.CP_EDGE_LEFT:
  58691. //no change to neighborEdgeStartPtr for this case since it points
  58692. // to the upper left corner already
  58693. neighborEdgeWalk = this.numChannels * cubeMapSize;
  58694. break;
  58695. case PMREMGenerator.CP_EDGE_RIGHT:
  58696. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  58697. neighborEdgeWalk = this.numChannels * cubeMapSize;
  58698. break;
  58699. case PMREMGenerator.CP_EDGE_TOP:
  58700. //no change to neighborEdgeStartPtr for this case since it points
  58701. // to the upper left corner already
  58702. neighborEdgeWalk = this.numChannels;
  58703. break;
  58704. case PMREMGenerator.CP_EDGE_BOTTOM:
  58705. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  58706. neighborEdgeWalk = this.numChannels;
  58707. break;
  58708. }
  58709. }
  58710. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  58711. //nearby neighborhood
  58712. //step ahead one texel on edge
  58713. edgeStartIndex += edgeWalk;
  58714. neighborEdgeStartIndex += neighborEdgeWalk;
  58715. // note that this loop does not process the corner texels, since they have already been
  58716. // averaged across faces across earlier
  58717. for (j = 1; j < (cubeMapSize - 1); j++) {
  58718. //for each set of taps along edge, average them
  58719. // and rewrite the results into the edges
  58720. for (k = 0; k < this.numChannels; k++) {
  58721. var edgeTap = cubeMap[face][edgeStartIndex + k];
  58722. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  58723. //compute average of tap intensity values
  58724. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  58725. //propagate average of taps to edge taps
  58726. cubeMap[face][edgeStartIndex + k] = avgTap;
  58727. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  58728. }
  58729. edgeStartIndex += edgeWalk;
  58730. neighborEdgeStartIndex += neighborEdgeWalk;
  58731. }
  58732. }
  58733. };
  58734. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  58735. PMREMGenerator.CP_UDIR = 0;
  58736. PMREMGenerator.CP_VDIR = 1;
  58737. PMREMGenerator.CP_FACEAXIS = 2;
  58738. //used to index cube faces
  58739. PMREMGenerator.CP_FACE_X_POS = 0;
  58740. PMREMGenerator.CP_FACE_X_NEG = 1;
  58741. PMREMGenerator.CP_FACE_Y_POS = 2;
  58742. PMREMGenerator.CP_FACE_Y_NEG = 3;
  58743. PMREMGenerator.CP_FACE_Z_POS = 4;
  58744. PMREMGenerator.CP_FACE_Z_NEG = 5;
  58745. //used to index image edges
  58746. // NOTE.. the actual number corresponding to the edge is important
  58747. // do not change these, or the code will break
  58748. //
  58749. // CP_EDGE_LEFT is u = 0
  58750. // CP_EDGE_RIGHT is u = width-1
  58751. // CP_EDGE_TOP is v = 0
  58752. // CP_EDGE_BOTTOM is v = height-1
  58753. PMREMGenerator.CP_EDGE_LEFT = 0;
  58754. PMREMGenerator.CP_EDGE_RIGHT = 1;
  58755. PMREMGenerator.CP_EDGE_TOP = 2;
  58756. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  58757. //corners of CUBE map (P or N specifys if it corresponds to the
  58758. // positive or negative direction each of X, Y, and Z
  58759. PMREMGenerator.CP_CORNER_NNN = 0;
  58760. PMREMGenerator.CP_CORNER_NNP = 1;
  58761. PMREMGenerator.CP_CORNER_NPN = 2;
  58762. PMREMGenerator.CP_CORNER_NPP = 3;
  58763. PMREMGenerator.CP_CORNER_PNN = 4;
  58764. PMREMGenerator.CP_CORNER_PNP = 5;
  58765. PMREMGenerator.CP_CORNER_PPN = 6;
  58766. PMREMGenerator.CP_CORNER_PPP = 7;
  58767. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  58768. //3x2 matrices that map cube map indexing vectors in 3d
  58769. // (after face selection and divide through by the
  58770. // _ABSOLUTE VALUE_ of the max coord)
  58771. // into NVC space
  58772. //Note this currently assumes the D3D cube face ordering and orientation
  58773. PMREMGenerator._sgFace2DMapping = [
  58774. //XPOS face
  58775. [[0, 0, -1],
  58776. [0, -1, 0],
  58777. [1, 0, 0]],
  58778. //XNEG face
  58779. [[0, 0, 1],
  58780. [0, -1, 0],
  58781. [-1, 0, 0]],
  58782. //YPOS face
  58783. [[1, 0, 0],
  58784. [0, 0, 1],
  58785. [0, 1, 0]],
  58786. //YNEG face
  58787. [[1, 0, 0],
  58788. [0, 0, -1],
  58789. [0, -1, 0]],
  58790. //ZPOS face
  58791. [[1, 0, 0],
  58792. [0, -1, 0],
  58793. [0, 0, 1]],
  58794. //ZNEG face
  58795. [[-1, 0, 0],
  58796. [0, -1, 0],
  58797. [0, 0, -1]],
  58798. ];
  58799. //------------------------------------------------------------------------------
  58800. // D3D cube map face specification
  58801. // mapping from 3D x,y,z cube map lookup coordinates
  58802. // to 2D within face u,v coordinates
  58803. //
  58804. // --------------------> U direction
  58805. // | (within-face texture space)
  58806. // | _____
  58807. // | | |
  58808. // | | +Y |
  58809. // | _____|_____|_____ _____
  58810. // | | | | | |
  58811. // | | -X | +Z | +X | -Z |
  58812. // | |_____|_____|_____|_____|
  58813. // | | |
  58814. // | | -Y |
  58815. // | |_____|
  58816. // |
  58817. // v V direction
  58818. // (within-face texture space)
  58819. //------------------------------------------------------------------------------
  58820. //Information about neighbors and how texture coorrdinates change across faces
  58821. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  58822. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  58823. //Note this currently assumes the D3D cube face ordering and orientation
  58824. PMREMGenerator._sgCubeNgh = [
  58825. //XPOS face
  58826. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  58827. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  58828. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  58829. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  58830. //XNEG face
  58831. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  58832. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  58833. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  58834. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  58835. //YPOS face
  58836. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  58837. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  58838. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  58839. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  58840. //YNEG face
  58841. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  58842. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  58843. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  58844. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  58845. //ZPOS face
  58846. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  58847. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  58848. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  58849. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  58850. //ZNEG face
  58851. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  58852. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  58853. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  58854. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  58855. ];
  58856. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  58857. // this table is used to average over the edges.
  58858. PMREMGenerator._sgCubeEdgeList = [
  58859. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  58860. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  58861. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  58862. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  58863. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  58864. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  58865. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  58866. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  58867. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  58868. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  58869. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  58870. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  58871. ];
  58872. //Information about which of the 8 cube corners are correspond to the
  58873. // the 4 corners in each cube face
  58874. // the order is upper left, upper right, lower left, lower right
  58875. PMREMGenerator._sgCubeCornerList = [
  58876. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  58877. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  58878. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  58879. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  58880. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  58881. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  58882. ];
  58883. return PMREMGenerator;
  58884. })();
  58885. Internals.PMREMGenerator = PMREMGenerator;
  58886. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58887. })(BABYLON || (BABYLON = {}));
  58888. var BABYLON;
  58889. (function (BABYLON) {
  58890. /**
  58891. * This represents a texture coming from an HDR input.
  58892. *
  58893. * The only supported format is currently panorama picture stored in RGBE format.
  58894. * Example of such files can be found on HDRLib: http://hdrlib.com/
  58895. */
  58896. var HDRCubeTexture = (function (_super) {
  58897. __extends(HDRCubeTexture, _super);
  58898. /**
  58899. * Instantiates an HDRTexture from the following parameters.
  58900. *
  58901. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  58902. * @param scene The scene the texture will be used in
  58903. * @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.
  58904. * @param noMipmap Forces to not generate the mipmap if true
  58905. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  58906. * @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)
  58907. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  58908. */
  58909. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  58910. if (noMipmap === void 0) { noMipmap = false; }
  58911. if (generateHarmonics === void 0) { generateHarmonics = true; }
  58912. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  58913. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  58914. _super.call(this, scene);
  58915. this._useInGammaSpace = false;
  58916. this._generateHarmonics = true;
  58917. this._isBABYLONPreprocessed = false;
  58918. /**
  58919. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  58920. */
  58921. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58922. /**
  58923. * The spherical polynomial data extracted from the texture.
  58924. */
  58925. this.sphericalPolynomial = null;
  58926. /**
  58927. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  58928. * This is usefull at run time to apply the good shader.
  58929. */
  58930. this.isPMREM = false;
  58931. if (!url) {
  58932. return;
  58933. }
  58934. this.name = url;
  58935. this.url = url;
  58936. this.hasAlpha = false;
  58937. this.isCube = true;
  58938. this._textureMatrix = BABYLON.Matrix.Identity();
  58939. if (size) {
  58940. this._isBABYLONPreprocessed = false;
  58941. this._noMipmap = noMipmap;
  58942. this._size = size;
  58943. this._useInGammaSpace = useInGammaSpace;
  58944. this._usePMREMGenerator = usePMREMGenerator &&
  58945. scene.getEngine().getCaps().textureLOD &&
  58946. this.getScene().getEngine().getCaps().textureFloat &&
  58947. !this._useInGammaSpace;
  58948. }
  58949. else {
  58950. this._isBABYLONPreprocessed = true;
  58951. this._noMipmap = false;
  58952. this._useInGammaSpace = false;
  58953. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  58954. this.getScene().getEngine().getCaps().textureFloat &&
  58955. !this._useInGammaSpace;
  58956. }
  58957. this.isPMREM = this._usePMREMGenerator;
  58958. this._texture = this._getFromCache(url, this._noMipmap);
  58959. if (!this._texture) {
  58960. if (!scene.useDelayedTextureLoading) {
  58961. this.loadTexture();
  58962. }
  58963. else {
  58964. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58965. }
  58966. }
  58967. }
  58968. /**
  58969. * Occurs when the file is a preprocessed .babylon.hdr file.
  58970. */
  58971. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  58972. var _this = this;
  58973. var mipLevels = 0;
  58974. var floatArrayView = null;
  58975. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  58976. var mips = [];
  58977. var startIndex = 30;
  58978. for (var level = 0; level < mipLevels; level++) {
  58979. mips.push([]);
  58980. // Fill each pixel of the mip level.
  58981. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  58982. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  58983. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  58984. mips[level].push(faceData);
  58985. startIndex += faceSize;
  58986. }
  58987. }
  58988. return mips;
  58989. } : null;
  58990. var callback = function (buffer) {
  58991. // Create Native Array Views
  58992. var intArrayView = new Int32Array(buffer);
  58993. floatArrayView = new Float32Array(buffer);
  58994. // Fill header.
  58995. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  58996. _this._size = intArrayView[1]; // CubeMap max mip face size.
  58997. // Update Texture Information.
  58998. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  58999. // Fill polynomial information.
  59000. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  59001. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  59002. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  59003. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  59004. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  59005. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  59006. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  59007. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  59008. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  59009. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  59010. // Fill pixel data.
  59011. mipLevels = intArrayView[29]; // Number of mip levels.
  59012. var startIndex = 30;
  59013. var data = [];
  59014. var faceSize = Math.pow(_this._size, 2) * 3;
  59015. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59016. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  59017. startIndex += faceSize;
  59018. }
  59019. var results = [];
  59020. var byteArray = null;
  59021. // Push each faces.
  59022. for (var k = 0; k < 6; k++) {
  59023. var dataFace = null;
  59024. // If special cases.
  59025. if (!mipmapGenerator) {
  59026. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  59027. dataFace = data[j];
  59028. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  59029. // 3 channels of 1 bytes per pixel in bytes.
  59030. var byteBuffer = new ArrayBuffer(faceSize);
  59031. byteArray = new Uint8Array(byteBuffer);
  59032. }
  59033. for (var i = 0; i < _this._size * _this._size; i++) {
  59034. // Put in gamma space if requested.
  59035. if (_this._useInGammaSpace) {
  59036. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  59037. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  59038. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  59039. }
  59040. // Convert to int texture for fallback.
  59041. if (byteArray) {
  59042. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  59043. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  59044. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  59045. // May use luminance instead if the result is not accurate.
  59046. var max = Math.max(Math.max(r, g), b);
  59047. if (max > 255) {
  59048. var scale = 255 / max;
  59049. r *= scale;
  59050. g *= scale;
  59051. b *= scale;
  59052. }
  59053. byteArray[(i * 3) + 0] = r;
  59054. byteArray[(i * 3) + 1] = g;
  59055. byteArray[(i * 3) + 2] = b;
  59056. }
  59057. }
  59058. }
  59059. else {
  59060. dataFace = data[k];
  59061. }
  59062. // Fill the array accordingly.
  59063. if (byteArray) {
  59064. results.push(byteArray);
  59065. }
  59066. else {
  59067. results.push(dataFace);
  59068. }
  59069. }
  59070. return results;
  59071. };
  59072. 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);
  59073. };
  59074. /**
  59075. * Occurs when the file is raw .hdr file.
  59076. */
  59077. HDRCubeTexture.prototype.loadHDRTexture = function () {
  59078. var _this = this;
  59079. var callback = function (buffer) {
  59080. // Extract the raw linear data.
  59081. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  59082. // Generate harmonics if needed.
  59083. if (_this._generateHarmonics) {
  59084. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  59085. }
  59086. var results = [];
  59087. var byteArray = null;
  59088. // Push each faces.
  59089. for (var j = 0; j < 6; j++) {
  59090. // Create uintarray fallback.
  59091. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  59092. // 3 channels of 1 bytes per pixel in bytes.
  59093. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  59094. byteArray = new Uint8Array(byteBuffer);
  59095. }
  59096. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  59097. // If special cases.
  59098. if (_this._useInGammaSpace || byteArray) {
  59099. for (var i = 0; i < _this._size * _this._size; i++) {
  59100. // Put in gamma space if requested.
  59101. if (_this._useInGammaSpace) {
  59102. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  59103. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  59104. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  59105. }
  59106. // Convert to int texture for fallback.
  59107. if (byteArray) {
  59108. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  59109. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  59110. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  59111. // May use luminance instead if the result is not accurate.
  59112. var max = Math.max(Math.max(r, g), b);
  59113. if (max > 255) {
  59114. var scale = 255 / max;
  59115. r *= scale;
  59116. g *= scale;
  59117. b *= scale;
  59118. }
  59119. byteArray[(i * 3) + 0] = r;
  59120. byteArray[(i * 3) + 1] = g;
  59121. byteArray[(i * 3) + 2] = b;
  59122. }
  59123. }
  59124. }
  59125. if (byteArray) {
  59126. results.push(byteArray);
  59127. }
  59128. else {
  59129. results.push(dataFace);
  59130. }
  59131. }
  59132. return results;
  59133. };
  59134. var mipmapGenerator = null;
  59135. if (!this._noMipmap &&
  59136. this._usePMREMGenerator) {
  59137. mipmapGenerator = function (data) {
  59138. // Custom setup of the generator matching with the PBR shader values.
  59139. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  59140. return generator.filterCubeMap();
  59141. };
  59142. }
  59143. 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);
  59144. };
  59145. /**
  59146. * Starts the loading process of the texture.
  59147. */
  59148. HDRCubeTexture.prototype.loadTexture = function () {
  59149. if (this._isBABYLONPreprocessed) {
  59150. this.loadBabylonTexture();
  59151. }
  59152. else {
  59153. this.loadHDRTexture();
  59154. }
  59155. };
  59156. HDRCubeTexture.prototype.clone = function () {
  59157. var size = this._isBABYLONPreprocessed ? null : this._size;
  59158. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  59159. // Base texture
  59160. newTexture.level = this.level;
  59161. newTexture.wrapU = this.wrapU;
  59162. newTexture.wrapV = this.wrapV;
  59163. newTexture.coordinatesIndex = this.coordinatesIndex;
  59164. newTexture.coordinatesMode = this.coordinatesMode;
  59165. return newTexture;
  59166. };
  59167. // Methods
  59168. HDRCubeTexture.prototype.delayLoad = function () {
  59169. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  59170. return;
  59171. }
  59172. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  59173. this._texture = this._getFromCache(this.url, this._noMipmap);
  59174. if (!this._texture) {
  59175. this.loadTexture();
  59176. }
  59177. };
  59178. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  59179. return this._textureMatrix;
  59180. };
  59181. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  59182. var texture = null;
  59183. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  59184. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  59185. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  59186. texture.name = parsedTexture.name;
  59187. texture.hasAlpha = parsedTexture.hasAlpha;
  59188. texture.level = parsedTexture.level;
  59189. texture.coordinatesMode = parsedTexture.coordinatesMode;
  59190. }
  59191. return texture;
  59192. };
  59193. HDRCubeTexture.prototype.serialize = function () {
  59194. if (!this.name) {
  59195. return null;
  59196. }
  59197. var serializationObject = {};
  59198. serializationObject.name = this.name;
  59199. serializationObject.hasAlpha = this.hasAlpha;
  59200. serializationObject.isCube = true;
  59201. serializationObject.level = this.level;
  59202. serializationObject.size = this._size;
  59203. serializationObject.coordinatesMode = this.coordinatesMode;
  59204. serializationObject.useInGammaSpace = this._useInGammaSpace;
  59205. serializationObject.generateHarmonics = this._generateHarmonics;
  59206. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  59207. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  59208. serializationObject.customType = "BABYLON.HDRCubeTexture";
  59209. return serializationObject;
  59210. };
  59211. /**
  59212. * Saves as a file the data contained in the texture in a binary format.
  59213. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  59214. * as the spherical used in the lighting.
  59215. * @param url The HDR file url.
  59216. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  59217. * @param onError Method called if any error happens during download.
  59218. * @return The packed binary data.
  59219. */
  59220. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  59221. if (onError === void 0) { onError = null; }
  59222. var callback = function (buffer) {
  59223. var data = new Blob([buffer], { type: 'application/octet-stream' });
  59224. // Returns a URL you can use as a href.
  59225. var objUrl = window.URL.createObjectURL(data);
  59226. // Simulates a link to it and click to dowload.
  59227. var a = document.createElement("a");
  59228. document.body.appendChild(a);
  59229. a.style.display = "none";
  59230. a.href = objUrl;
  59231. a.download = "envmap.babylon.hdr";
  59232. a.click();
  59233. };
  59234. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  59235. };
  59236. /**
  59237. * Serializes the data contained in the texture in a binary format.
  59238. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  59239. * as the spherical used in the lighting.
  59240. * @param url The HDR file url.
  59241. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  59242. * @param onError Method called if any error happens during download.
  59243. * @return The packed binary data.
  59244. */
  59245. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  59246. if (onError === void 0) { onError = null; }
  59247. // Needs the url tho create the texture.
  59248. if (!url) {
  59249. return null;
  59250. }
  59251. // Check Power of two size.
  59252. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  59253. return null;
  59254. }
  59255. var getDataCallback = function (dataBuffer) {
  59256. // Extract the raw linear data.
  59257. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  59258. // Generate harmonics if needed.
  59259. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  59260. // Generate seamless faces
  59261. var mipGeneratorArray = [];
  59262. // Data are known to be in +X +Y +Z -X -Y -Z
  59263. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  59264. mipGeneratorArray.push(cubeData.right); // +X
  59265. mipGeneratorArray.push(cubeData.left); // -X
  59266. mipGeneratorArray.push(cubeData.up); // +Y
  59267. mipGeneratorArray.push(cubeData.down); // -Y
  59268. mipGeneratorArray.push(cubeData.front); // +Z
  59269. mipGeneratorArray.push(cubeData.back); // -Z
  59270. // Custom setup of the generator matching with the PBR shader values.
  59271. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  59272. var mippedData = generator.filterCubeMap();
  59273. // Compute required byte length.
  59274. var byteLength = 1 * 4; // Raw Data Version int32.
  59275. byteLength += 4; // CubeMap max mip face size int32.
  59276. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  59277. // Add data size.
  59278. byteLength += 4; // Number of mip levels int32.
  59279. for (var level = 0; level < mippedData.length; level++) {
  59280. var mipSize = size >> level;
  59281. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  59282. }
  59283. // Prepare binary structure.
  59284. var buffer = new ArrayBuffer(byteLength);
  59285. var intArrayView = new Int32Array(buffer);
  59286. var floatArrayView = new Float32Array(buffer);
  59287. // Fill header.
  59288. intArrayView[0] = 1; // Version 1.
  59289. intArrayView[1] = size; // CubeMap max mip face size.
  59290. // Fill polynomial information.
  59291. sphericalPolynomial.x.toArray(floatArrayView, 2);
  59292. sphericalPolynomial.y.toArray(floatArrayView, 5);
  59293. sphericalPolynomial.z.toArray(floatArrayView, 8);
  59294. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  59295. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  59296. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  59297. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  59298. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  59299. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  59300. // Fill pixel data.
  59301. intArrayView[29] = mippedData.length; // Number of mip levels.
  59302. var startIndex = 30;
  59303. for (var level = 0; level < mippedData.length; level++) {
  59304. // Fill each pixel of the mip level.
  59305. var faceSize = Math.pow(size >> level, 2) * 3;
  59306. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59307. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  59308. startIndex += faceSize;
  59309. }
  59310. }
  59311. // Callback.
  59312. callback(buffer);
  59313. };
  59314. // Download and process.
  59315. BABYLON.Tools.LoadFile(url, function (data) {
  59316. getDataCallback(data);
  59317. }, null, null, true, onError);
  59318. };
  59319. HDRCubeTexture._facesMapping = [
  59320. "right",
  59321. "up",
  59322. "front",
  59323. "left",
  59324. "down",
  59325. "back"
  59326. ];
  59327. return HDRCubeTexture;
  59328. })(BABYLON.BaseTexture);
  59329. BABYLON.HDRCubeTexture = HDRCubeTexture;
  59330. })(BABYLON || (BABYLON = {}));
  59331. var BABYLON;
  59332. (function (BABYLON) {
  59333. var Debug;
  59334. (function (Debug) {
  59335. /**
  59336. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  59337. */
  59338. var SkeletonViewer = (function () {
  59339. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  59340. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  59341. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  59342. this.skeleton = skeleton;
  59343. this.mesh = mesh;
  59344. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  59345. this.renderingGroupId = renderingGroupId;
  59346. this.color = BABYLON.Color3.White();
  59347. this._debugLines = [];
  59348. this._isEnabled = false;
  59349. this._scene = scene;
  59350. this.update();
  59351. this._renderFunction = this.update.bind(this);
  59352. }
  59353. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  59354. get: function () {
  59355. return this._isEnabled;
  59356. },
  59357. set: function (value) {
  59358. if (this._isEnabled === value) {
  59359. return;
  59360. }
  59361. this._isEnabled = value;
  59362. if (value) {
  59363. this._scene.registerBeforeRender(this._renderFunction);
  59364. }
  59365. else {
  59366. this._scene.unregisterBeforeRender(this._renderFunction);
  59367. }
  59368. },
  59369. enumerable: true,
  59370. configurable: true
  59371. });
  59372. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  59373. if (x === void 0) { x = 0; }
  59374. if (y === void 0) { y = 0; }
  59375. if (z === void 0) { z = 0; }
  59376. var tmat = BABYLON.Tmp.Matrix[0];
  59377. var parentBone = bone.getParent();
  59378. tmat.copyFrom(bone.getLocalMatrix());
  59379. if (x !== 0 || y !== 0 || z !== 0) {
  59380. var tmat2 = BABYLON.Tmp.Matrix[1];
  59381. BABYLON.Matrix.IdentityToRef(tmat2);
  59382. tmat2.m[12] = x;
  59383. tmat2.m[13] = y;
  59384. tmat2.m[14] = z;
  59385. tmat2.multiplyToRef(tmat, tmat);
  59386. }
  59387. if (parentBone) {
  59388. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  59389. }
  59390. tmat.multiplyToRef(meshMat, tmat);
  59391. position.x = tmat.m[12];
  59392. position.y = tmat.m[13];
  59393. position.z = tmat.m[14];
  59394. };
  59395. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  59396. var len = bones.length;
  59397. for (var i = 0; i < len; i++) {
  59398. var bone = bones[i];
  59399. var points = this._debugLines[i];
  59400. if (!points) {
  59401. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59402. this._debugLines[i] = points;
  59403. }
  59404. this._getBonePosition(points[0], bone, meshMat);
  59405. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  59406. }
  59407. };
  59408. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  59409. var len = bones.length;
  59410. var boneNum = 0;
  59411. for (var i = len - 1; i >= 0; i--) {
  59412. var childBone = bones[i];
  59413. var parentBone = childBone.getParent();
  59414. if (!parentBone) {
  59415. continue;
  59416. }
  59417. var points = this._debugLines[boneNum];
  59418. if (!points) {
  59419. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59420. this._debugLines[boneNum] = points;
  59421. }
  59422. this._getBonePosition(points[0], childBone, meshMat);
  59423. this._getBonePosition(points[1], parentBone, meshMat);
  59424. boneNum++;
  59425. }
  59426. };
  59427. SkeletonViewer.prototype.update = function () {
  59428. if (this.autoUpdateBonesMatrices) {
  59429. this._updateBoneMatrix(this.skeleton.bones[0]);
  59430. }
  59431. if (this.skeleton.bones[0].length === undefined) {
  59432. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59433. }
  59434. else {
  59435. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59436. }
  59437. if (!this._debugMesh) {
  59438. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  59439. this._debugMesh.renderingGroupId = this.renderingGroupId;
  59440. }
  59441. else {
  59442. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  59443. }
  59444. this._debugMesh.color = this.color;
  59445. };
  59446. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  59447. if (bone.getParent()) {
  59448. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  59449. }
  59450. var children = bone.children;
  59451. var len = children.length;
  59452. for (var i = 0; i < len; i++) {
  59453. this._updateBoneMatrix(children[i]);
  59454. }
  59455. };
  59456. SkeletonViewer.prototype.dispose = function () {
  59457. if (this._debugMesh) {
  59458. this.isEnabled = false;
  59459. this._debugMesh.dispose();
  59460. this._debugMesh = null;
  59461. }
  59462. };
  59463. return SkeletonViewer;
  59464. })();
  59465. Debug.SkeletonViewer = SkeletonViewer;
  59466. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59467. })(BABYLON || (BABYLON = {}));
  59468. var BABYLON;
  59469. (function (BABYLON) {
  59470. /**
  59471. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  59472. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  59473. * 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;
  59474. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  59475. */
  59476. var ColorCurves = (function () {
  59477. function ColorCurves() {
  59478. this._dirty = true;
  59479. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  59480. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  59481. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  59482. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  59483. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  59484. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  59485. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  59486. this._globalHue = 30;
  59487. this._globalDensity = 0;
  59488. this._globalSaturation = 0;
  59489. this._globalExposure = 0;
  59490. this._highlightsHue = 30;
  59491. this._highlightsDensity = 0;
  59492. this._highlightsSaturation = 0;
  59493. this._highlightsExposure = 0;
  59494. this._midtonesHue = 30;
  59495. this._midtonesDensity = 0;
  59496. this._midtonesSaturation = 0;
  59497. this._midtonesExposure = 0;
  59498. this._shadowsHue = 30;
  59499. this._shadowsDensity = 0;
  59500. this._shadowsSaturation = 0;
  59501. this._shadowsExposure = 0;
  59502. }
  59503. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  59504. /**
  59505. * Gets the global Hue value.
  59506. * 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).
  59507. */
  59508. get: function () {
  59509. return this._globalHue;
  59510. },
  59511. /**
  59512. * Sets the global Hue value.
  59513. * 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).
  59514. */
  59515. set: function (value) {
  59516. this._globalHue = value;
  59517. this._dirty = true;
  59518. },
  59519. enumerable: true,
  59520. configurable: true
  59521. });
  59522. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  59523. /**
  59524. * Gets the global Density value.
  59525. * 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.
  59526. * Values less than zero provide a filter of opposite hue.
  59527. */
  59528. get: function () {
  59529. return this._globalDensity;
  59530. },
  59531. /**
  59532. * Sets the global Density value.
  59533. * 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.
  59534. * Values less than zero provide a filter of opposite hue.
  59535. */
  59536. set: function (value) {
  59537. this._globalDensity = value;
  59538. this._dirty = true;
  59539. },
  59540. enumerable: true,
  59541. configurable: true
  59542. });
  59543. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  59544. /**
  59545. * Gets the global Saturation value.
  59546. * 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.
  59547. */
  59548. get: function () {
  59549. return this._globalSaturation;
  59550. },
  59551. /**
  59552. * Sets the global Saturation value.
  59553. * 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.
  59554. */
  59555. set: function (value) {
  59556. this._globalSaturation = value;
  59557. this._dirty = true;
  59558. },
  59559. enumerable: true,
  59560. configurable: true
  59561. });
  59562. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  59563. /**
  59564. * Gets the highlights Hue value.
  59565. * 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).
  59566. */
  59567. get: function () {
  59568. return this._highlightsHue;
  59569. },
  59570. /**
  59571. * Sets the highlights Hue value.
  59572. * 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).
  59573. */
  59574. set: function (value) {
  59575. this._highlightsHue = value;
  59576. this._dirty = true;
  59577. },
  59578. enumerable: true,
  59579. configurable: true
  59580. });
  59581. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  59582. /**
  59583. * Gets the highlights Density value.
  59584. * 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.
  59585. * Values less than zero provide a filter of opposite hue.
  59586. */
  59587. get: function () {
  59588. return this._highlightsDensity;
  59589. },
  59590. /**
  59591. * Sets the highlights Density value.
  59592. * 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.
  59593. * Values less than zero provide a filter of opposite hue.
  59594. */
  59595. set: function (value) {
  59596. this._highlightsDensity = value;
  59597. this._dirty = true;
  59598. },
  59599. enumerable: true,
  59600. configurable: true
  59601. });
  59602. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  59603. /**
  59604. * Gets the highlights Saturation value.
  59605. * 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.
  59606. */
  59607. get: function () {
  59608. return this._highlightsSaturation;
  59609. },
  59610. /**
  59611. * Sets the highlights Saturation value.
  59612. * 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.
  59613. */
  59614. set: function (value) {
  59615. this._highlightsSaturation = value;
  59616. this._dirty = true;
  59617. },
  59618. enumerable: true,
  59619. configurable: true
  59620. });
  59621. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  59622. /**
  59623. * Gets the highlights Exposure value.
  59624. * 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.
  59625. */
  59626. get: function () {
  59627. return this._highlightsExposure;
  59628. },
  59629. /**
  59630. * Sets the highlights Exposure value.
  59631. * 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.
  59632. */
  59633. set: function (value) {
  59634. this._highlightsExposure = value;
  59635. this._dirty = true;
  59636. },
  59637. enumerable: true,
  59638. configurable: true
  59639. });
  59640. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  59641. /**
  59642. * Gets the midtones Hue value.
  59643. * 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).
  59644. */
  59645. get: function () {
  59646. return this._midtonesHue;
  59647. },
  59648. /**
  59649. * Sets the midtones Hue value.
  59650. * 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).
  59651. */
  59652. set: function (value) {
  59653. this._midtonesHue = value;
  59654. this._dirty = true;
  59655. },
  59656. enumerable: true,
  59657. configurable: true
  59658. });
  59659. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  59660. /**
  59661. * Gets the midtones Density value.
  59662. * 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.
  59663. * Values less than zero provide a filter of opposite hue.
  59664. */
  59665. get: function () {
  59666. return this._midtonesDensity;
  59667. },
  59668. /**
  59669. * Sets the midtones Density value.
  59670. * 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.
  59671. * Values less than zero provide a filter of opposite hue.
  59672. */
  59673. set: function (value) {
  59674. this._midtonesDensity = value;
  59675. this._dirty = true;
  59676. },
  59677. enumerable: true,
  59678. configurable: true
  59679. });
  59680. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  59681. /**
  59682. * Gets the midtones Saturation value.
  59683. * 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.
  59684. */
  59685. get: function () {
  59686. return this._midtonesSaturation;
  59687. },
  59688. /**
  59689. * Sets the midtones Saturation value.
  59690. * 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.
  59691. */
  59692. set: function (value) {
  59693. this._midtonesSaturation = value;
  59694. this._dirty = true;
  59695. },
  59696. enumerable: true,
  59697. configurable: true
  59698. });
  59699. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  59700. /**
  59701. * Gets the midtones Exposure value.
  59702. * 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.
  59703. */
  59704. get: function () {
  59705. return this._midtonesExposure;
  59706. },
  59707. /**
  59708. * Sets the midtones Exposure value.
  59709. * 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.
  59710. */
  59711. set: function (value) {
  59712. this._midtonesExposure = value;
  59713. this._dirty = true;
  59714. },
  59715. enumerable: true,
  59716. configurable: true
  59717. });
  59718. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  59719. /**
  59720. * Gets the shadows Hue value.
  59721. * 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).
  59722. */
  59723. get: function () {
  59724. return this._shadowsHue;
  59725. },
  59726. /**
  59727. * Sets the shadows Hue value.
  59728. * 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).
  59729. */
  59730. set: function (value) {
  59731. this._shadowsHue = value;
  59732. this._dirty = true;
  59733. },
  59734. enumerable: true,
  59735. configurable: true
  59736. });
  59737. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  59738. /**
  59739. * Gets the shadows Density value.
  59740. * 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.
  59741. * Values less than zero provide a filter of opposite hue.
  59742. */
  59743. get: function () {
  59744. return this._shadowsDensity;
  59745. },
  59746. /**
  59747. * Sets the shadows Density value.
  59748. * 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.
  59749. * Values less than zero provide a filter of opposite hue.
  59750. */
  59751. set: function (value) {
  59752. this._shadowsDensity = value;
  59753. this._dirty = true;
  59754. },
  59755. enumerable: true,
  59756. configurable: true
  59757. });
  59758. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  59759. /**
  59760. * Gets the shadows Saturation value.
  59761. * 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.
  59762. */
  59763. get: function () {
  59764. return this._shadowsSaturation;
  59765. },
  59766. /**
  59767. * Sets the shadows Saturation value.
  59768. * 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.
  59769. */
  59770. set: function (value) {
  59771. this._shadowsSaturation = value;
  59772. this._dirty = true;
  59773. },
  59774. enumerable: true,
  59775. configurable: true
  59776. });
  59777. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  59778. /**
  59779. * Gets the shadows Exposure value.
  59780. * 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.
  59781. */
  59782. get: function () {
  59783. return this._shadowsExposure;
  59784. },
  59785. /**
  59786. * Sets the shadows Exposure value.
  59787. * 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.
  59788. */
  59789. set: function (value) {
  59790. this._shadowsExposure = value;
  59791. this._dirty = true;
  59792. },
  59793. enumerable: true,
  59794. configurable: true
  59795. });
  59796. /**
  59797. * Binds the color curves to the shader.
  59798. * @param colorCurves The color curve to bind
  59799. * @param effect The effect to bind to
  59800. */
  59801. ColorCurves.Bind = function (colorCurves, effect) {
  59802. if (colorCurves._dirty) {
  59803. colorCurves._dirty = false;
  59804. // Fill in global info.
  59805. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  59806. // Compute highlights info.
  59807. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  59808. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  59809. // Compute midtones info.
  59810. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  59811. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  59812. // Compute shadows info.
  59813. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  59814. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  59815. // Compute deltas (neutral is midtones).
  59816. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  59817. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  59818. }
  59819. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  59820. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  59821. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  59822. };
  59823. /**
  59824. * Prepare the list of uniforms associated with the ColorCurves effects.
  59825. * @param uniformsList The list of uniforms used in the effect
  59826. */
  59827. ColorCurves.PrepareUniforms = function (uniformsList) {
  59828. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  59829. };
  59830. /**
  59831. * Returns color grading data based on a hue, density, saturation and exposure value.
  59832. * @param filterHue The hue of the color filter.
  59833. * @param filterDensity The density of the color filter.
  59834. * @param saturation The saturation.
  59835. * @param exposure The exposure.
  59836. * @param result The result data container.
  59837. */
  59838. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  59839. if (hue == null) {
  59840. return;
  59841. }
  59842. hue = ColorCurves.clamp(hue, 0, 360);
  59843. density = ColorCurves.clamp(density, -100, 100);
  59844. saturation = ColorCurves.clamp(saturation, -100, 100);
  59845. exposure = ColorCurves.clamp(exposure, -100, 100);
  59846. // Remap the slider/config filter density with non-linear mapping and also scale by half
  59847. // so that the maximum filter density is only 50% control. This provides fine control
  59848. // for small values and reasonable range.
  59849. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  59850. density *= 0.5;
  59851. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  59852. if (density < 0) {
  59853. density *= -1;
  59854. hue = (hue + 180) % 360;
  59855. }
  59856. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  59857. result.scaleToRef(2, result);
  59858. result.a = 1 + 0.01 * saturation;
  59859. };
  59860. /**
  59861. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  59862. * @param value The input slider value in range [-100,100].
  59863. * @returns Adjusted value.
  59864. */
  59865. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  59866. value /= 100;
  59867. var x = Math.abs(value);
  59868. x = Math.pow(x, 2);
  59869. if (value < 0) {
  59870. x *= -1;
  59871. }
  59872. x *= 100;
  59873. return x;
  59874. };
  59875. /**
  59876. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  59877. * @param hue The hue (H) input.
  59878. * @param saturation The saturation (S) input.
  59879. * @param brightness The brightness (B) input.
  59880. * @result An RGBA color represented as Vector4.
  59881. */
  59882. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  59883. var h = ColorCurves.clamp(hue, 0, 360);
  59884. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  59885. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  59886. if (s === 0) {
  59887. result.r = v;
  59888. result.g = v;
  59889. result.b = v;
  59890. }
  59891. else {
  59892. // sector 0 to 5
  59893. h /= 60;
  59894. var i = Math.floor(h);
  59895. // fractional part of h
  59896. var f = h - i;
  59897. var p = v * (1 - s);
  59898. var q = v * (1 - s * f);
  59899. var t = v * (1 - s * (1 - f));
  59900. switch (i) {
  59901. case 0:
  59902. result.r = v;
  59903. result.g = t;
  59904. result.b = p;
  59905. break;
  59906. case 1:
  59907. result.r = q;
  59908. result.g = v;
  59909. result.b = p;
  59910. break;
  59911. case 2:
  59912. result.r = p;
  59913. result.g = v;
  59914. result.b = t;
  59915. break;
  59916. case 3:
  59917. result.r = p;
  59918. result.g = q;
  59919. result.b = v;
  59920. break;
  59921. case 4:
  59922. result.r = t;
  59923. result.g = p;
  59924. result.b = v;
  59925. break;
  59926. default:
  59927. result.r = v;
  59928. result.g = p;
  59929. result.b = q;
  59930. break;
  59931. }
  59932. }
  59933. result.a = 1;
  59934. };
  59935. /**
  59936. * Returns a value clamped between min and max
  59937. * @param value The value to clamp
  59938. * @param min The minimum of value
  59939. * @param max The maximum of value
  59940. * @returns The clamped value.
  59941. */
  59942. ColorCurves.clamp = function (value, min, max) {
  59943. return Math.min(Math.max(value, min), max);
  59944. };
  59945. /**
  59946. * Clones the current color curve instance.
  59947. * @return The cloned curves
  59948. */
  59949. ColorCurves.prototype.clone = function () {
  59950. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  59951. };
  59952. /**
  59953. * Serializes the current color curve instance to a json representation.
  59954. * @return a JSON representation
  59955. */
  59956. ColorCurves.prototype.serialize = function () {
  59957. return BABYLON.SerializationHelper.Serialize(this);
  59958. };
  59959. /**
  59960. * Parses the color curve from a json representation.
  59961. * @param source the JSON source to parse
  59962. * @return The parsed curves
  59963. */
  59964. ColorCurves.Parse = function (source) {
  59965. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  59966. };
  59967. __decorate([
  59968. BABYLON.serialize()
  59969. ], ColorCurves.prototype, "_globalHue", void 0);
  59970. __decorate([
  59971. BABYLON.serialize()
  59972. ], ColorCurves.prototype, "_globalDensity", void 0);
  59973. __decorate([
  59974. BABYLON.serialize()
  59975. ], ColorCurves.prototype, "_globalSaturation", void 0);
  59976. __decorate([
  59977. BABYLON.serialize()
  59978. ], ColorCurves.prototype, "_globalExposure", void 0);
  59979. __decorate([
  59980. BABYLON.serialize()
  59981. ], ColorCurves.prototype, "_highlightsHue", void 0);
  59982. __decorate([
  59983. BABYLON.serialize()
  59984. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  59985. __decorate([
  59986. BABYLON.serialize()
  59987. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  59988. __decorate([
  59989. BABYLON.serialize()
  59990. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  59991. __decorate([
  59992. BABYLON.serialize()
  59993. ], ColorCurves.prototype, "_midtonesHue", void 0);
  59994. __decorate([
  59995. BABYLON.serialize()
  59996. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  59997. __decorate([
  59998. BABYLON.serialize()
  59999. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  60000. __decorate([
  60001. BABYLON.serialize()
  60002. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  60003. return ColorCurves;
  60004. })();
  60005. BABYLON.ColorCurves = ColorCurves;
  60006. })(BABYLON || (BABYLON = {}));
  60007. var BABYLON;
  60008. (function (BABYLON) {
  60009. /**
  60010. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  60011. * It can help converting any input color in a desired output one. This can then be used to create effects
  60012. * from sepia, black and white to sixties or futuristic rendering...
  60013. *
  60014. * The only supported format is currently 3dl.
  60015. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  60016. */
  60017. var ColorGradingTexture = (function (_super) {
  60018. __extends(ColorGradingTexture, _super);
  60019. /**
  60020. * Instantiates a ColorGradingTexture from the following parameters.
  60021. *
  60022. * @param url The location of the color gradind data (currently only supporting 3dl)
  60023. * @param scene The scene the texture will be used in
  60024. */
  60025. function ColorGradingTexture(url, scene) {
  60026. _super.call(this, scene);
  60027. if (!url) {
  60028. return;
  60029. }
  60030. this._textureMatrix = BABYLON.Matrix.Identity();
  60031. this.name = url;
  60032. this.url = url;
  60033. this.hasAlpha = false;
  60034. this.isCube = false;
  60035. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60036. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60037. this.anisotropicFilteringLevel = 1;
  60038. this._texture = this._getFromCache(url, true);
  60039. if (!this._texture) {
  60040. if (!scene.useDelayedTextureLoading) {
  60041. this.loadTexture();
  60042. }
  60043. else {
  60044. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  60045. }
  60046. }
  60047. }
  60048. /**
  60049. * Returns the texture matrix used in most of the material.
  60050. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  60051. */
  60052. ColorGradingTexture.prototype.getTextureMatrix = function () {
  60053. return this._textureMatrix;
  60054. };
  60055. /**
  60056. * Occurs when the file being loaded is a .3dl LUT file.
  60057. */
  60058. ColorGradingTexture.prototype.load3dlTexture = function () {
  60059. var _this = this;
  60060. var mipLevels = 0;
  60061. var floatArrayView = null;
  60062. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60063. this._texture = texture;
  60064. var callback = function (text) {
  60065. var data;
  60066. var tempData;
  60067. var line;
  60068. var lines = text.split('\n');
  60069. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  60070. var maxColor = 0;
  60071. for (var i = 0; i < lines.length; i++) {
  60072. line = lines[i];
  60073. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  60074. continue;
  60075. if (line.indexOf('#') === 0)
  60076. continue;
  60077. var words = line.split(" ");
  60078. if (size === 0) {
  60079. // Number of space + one
  60080. size = words.length;
  60081. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  60082. tempData = new Float32Array(size * size * size * 4);
  60083. continue;
  60084. }
  60085. if (size != 0) {
  60086. var r = Math.max(parseInt(words[0]), 0);
  60087. var g = Math.max(parseInt(words[1]), 0);
  60088. var b = Math.max(parseInt(words[2]), 0);
  60089. maxColor = Math.max(r, maxColor);
  60090. maxColor = Math.max(g, maxColor);
  60091. maxColor = Math.max(b, maxColor);
  60092. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  60093. tempData[pixelStorageIndex + 0] = r;
  60094. tempData[pixelStorageIndex + 1] = g;
  60095. tempData[pixelStorageIndex + 2] = b;
  60096. tempData[pixelStorageIndex + 3] = 0;
  60097. pixelIndexSlice++;
  60098. if (pixelIndexSlice % size == 0) {
  60099. pixelIndexH++;
  60100. pixelIndexSlice = 0;
  60101. if (pixelIndexH % size == 0) {
  60102. pixelIndexW++;
  60103. pixelIndexH = 0;
  60104. }
  60105. }
  60106. }
  60107. }
  60108. for (var i = 0; i < tempData.length; i++) {
  60109. var value = tempData[i];
  60110. data[i] = (value / maxColor * 255);
  60111. }
  60112. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  60113. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  60114. };
  60115. BABYLON.Tools.LoadFile(this.url, callback);
  60116. return this._texture;
  60117. };
  60118. /**
  60119. * Starts the loading process of the texture.
  60120. */
  60121. ColorGradingTexture.prototype.loadTexture = function () {
  60122. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  60123. this.load3dlTexture();
  60124. }
  60125. };
  60126. /**
  60127. * Clones the color gradind texture.
  60128. */
  60129. ColorGradingTexture.prototype.clone = function () {
  60130. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  60131. // Base texture
  60132. newTexture.level = this.level;
  60133. return newTexture;
  60134. };
  60135. /**
  60136. * Called during delayed load for textures.
  60137. */
  60138. ColorGradingTexture.prototype.delayLoad = function () {
  60139. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  60140. return;
  60141. }
  60142. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  60143. this._texture = this._getFromCache(this.url, true);
  60144. if (!this._texture) {
  60145. this.loadTexture();
  60146. }
  60147. };
  60148. /**
  60149. * Binds the color grading to the shader.
  60150. * @param colorGrading The texture to bind
  60151. * @param effect The effect to bind to
  60152. */
  60153. ColorGradingTexture.Bind = function (colorGrading, effect) {
  60154. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  60155. var x = colorGrading.level; // Texture Level
  60156. var y = colorGrading.getSize().height; // Texture Size example with 8
  60157. var z = y - 1.0; // SizeMinusOne 8 - 1
  60158. var w = 1 / y; // Space of 1 slice 1 / 8
  60159. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  60160. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  60161. 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
  60162. 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
  60163. 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
  60164. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  60165. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  60166. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  60167. };
  60168. /**
  60169. * Prepare the list of uniforms associated with the ColorGrading effects.
  60170. * @param uniformsList The list of uniforms used in the effect
  60171. * @param samplersList The list of samplers used in the effect
  60172. */
  60173. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  60174. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  60175. samplersList.push("cameraColorGrading2DSampler");
  60176. };
  60177. /**
  60178. * Parses a color grading texture serialized by Babylon.
  60179. * @param parsedTexture The texture information being parsedTexture
  60180. * @param scene The scene to load the texture in
  60181. * @param rootUrl The root url of the data assets to load
  60182. * @return A color gradind texture
  60183. */
  60184. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  60185. var texture = null;
  60186. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  60187. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  60188. texture.name = parsedTexture.name;
  60189. texture.level = parsedTexture.level;
  60190. }
  60191. return texture;
  60192. };
  60193. /**
  60194. * Serializes the LUT texture to json format.
  60195. */
  60196. ColorGradingTexture.prototype.serialize = function () {
  60197. if (!this.name) {
  60198. return null;
  60199. }
  60200. var serializationObject = {};
  60201. serializationObject.name = this.name;
  60202. serializationObject.level = this.level;
  60203. serializationObject.customType = "BABYLON.ColorGradingTexture";
  60204. return serializationObject;
  60205. };
  60206. /**
  60207. * Empty line regex stored for GC.
  60208. */
  60209. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  60210. return ColorGradingTexture;
  60211. })(BABYLON.BaseTexture);
  60212. BABYLON.ColorGradingTexture = ColorGradingTexture;
  60213. })(BABYLON || (BABYLON = {}));
  60214. var BABYLON;
  60215. (function (BABYLON) {
  60216. var PBRMaterialDefines = (function (_super) {
  60217. __extends(PBRMaterialDefines, _super);
  60218. function PBRMaterialDefines() {
  60219. _super.call(this);
  60220. this.ALBEDO = false;
  60221. this.AMBIENT = false;
  60222. this.OPACITY = false;
  60223. this.OPACITYRGB = false;
  60224. this.REFLECTION = false;
  60225. this.EMISSIVE = false;
  60226. this.REFLECTIVITY = false;
  60227. this.BUMP = false;
  60228. this.PARALLAX = false;
  60229. this.PARALLAXOCCLUSION = false;
  60230. this.SPECULAROVERALPHA = false;
  60231. this.CLIPPLANE = false;
  60232. this.ALPHATEST = false;
  60233. this.ALPHAFROMALBEDO = false;
  60234. this.POINTSIZE = false;
  60235. this.FOG = false;
  60236. this.SPECULARTERM = false;
  60237. this.OPACITYFRESNEL = false;
  60238. this.EMISSIVEFRESNEL = false;
  60239. this.FRESNEL = false;
  60240. this.NORMAL = false;
  60241. this.UV1 = false;
  60242. this.UV2 = false;
  60243. this.VERTEXCOLOR = false;
  60244. this.VERTEXALPHA = false;
  60245. this.NUM_BONE_INFLUENCERS = 0;
  60246. this.BonesPerMesh = 0;
  60247. this.INSTANCES = false;
  60248. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  60249. this.MICROSURFACEAUTOMATIC = false;
  60250. this.EMISSIVEASILLUMINATION = false;
  60251. this.LINKEMISSIVEWITHALBEDO = false;
  60252. this.LIGHTMAP = false;
  60253. this.USELIGHTMAPASSHADOWMAP = false;
  60254. this.REFLECTIONMAP_3D = false;
  60255. this.REFLECTIONMAP_SPHERICAL = false;
  60256. this.REFLECTIONMAP_PLANAR = false;
  60257. this.REFLECTIONMAP_CUBIC = false;
  60258. this.REFLECTIONMAP_PROJECTION = false;
  60259. this.REFLECTIONMAP_SKYBOX = false;
  60260. this.REFLECTIONMAP_EXPLICIT = false;
  60261. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  60262. this.INVERTCUBICMAP = false;
  60263. this.LOGARITHMICDEPTH = false;
  60264. this.CAMERATONEMAP = false;
  60265. this.CAMERACONTRAST = false;
  60266. this.CAMERACOLORGRADING = false;
  60267. this.CAMERACOLORCURVES = false;
  60268. this.OVERLOADEDVALUES = false;
  60269. this.OVERLOADEDSHADOWVALUES = false;
  60270. this.USESPHERICALFROMREFLECTIONMAP = false;
  60271. this.REFRACTION = false;
  60272. this.REFRACTIONMAP_3D = false;
  60273. this.LINKREFRACTIONTOTRANSPARENCY = false;
  60274. this.REFRACTIONMAPINLINEARSPACE = false;
  60275. this.LODBASEDMICROSFURACE = false;
  60276. this.USEPHYSICALLIGHTFALLOFF = false;
  60277. this.RADIANCEOVERALPHA = false;
  60278. this.USEPMREMREFLECTION = false;
  60279. this.USEPMREMREFRACTION = false;
  60280. this.OPENGLNORMALMAP = false;
  60281. this.INVERTNORMALMAPX = false;
  60282. this.INVERTNORMALMAPY = false;
  60283. this.SHADOWFULLFLOAT = false;
  60284. this.rebuild();
  60285. }
  60286. return PBRMaterialDefines;
  60287. })(BABYLON.MaterialDefines);
  60288. /**
  60289. * The Physically based material of BJS.
  60290. *
  60291. * This offers the main features of a standard PBR material.
  60292. * For more information, please refer to the documentation :
  60293. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  60294. */
  60295. var PBRMaterial = (function (_super) {
  60296. __extends(PBRMaterial, _super);
  60297. /**
  60298. * Instantiates a new PBRMaterial instance.
  60299. *
  60300. * @param name The material name
  60301. * @param scene The scene the material will be use in.
  60302. */
  60303. function PBRMaterial(name, scene) {
  60304. var _this = this;
  60305. _super.call(this, name, scene);
  60306. /**
  60307. * Intensity of the direct lights e.g. the four lights available in your scene.
  60308. * This impacts both the direct diffuse and specular highlights.
  60309. */
  60310. this.directIntensity = 1.0;
  60311. /**
  60312. * Intensity of the emissive part of the material.
  60313. * This helps controlling the emissive effect without modifying the emissive color.
  60314. */
  60315. this.emissiveIntensity = 1.0;
  60316. /**
  60317. * Intensity of the environment e.g. how much the environment will light the object
  60318. * either through harmonics for rough material or through the refelction for shiny ones.
  60319. */
  60320. this.environmentIntensity = 1.0;
  60321. /**
  60322. * This is a special control allowing the reduction of the specular highlights coming from the
  60323. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  60324. */
  60325. this.specularIntensity = 1.0;
  60326. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  60327. /**
  60328. * Debug Control allowing disabling the bump map on this material.
  60329. */
  60330. this.disableBumpMap = false;
  60331. /**
  60332. * Debug Control helping enforcing or dropping the darkness of shadows.
  60333. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  60334. */
  60335. this.overloadedShadowIntensity = 1.0;
  60336. /**
  60337. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  60338. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  60339. */
  60340. this.overloadedShadeIntensity = 1.0;
  60341. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  60342. /**
  60343. * The camera exposure used on this material.
  60344. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  60345. * This corresponds to a photographic exposure.
  60346. */
  60347. this.cameraExposure = 1.0;
  60348. /**
  60349. * The camera contrast used on this material.
  60350. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  60351. */
  60352. this.cameraContrast = 1.0;
  60353. /**
  60354. * Color Grading 2D Lookup Texture.
  60355. * This allows special effects like sepia, black and white to sixties rendering style.
  60356. */
  60357. this.cameraColorGradingTexture = null;
  60358. /**
  60359. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  60360. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  60361. * 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;
  60362. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  60363. */
  60364. this.cameraColorCurves = null;
  60365. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  60366. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  60367. /**
  60368. * Debug Control allowing to overload the ambient color.
  60369. * This as to be use with the overloadedAmbientIntensity parameter.
  60370. */
  60371. this.overloadedAmbient = BABYLON.Color3.White();
  60372. /**
  60373. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  60374. */
  60375. this.overloadedAmbientIntensity = 0.0;
  60376. /**
  60377. * Debug Control allowing to overload the albedo color.
  60378. * This as to be use with the overloadedAlbedoIntensity parameter.
  60379. */
  60380. this.overloadedAlbedo = BABYLON.Color3.White();
  60381. /**
  60382. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  60383. */
  60384. this.overloadedAlbedoIntensity = 0.0;
  60385. /**
  60386. * Debug Control allowing to overload the reflectivity color.
  60387. * This as to be use with the overloadedReflectivityIntensity parameter.
  60388. */
  60389. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  60390. /**
  60391. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  60392. */
  60393. this.overloadedReflectivityIntensity = 0.0;
  60394. /**
  60395. * Debug Control allowing to overload the emissive color.
  60396. * This as to be use with the overloadedEmissiveIntensity parameter.
  60397. */
  60398. this.overloadedEmissive = BABYLON.Color3.White();
  60399. /**
  60400. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  60401. */
  60402. this.overloadedEmissiveIntensity = 0.0;
  60403. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  60404. /**
  60405. * Debug Control allowing to overload the reflection color.
  60406. * This as to be use with the overloadedReflectionIntensity parameter.
  60407. */
  60408. this.overloadedReflection = BABYLON.Color3.White();
  60409. /**
  60410. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  60411. */
  60412. this.overloadedReflectionIntensity = 0.0;
  60413. /**
  60414. * Debug Control allowing to overload the microsurface.
  60415. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  60416. */
  60417. this.overloadedMicroSurface = 0.0;
  60418. /**
  60419. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  60420. */
  60421. this.overloadedMicroSurfaceIntensity = 0.0;
  60422. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  60423. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  60424. /**
  60425. * AKA Diffuse Color in other nomenclature.
  60426. */
  60427. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  60428. /**
  60429. * AKA Specular Color in other nomenclature.
  60430. */
  60431. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  60432. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  60433. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  60434. /**
  60435. * AKA Glossiness in other nomenclature.
  60436. */
  60437. this.microSurface = 0.9;
  60438. /**
  60439. * source material index of refraction (IOR)' / 'destination material IOR.
  60440. */
  60441. this.indexOfRefraction = 0.66;
  60442. /**
  60443. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  60444. */
  60445. this.invertRefractionY = false;
  60446. /**
  60447. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  60448. * Materials half opaque for instance using refraction could benefit from this control.
  60449. */
  60450. this.linkRefractionWithTransparency = false;
  60451. /**
  60452. * The emissive and albedo are linked to never be more than one (Energy conservation).
  60453. */
  60454. this.linkEmissiveWithAlbedo = false;
  60455. this.useLightmapAsShadowmap = false;
  60456. /**
  60457. * In this mode, the emissive informtaion will always be added to the lighting once.
  60458. * A light for instance can be thought as emissive.
  60459. */
  60460. this.useEmissiveAsIllumination = false;
  60461. /**
  60462. * Secifies that the alpha is coming form the albedo channel alpha channel.
  60463. */
  60464. this.useAlphaFromAlbedoTexture = false;
  60465. /**
  60466. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  60467. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  60468. */
  60469. this.useSpecularOverAlpha = true;
  60470. /**
  60471. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  60472. */
  60473. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  60474. /**
  60475. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  60476. * The material will try to infer what glossiness each pixel should be.
  60477. */
  60478. this.useAutoMicroSurfaceFromReflectivityMap = false;
  60479. /**
  60480. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  60481. * the creation of the material.
  60482. */
  60483. this.useScalarInLinearSpace = false;
  60484. /**
  60485. * BJS is using an harcoded light falloff based on a manually sets up range.
  60486. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  60487. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  60488. */
  60489. this.usePhysicalLightFalloff = true;
  60490. /**
  60491. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  60492. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  60493. */
  60494. this.useRadianceOverAlpha = true;
  60495. /**
  60496. * Allows using the bump map in parallax mode.
  60497. */
  60498. this.useParallax = false;
  60499. /**
  60500. * Allows using the bump map in parallax occlusion mode.
  60501. */
  60502. this.useParallaxOcclusion = false;
  60503. /**
  60504. * Controls the scale bias of the parallax mode.
  60505. */
  60506. this.parallaxScaleBias = 0.05;
  60507. /**
  60508. * If sets to true, disables all the lights affecting the material.
  60509. */
  60510. this.disableLighting = false;
  60511. /**
  60512. * Number of Simultaneous lights allowed on the material.
  60513. */
  60514. this.maxSimultaneousLights = 4;
  60515. /**
  60516. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  60517. */
  60518. this.invertNormalMapX = false;
  60519. /**
  60520. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  60521. */
  60522. this.invertNormalMapY = false;
  60523. this._renderTargets = new BABYLON.SmartArray(16);
  60524. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  60525. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  60526. this._tempColor = new BABYLON.Color3();
  60527. this._defines = new PBRMaterialDefines();
  60528. this._cachedDefines = new PBRMaterialDefines();
  60529. this._myScene = null;
  60530. this._myShadowGenerator = null;
  60531. this._cachedDefines.BonesPerMesh = -1;
  60532. this.getRenderTargetTextures = function () {
  60533. _this._renderTargets.reset();
  60534. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  60535. _this._renderTargets.push(_this.reflectionTexture);
  60536. }
  60537. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  60538. _this._renderTargets.push(_this.refractionTexture);
  60539. }
  60540. return _this._renderTargets;
  60541. };
  60542. }
  60543. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  60544. get: function () {
  60545. return this._useLogarithmicDepth;
  60546. },
  60547. set: function (value) {
  60548. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  60549. },
  60550. enumerable: true,
  60551. configurable: true
  60552. });
  60553. PBRMaterial.prototype.needAlphaBlending = function () {
  60554. if (this.linkRefractionWithTransparency) {
  60555. return false;
  60556. }
  60557. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  60558. };
  60559. PBRMaterial.prototype.needAlphaTesting = function () {
  60560. if (this.linkRefractionWithTransparency) {
  60561. return false;
  60562. }
  60563. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  60564. };
  60565. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  60566. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  60567. };
  60568. PBRMaterial.prototype.getAlphaTestTexture = function () {
  60569. return this.albedoTexture;
  60570. };
  60571. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  60572. if (!mesh) {
  60573. return true;
  60574. }
  60575. if (this._defines.INSTANCES !== useInstances) {
  60576. return false;
  60577. }
  60578. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  60579. return true;
  60580. }
  60581. return false;
  60582. };
  60583. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  60584. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  60585. };
  60586. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  60587. if (!useScalarInLinear) {
  60588. color.toLinearSpaceToRef(ref);
  60589. }
  60590. else {
  60591. ref.r = color.r;
  60592. ref.g = color.g;
  60593. ref.b = color.b;
  60594. }
  60595. };
  60596. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  60597. var lightIndex = 0;
  60598. var depthValuesAlreadySet = false;
  60599. for (var index = 0; index < scene.lights.length; index++) {
  60600. var light = scene.lights[index];
  60601. if (!light.isEnabled()) {
  60602. continue;
  60603. }
  60604. if (!light.canAffectMesh(mesh)) {
  60605. continue;
  60606. }
  60607. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  60608. // GAMMA CORRECTION.
  60609. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  60610. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  60611. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  60612. if (defines["SPECULARTERM"]) {
  60613. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  60614. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  60615. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  60616. }
  60617. // Shadows
  60618. if (scene.shadowsEnabled) {
  60619. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  60620. }
  60621. lightIndex++;
  60622. if (lightIndex === maxSimultaneousLights)
  60623. break;
  60624. }
  60625. };
  60626. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  60627. if (this.checkReadyOnlyOnce) {
  60628. if (this._wasPreviouslyReady) {
  60629. return true;
  60630. }
  60631. }
  60632. var scene = this.getScene();
  60633. if (!this.checkReadyOnEveryCall) {
  60634. if (this._renderId === scene.getRenderId()) {
  60635. if (this._checkCache(scene, mesh, useInstances)) {
  60636. return true;
  60637. }
  60638. }
  60639. }
  60640. var engine = scene.getEngine();
  60641. var needNormals = false;
  60642. var needUVs = false;
  60643. this._defines.reset();
  60644. if (scene.texturesEnabled) {
  60645. // Textures
  60646. if (scene.texturesEnabled) {
  60647. if (scene.getEngine().getCaps().textureLOD) {
  60648. this._defines.LODBASEDMICROSFURACE = true;
  60649. }
  60650. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  60651. if (!this.albedoTexture.isReady()) {
  60652. return false;
  60653. }
  60654. else {
  60655. needUVs = true;
  60656. this._defines.ALBEDO = true;
  60657. }
  60658. }
  60659. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  60660. if (!this.ambientTexture.isReady()) {
  60661. return false;
  60662. }
  60663. else {
  60664. needUVs = true;
  60665. this._defines.AMBIENT = true;
  60666. }
  60667. }
  60668. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  60669. if (!this.opacityTexture.isReady()) {
  60670. return false;
  60671. }
  60672. else {
  60673. needUVs = true;
  60674. this._defines.OPACITY = true;
  60675. if (this.opacityTexture.getAlphaFromRGB) {
  60676. this._defines.OPACITYRGB = true;
  60677. }
  60678. }
  60679. }
  60680. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  60681. if (!this.reflectionTexture.isReady()) {
  60682. return false;
  60683. }
  60684. else {
  60685. needNormals = true;
  60686. this._defines.REFLECTION = true;
  60687. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  60688. this._defines.INVERTCUBICMAP = true;
  60689. }
  60690. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  60691. switch (this.reflectionTexture.coordinatesMode) {
  60692. case BABYLON.Texture.CUBIC_MODE:
  60693. case BABYLON.Texture.INVCUBIC_MODE:
  60694. this._defines.REFLECTIONMAP_CUBIC = true;
  60695. break;
  60696. case BABYLON.Texture.EXPLICIT_MODE:
  60697. this._defines.REFLECTIONMAP_EXPLICIT = true;
  60698. break;
  60699. case BABYLON.Texture.PLANAR_MODE:
  60700. this._defines.REFLECTIONMAP_PLANAR = true;
  60701. break;
  60702. case BABYLON.Texture.PROJECTION_MODE:
  60703. this._defines.REFLECTIONMAP_PROJECTION = true;
  60704. break;
  60705. case BABYLON.Texture.SKYBOX_MODE:
  60706. this._defines.REFLECTIONMAP_SKYBOX = true;
  60707. break;
  60708. case BABYLON.Texture.SPHERICAL_MODE:
  60709. this._defines.REFLECTIONMAP_SPHERICAL = true;
  60710. break;
  60711. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  60712. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  60713. break;
  60714. }
  60715. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  60716. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  60717. needNormals = true;
  60718. if (this.reflectionTexture.isPMREM) {
  60719. this._defines.USEPMREMREFLECTION = true;
  60720. }
  60721. }
  60722. }
  60723. }
  60724. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  60725. if (!this.lightmapTexture.isReady()) {
  60726. return false;
  60727. }
  60728. else {
  60729. needUVs = true;
  60730. this._defines.LIGHTMAP = true;
  60731. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  60732. }
  60733. }
  60734. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  60735. if (!this.emissiveTexture.isReady()) {
  60736. return false;
  60737. }
  60738. else {
  60739. needUVs = true;
  60740. this._defines.EMISSIVE = true;
  60741. }
  60742. }
  60743. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  60744. if (!this.reflectivityTexture.isReady()) {
  60745. return false;
  60746. }
  60747. else {
  60748. needUVs = true;
  60749. this._defines.REFLECTIVITY = true;
  60750. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  60751. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  60752. }
  60753. }
  60754. }
  60755. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  60756. if (!this.bumpTexture.isReady()) {
  60757. return false;
  60758. }
  60759. else {
  60760. needUVs = true;
  60761. this._defines.BUMP = true;
  60762. if (this.useParallax) {
  60763. this._defines.PARALLAX = true;
  60764. if (this.useParallaxOcclusion) {
  60765. this._defines.PARALLAXOCCLUSION = true;
  60766. }
  60767. }
  60768. if (this.invertNormalMapX) {
  60769. this._defines.INVERTNORMALMAPX = true;
  60770. }
  60771. if (this.invertNormalMapY) {
  60772. this._defines.INVERTNORMALMAPY = true;
  60773. }
  60774. }
  60775. }
  60776. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  60777. if (!this.refractionTexture.isReady()) {
  60778. return false;
  60779. }
  60780. else {
  60781. needUVs = true;
  60782. this._defines.REFRACTION = true;
  60783. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  60784. if (this.linkRefractionWithTransparency) {
  60785. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  60786. }
  60787. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  60788. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  60789. if (this.refractionTexture.isPMREM) {
  60790. this._defines.USEPMREMREFRACTION = true;
  60791. }
  60792. }
  60793. }
  60794. }
  60795. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  60796. if (!this.cameraColorGradingTexture.isReady()) {
  60797. return false;
  60798. }
  60799. else {
  60800. this._defines.CAMERACOLORGRADING = true;
  60801. }
  60802. }
  60803. }
  60804. // Effect
  60805. if (scene.clipPlane) {
  60806. this._defines.CLIPPLANE = true;
  60807. }
  60808. if (engine.getAlphaTesting()) {
  60809. this._defines.ALPHATEST = true;
  60810. }
  60811. if (this._shouldUseAlphaFromAlbedoTexture()) {
  60812. this._defines.ALPHAFROMALBEDO = true;
  60813. }
  60814. if (this.useEmissiveAsIllumination) {
  60815. this._defines.EMISSIVEASILLUMINATION = true;
  60816. }
  60817. if (this.linkEmissiveWithAlbedo) {
  60818. this._defines.LINKEMISSIVEWITHALBEDO = true;
  60819. }
  60820. if (this.useLogarithmicDepth) {
  60821. this._defines.LOGARITHMICDEPTH = true;
  60822. }
  60823. if (this.cameraContrast != 1) {
  60824. this._defines.CAMERACONTRAST = true;
  60825. }
  60826. if (this.cameraExposure != 1) {
  60827. this._defines.CAMERATONEMAP = true;
  60828. }
  60829. if (this.cameraColorCurves) {
  60830. this._defines.CAMERACOLORCURVES = true;
  60831. }
  60832. if (this.overloadedShadeIntensity != 1 ||
  60833. this.overloadedShadowIntensity != 1) {
  60834. this._defines.OVERLOADEDSHADOWVALUES = true;
  60835. }
  60836. if (this.overloadedMicroSurfaceIntensity > 0 ||
  60837. this.overloadedEmissiveIntensity > 0 ||
  60838. this.overloadedReflectivityIntensity > 0 ||
  60839. this.overloadedAlbedoIntensity > 0 ||
  60840. this.overloadedAmbientIntensity > 0 ||
  60841. this.overloadedReflectionIntensity > 0) {
  60842. this._defines.OVERLOADEDVALUES = true;
  60843. }
  60844. // Point size
  60845. if (this.pointsCloud || scene.forcePointsCloud) {
  60846. this._defines.POINTSIZE = true;
  60847. }
  60848. // Fog
  60849. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  60850. this._defines.FOG = true;
  60851. }
  60852. if (scene.lightsEnabled && !this.disableLighting) {
  60853. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  60854. }
  60855. if (BABYLON.StandardMaterial.FresnelEnabled) {
  60856. // Fresnel
  60857. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  60858. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  60859. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  60860. this._defines.OPACITYFRESNEL = true;
  60861. }
  60862. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  60863. this._defines.EMISSIVEFRESNEL = true;
  60864. }
  60865. needNormals = true;
  60866. this._defines.FRESNEL = true;
  60867. }
  60868. }
  60869. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  60870. this._defines.SPECULAROVERALPHA = true;
  60871. }
  60872. if (this.usePhysicalLightFalloff) {
  60873. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  60874. }
  60875. if (this.useRadianceOverAlpha) {
  60876. this._defines.RADIANCEOVERALPHA = true;
  60877. }
  60878. // Attribs
  60879. if (mesh) {
  60880. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  60881. this._defines.NORMAL = true;
  60882. }
  60883. if (needUVs) {
  60884. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60885. this._defines.UV1 = true;
  60886. }
  60887. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60888. this._defines.UV2 = true;
  60889. }
  60890. }
  60891. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  60892. this._defines.VERTEXCOLOR = true;
  60893. if (mesh.hasVertexAlpha) {
  60894. this._defines.VERTEXALPHA = true;
  60895. }
  60896. }
  60897. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60898. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  60899. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  60900. }
  60901. // Instances
  60902. if (useInstances) {
  60903. this._defines.INSTANCES = true;
  60904. }
  60905. }
  60906. // Get correct effect
  60907. if (!this._defines.isEqual(this._cachedDefines)) {
  60908. this._defines.cloneTo(this._cachedDefines);
  60909. scene.resetCachedMaterial();
  60910. // Fallbacks
  60911. var fallbacks = new BABYLON.EffectFallbacks();
  60912. if (this._defines.REFLECTION) {
  60913. fallbacks.addFallback(0, "REFLECTION");
  60914. }
  60915. if (this._defines.REFRACTION) {
  60916. fallbacks.addFallback(0, "REFRACTION");
  60917. }
  60918. if (this._defines.REFLECTIVITY) {
  60919. fallbacks.addFallback(0, "REFLECTIVITY");
  60920. }
  60921. if (this._defines.BUMP) {
  60922. fallbacks.addFallback(0, "BUMP");
  60923. }
  60924. if (this._defines.PARALLAX) {
  60925. fallbacks.addFallback(1, "PARALLAX");
  60926. }
  60927. if (this._defines.PARALLAXOCCLUSION) {
  60928. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  60929. }
  60930. if (this._defines.SPECULAROVERALPHA) {
  60931. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  60932. }
  60933. if (this._defines.FOG) {
  60934. fallbacks.addFallback(1, "FOG");
  60935. }
  60936. if (this._defines.POINTSIZE) {
  60937. fallbacks.addFallback(0, "POINTSIZE");
  60938. }
  60939. if (this._defines.LOGARITHMICDEPTH) {
  60940. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  60941. }
  60942. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  60943. if (this._defines.SPECULARTERM) {
  60944. fallbacks.addFallback(0, "SPECULARTERM");
  60945. }
  60946. if (this._defines.OPACITYFRESNEL) {
  60947. fallbacks.addFallback(1, "OPACITYFRESNEL");
  60948. }
  60949. if (this._defines.EMISSIVEFRESNEL) {
  60950. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  60951. }
  60952. if (this._defines.FRESNEL) {
  60953. fallbacks.addFallback(3, "FRESNEL");
  60954. }
  60955. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  60956. fallbacks.addCPUSkinningFallback(0, mesh);
  60957. }
  60958. //Attributes
  60959. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60960. if (this._defines.NORMAL) {
  60961. attribs.push(BABYLON.VertexBuffer.NormalKind);
  60962. }
  60963. if (this._defines.UV1) {
  60964. attribs.push(BABYLON.VertexBuffer.UVKind);
  60965. }
  60966. if (this._defines.UV2) {
  60967. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60968. }
  60969. if (this._defines.VERTEXCOLOR) {
  60970. attribs.push(BABYLON.VertexBuffer.ColorKind);
  60971. }
  60972. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  60973. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  60974. // Legacy browser patch
  60975. var shaderName = "pbr";
  60976. if (!scene.getEngine().getCaps().standardDerivatives) {
  60977. shaderName = "legacypbr";
  60978. }
  60979. var join = this._defines.toString();
  60980. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  60981. "vFogInfos", "vFogColor", "pointSize",
  60982. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  60983. "mBones",
  60984. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  60985. "depthValues",
  60986. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  60987. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  60988. "logarithmicDepthConstant",
  60989. "vSphericalX", "vSphericalY", "vSphericalZ",
  60990. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  60991. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  60992. "vMicrosurfaceTextureLods",
  60993. "vCameraInfos"
  60994. ];
  60995. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  60996. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  60997. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  60998. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  60999. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  61000. }
  61001. if (!this._effect.isReady()) {
  61002. return false;
  61003. }
  61004. this._renderId = scene.getRenderId();
  61005. this._wasPreviouslyReady = true;
  61006. if (mesh) {
  61007. if (!mesh._materialDefines) {
  61008. mesh._materialDefines = new PBRMaterialDefines();
  61009. }
  61010. this._defines.cloneTo(mesh._materialDefines);
  61011. }
  61012. return true;
  61013. };
  61014. PBRMaterial.prototype.unbind = function () {
  61015. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  61016. this._effect.setTexture("reflection2DSampler", null);
  61017. }
  61018. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  61019. this._effect.setTexture("refraction2DSampler", null);
  61020. }
  61021. _super.prototype.unbind.call(this);
  61022. };
  61023. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  61024. this._effect.setMatrix("world", world);
  61025. };
  61026. PBRMaterial.prototype.bind = function (world, mesh) {
  61027. this._myScene = this.getScene();
  61028. // Matrices
  61029. this.bindOnlyWorldMatrix(world);
  61030. // Bones
  61031. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  61032. if (this._myScene.getCachedMaterial() !== this) {
  61033. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  61034. if (BABYLON.StandardMaterial.FresnelEnabled) {
  61035. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  61036. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  61037. }
  61038. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  61039. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  61040. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  61041. }
  61042. }
  61043. // Textures
  61044. if (this._myScene.texturesEnabled) {
  61045. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  61046. this._effect.setTexture("albedoSampler", this.albedoTexture);
  61047. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  61048. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  61049. }
  61050. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  61051. this._effect.setTexture("ambientSampler", this.ambientTexture);
  61052. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  61053. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  61054. }
  61055. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  61056. this._effect.setTexture("opacitySampler", this.opacityTexture);
  61057. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  61058. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  61059. }
  61060. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  61061. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  61062. if (this.reflectionTexture.isCube) {
  61063. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  61064. }
  61065. else {
  61066. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  61067. }
  61068. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  61069. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  61070. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  61071. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  61072. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  61073. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  61074. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  61075. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  61076. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  61077. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  61078. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  61079. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  61080. }
  61081. }
  61082. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  61083. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  61084. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  61085. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  61086. }
  61087. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  61088. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  61089. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  61090. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  61091. }
  61092. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  61093. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  61094. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  61095. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  61096. }
  61097. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  61098. this._effect.setTexture("bumpSampler", this.bumpTexture);
  61099. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  61100. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  61101. }
  61102. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  61103. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  61104. var depth = 1.0;
  61105. if (this.refractionTexture.isCube) {
  61106. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  61107. }
  61108. else {
  61109. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  61110. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  61111. if (this.refractionTexture.depth) {
  61112. depth = this.refractionTexture.depth;
  61113. }
  61114. }
  61115. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  61116. }
  61117. if ((this.reflectionTexture || this.refractionTexture)) {
  61118. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  61119. }
  61120. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  61121. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  61122. }
  61123. }
  61124. // Clip plane
  61125. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  61126. // Point size
  61127. if (this.pointsCloud) {
  61128. this._effect.setFloat("pointSize", this.pointSize);
  61129. }
  61130. // Colors
  61131. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  61132. // GAMMA CORRECTION.
  61133. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  61134. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  61135. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  61136. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  61137. // GAMMA CORRECTION.
  61138. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  61139. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  61140. // GAMMA CORRECTION.
  61141. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  61142. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  61143. }
  61144. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  61145. // GAMMA CORRECTION.
  61146. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  61147. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  61148. // Lights
  61149. if (this._myScene.lightsEnabled && !this.disableLighting) {
  61150. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  61151. }
  61152. // View
  61153. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  61154. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  61155. }
  61156. // Fog
  61157. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  61158. this._lightingInfos.x = this.directIntensity;
  61159. this._lightingInfos.y = this.emissiveIntensity;
  61160. this._lightingInfos.z = this.environmentIntensity;
  61161. this._lightingInfos.w = this.specularIntensity;
  61162. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  61163. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  61164. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  61165. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  61166. this._cameraInfos.x = this.cameraExposure;
  61167. this._cameraInfos.y = this.cameraContrast;
  61168. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  61169. if (this.cameraColorCurves) {
  61170. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  61171. }
  61172. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  61173. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  61174. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  61175. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  61176. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  61177. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  61178. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  61179. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  61180. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  61181. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  61182. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  61183. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  61184. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  61185. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  61186. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  61187. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  61188. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  61189. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  61190. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  61191. // Log. depth
  61192. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  61193. }
  61194. _super.prototype.bind.call(this, world, mesh);
  61195. this._myScene = null;
  61196. };
  61197. PBRMaterial.prototype.getAnimatables = function () {
  61198. var results = [];
  61199. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  61200. results.push(this.albedoTexture);
  61201. }
  61202. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  61203. results.push(this.ambientTexture);
  61204. }
  61205. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  61206. results.push(this.opacityTexture);
  61207. }
  61208. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  61209. results.push(this.reflectionTexture);
  61210. }
  61211. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  61212. results.push(this.emissiveTexture);
  61213. }
  61214. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  61215. results.push(this.reflectivityTexture);
  61216. }
  61217. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  61218. results.push(this.bumpTexture);
  61219. }
  61220. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  61221. results.push(this.lightmapTexture);
  61222. }
  61223. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  61224. results.push(this.refractionTexture);
  61225. }
  61226. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  61227. results.push(this.cameraColorGradingTexture);
  61228. }
  61229. return results;
  61230. };
  61231. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  61232. if (forceDisposeTextures) {
  61233. if (this.albedoTexture) {
  61234. this.albedoTexture.dispose();
  61235. }
  61236. if (this.ambientTexture) {
  61237. this.ambientTexture.dispose();
  61238. }
  61239. if (this.opacityTexture) {
  61240. this.opacityTexture.dispose();
  61241. }
  61242. if (this.reflectionTexture) {
  61243. this.reflectionTexture.dispose();
  61244. }
  61245. if (this.emissiveTexture) {
  61246. this.emissiveTexture.dispose();
  61247. }
  61248. if (this.reflectivityTexture) {
  61249. this.reflectivityTexture.dispose();
  61250. }
  61251. if (this.bumpTexture) {
  61252. this.bumpTexture.dispose();
  61253. }
  61254. if (this.lightmapTexture) {
  61255. this.lightmapTexture.dispose();
  61256. }
  61257. if (this.refractionTexture) {
  61258. this.refractionTexture.dispose();
  61259. }
  61260. if (this.cameraColorGradingTexture) {
  61261. this.cameraColorGradingTexture.dispose();
  61262. }
  61263. }
  61264. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  61265. };
  61266. PBRMaterial.prototype.clone = function (name) {
  61267. var _this = this;
  61268. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  61269. };
  61270. PBRMaterial.prototype.serialize = function () {
  61271. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61272. serializationObject.customType = "BABYLON.PBRMaterial";
  61273. return serializationObject;
  61274. };
  61275. // Statics
  61276. PBRMaterial.Parse = function (source, scene, rootUrl) {
  61277. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  61278. };
  61279. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  61280. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  61281. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  61282. PBRMaterial._scaledReflection = new BABYLON.Color3();
  61283. __decorate([
  61284. BABYLON.serialize()
  61285. ], PBRMaterial.prototype, "directIntensity", void 0);
  61286. __decorate([
  61287. BABYLON.serialize()
  61288. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  61289. __decorate([
  61290. BABYLON.serialize()
  61291. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  61292. __decorate([
  61293. BABYLON.serialize()
  61294. ], PBRMaterial.prototype, "specularIntensity", void 0);
  61295. __decorate([
  61296. BABYLON.serialize()
  61297. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  61298. __decorate([
  61299. BABYLON.serialize()
  61300. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  61301. __decorate([
  61302. BABYLON.serialize()
  61303. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  61304. __decorate([
  61305. BABYLON.serialize()
  61306. ], PBRMaterial.prototype, "cameraExposure", void 0);
  61307. __decorate([
  61308. BABYLON.serialize()
  61309. ], PBRMaterial.prototype, "cameraContrast", void 0);
  61310. __decorate([
  61311. BABYLON.serializeAsTexture()
  61312. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  61313. __decorate([
  61314. BABYLON.serializeAsColorCurves()
  61315. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  61316. __decorate([
  61317. BABYLON.serializeAsColor3()
  61318. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  61319. __decorate([
  61320. BABYLON.serialize()
  61321. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  61322. __decorate([
  61323. BABYLON.serializeAsColor3()
  61324. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  61325. __decorate([
  61326. BABYLON.serialize()
  61327. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  61328. __decorate([
  61329. BABYLON.serializeAsColor3()
  61330. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  61331. __decorate([
  61332. BABYLON.serialize()
  61333. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  61334. __decorate([
  61335. BABYLON.serializeAsColor3()
  61336. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  61337. __decorate([
  61338. BABYLON.serialize()
  61339. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  61340. __decorate([
  61341. BABYLON.serializeAsColor3()
  61342. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  61343. __decorate([
  61344. BABYLON.serialize()
  61345. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  61346. __decorate([
  61347. BABYLON.serialize()
  61348. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  61349. __decorate([
  61350. BABYLON.serialize()
  61351. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  61352. __decorate([
  61353. BABYLON.serializeAsTexture()
  61354. ], PBRMaterial.prototype, "albedoTexture", void 0);
  61355. __decorate([
  61356. BABYLON.serializeAsTexture()
  61357. ], PBRMaterial.prototype, "ambientTexture", void 0);
  61358. __decorate([
  61359. BABYLON.serializeAsTexture()
  61360. ], PBRMaterial.prototype, "opacityTexture", void 0);
  61361. __decorate([
  61362. BABYLON.serializeAsTexture()
  61363. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  61364. __decorate([
  61365. BABYLON.serializeAsTexture()
  61366. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  61367. __decorate([
  61368. BABYLON.serializeAsTexture()
  61369. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  61370. __decorate([
  61371. BABYLON.serializeAsTexture()
  61372. ], PBRMaterial.prototype, "bumpTexture", void 0);
  61373. __decorate([
  61374. BABYLON.serializeAsTexture()
  61375. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  61376. __decorate([
  61377. BABYLON.serializeAsTexture()
  61378. ], PBRMaterial.prototype, "refractionTexture", void 0);
  61379. __decorate([
  61380. BABYLON.serializeAsColor3("ambient")
  61381. ], PBRMaterial.prototype, "ambientColor", void 0);
  61382. __decorate([
  61383. BABYLON.serializeAsColor3("albedo")
  61384. ], PBRMaterial.prototype, "albedoColor", void 0);
  61385. __decorate([
  61386. BABYLON.serializeAsColor3("reflectivity")
  61387. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  61388. __decorate([
  61389. BABYLON.serializeAsColor3("reflection")
  61390. ], PBRMaterial.prototype, "reflectionColor", void 0);
  61391. __decorate([
  61392. BABYLON.serializeAsColor3("emissive")
  61393. ], PBRMaterial.prototype, "emissiveColor", void 0);
  61394. __decorate([
  61395. BABYLON.serialize()
  61396. ], PBRMaterial.prototype, "microSurface", void 0);
  61397. __decorate([
  61398. BABYLON.serialize()
  61399. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  61400. __decorate([
  61401. BABYLON.serialize()
  61402. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  61403. __decorate([
  61404. BABYLON.serializeAsFresnelParameters()
  61405. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  61406. __decorate([
  61407. BABYLON.serializeAsFresnelParameters()
  61408. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  61409. __decorate([
  61410. BABYLON.serialize()
  61411. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  61412. __decorate([
  61413. BABYLON.serialize()
  61414. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  61415. __decorate([
  61416. BABYLON.serialize()
  61417. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  61418. __decorate([
  61419. BABYLON.serialize()
  61420. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  61421. __decorate([
  61422. BABYLON.serialize()
  61423. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  61424. __decorate([
  61425. BABYLON.serialize()
  61426. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  61427. __decorate([
  61428. BABYLON.serialize()
  61429. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  61430. __decorate([
  61431. BABYLON.serialize()
  61432. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  61433. __decorate([
  61434. BABYLON.serialize()
  61435. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  61436. __decorate([
  61437. BABYLON.serialize()
  61438. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  61439. __decorate([
  61440. BABYLON.serialize()
  61441. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  61442. __decorate([
  61443. BABYLON.serialize()
  61444. ], PBRMaterial.prototype, "useParallax", void 0);
  61445. __decorate([
  61446. BABYLON.serialize()
  61447. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  61448. __decorate([
  61449. BABYLON.serialize()
  61450. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  61451. __decorate([
  61452. BABYLON.serialize()
  61453. ], PBRMaterial.prototype, "disableLighting", void 0);
  61454. __decorate([
  61455. BABYLON.serialize()
  61456. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  61457. __decorate([
  61458. BABYLON.serialize()
  61459. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  61460. __decorate([
  61461. BABYLON.serialize()
  61462. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  61463. __decorate([
  61464. BABYLON.serialize()
  61465. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  61466. return PBRMaterial;
  61467. })(BABYLON.Material);
  61468. BABYLON.PBRMaterial = PBRMaterial;
  61469. })(BABYLON || (BABYLON = {}));
  61470. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec2 diffuseUV=vDiffuseUV;\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,diffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","ellipse2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","ellipse2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat ms=properties.z;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<ms) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=ms;\n}\nfloat angle=TWOPI*segi/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat ms=properties.z;\nfloat angle=TWOPI*(index-1.0)/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\n}\n#endif\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","legacydefaultPixelShader":"#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\nuniform vec2 vReflectionInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 normalW=normalize(vNormalW);\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\nglossiness=vSpecularColor.a;\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0..3]\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha=vDiffuseColor.a;\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor=texture2D(specularSampler,vSpecularUV).rgb*vSpecularInfos.y;\n#endif\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}","legacydefaultVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform mat4 reflectionMatrix;\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 coords=vec3(view*vec4(worldNormal,0.0));\nreturn vec3(reflectionMatrix*vec4(coords,1.0));\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn position;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef REFLECTION\nvReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),vNormalW);\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","legacypbrPixelShader":"precision mediump float;\n\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vAlbedoColor;\nuniform vec3 vReflectionColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#ifdef CAMERACOLORGRADING\nuniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;\n#endif\n\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution= vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance,alpha);\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor,cameraColorGrading2DSampler,vCameraColorGradingInfos,vCameraColorGradingScaleOffset);\n#endif\ngl_FragColor=finalColor;\n}","legacypbrVertexShader":"precision mediump float;\n\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","lines2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","lines2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute vec2 position;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec2 boundingMin;\natt vec2 boundingMax;\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=position.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","rect2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","rect2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n\n#define rsub0 17.0\n#define rsub1 33.0\n#define rsub2 49.0\n#define rsub3 65.0\n#define rsub 64.0\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (properties.z == 0.0) {\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<4.0) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=4.0;\n}\nif (segi == 0.0) {\npos2=vec2(1.0,1.0);\n} \nelse if (segi == 1.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (segi == 2.0) {\npos2=vec2(0.0,0.0);\n} \nelse {\npos2=vec2(0.0,1.0);\n}\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse if (index == 1.0) {\npos2=vec2(1.0,1.0);\n}\nelse if (index == 2.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (index == 3.0) {\npos2=vec2(0.0,0.0);\n}\nelse {\npos2=vec2(0.0,1.0);\n}\n#endif\n}\nelse\n{\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<rsub) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=rsub;\n}\n\nif (segi<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (segi<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (segi<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\n\nif (index<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (index<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (index<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\n}\n#endif\n}\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"#ifndef FULLFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\n#endif\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\n#ifndef FULLFLOAT\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=vec4(moment1,moment2,1.0,1.0);\n#endif\n#else\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","sprite2dPixelShader":"varying vec2 vUV;\nvarying float vOpacity;\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (color.a<0.05) {\ndiscard;\n}\ncolor.a*=vOpacity;\ngl_FragColor=color;\n}","sprite2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 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","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","text2dPixelShader":"varying vec4 vColor;\nvarying vec2 vUV;\n\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (color.a<0.05)\ndiscard;\ngl_FragColor=color*vColor;\n}","text2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 textureSize;\natt vec4 color;\natt float superSampleFactor;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y+sizeUV.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y);\n}\n\nelse if (index == 2.0) {\npos2=vec2(1.0,1.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y);\n}\n\nelse if (index == 3.0) {\npos2=vec2(1.0,0.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y+sizeUV.y);\n}\n\nvUV=(floor(vUV*textureSize)+vec2(0.0,0.0))/textureSize;\nvColor=color;\nvColor.a*=opacity;\nvec4 pos;\npos.xy=floor(pos2.xy*superSampleFactor*sizeUV*textureSize); \npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  61471. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpFragment":"#ifdef BUMP\nvec2 bumpUV=vBumpUV;\n#endif\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,bumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nvec2 uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,bumpUV,vBumpInfos.z);\n#else\nvec2 uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\ndiffuseUV+=uvOffset;\nbumpUV+=uvOffset;\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,bumpUV);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","colorCurves":"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","colorGrading":"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying float fFogDistance;\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW-lightDirection.xyz);\nNdotL=max(0.00000000001,dot(vNormal,-lightDirection.xyz));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif","pbrShadowFunctions":"\n#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n"};
  61472. 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,n){void 0===n&&(n=1.401298e-45);var r=t-i;return r>=-n&&n>=r},t.ToHex=function(t){var i=t.toString(16);return 15>=t?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,n){return void 0===i&&(i=0),void 0===n&&(n=1),Math.min(n,Math.max(i,t))},t}();t.MathTools=i;var n=function(){function n(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return n.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},n.prototype.getClassName=function(){return\"Color3\"},n.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},n.prototype.toColor4=function(t){return void 0===t&&(t=1),new r(this.r,this.g,this.b,t)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},n.prototype.multiply=function(t){return new n(this.r*t.r,this.g*t.g,this.b*t.b)},n.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},n.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},n.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},n.prototype.scale=function(t){return new n(this.r*t,this.g*t,this.b*t)},n.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},n.prototype.add=function(t){return new n(this.r+t.r,this.g+t.g,this.b+t.b)},n.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},n.prototype.subtract=function(t){return new n(this.r-t.r,this.g-t.g,this.b-t.b)},n.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},n.prototype.clone=function(){return new n(this.r,this.g,this.b)},n.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},n.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},n.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)},n.prototype.toLinearSpace=function(){var t=new n;return this.toLinearSpaceToRef(t),t},n.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},n.prototype.toGammaSpace=function(){var t=new n;return this.toGammaSpaceToRef(t),t},n.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},n.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new n(0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return n.FromInts(i,r,o)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1],t[i+2])},n.FromInts=function(t,i,r){return new n(t/255,i/255,r/255)},n.Lerp=function(t,i,r){var o=t.r+(i.r-t.r)*r,e=t.g+(i.g-t.g)*r,s=t.b+(i.b-t.b)*r;return new n(o,e,s)},n.Red=function(){return new n(1,0,0)},n.Green=function(){return new n(0,1,0)},n.Blue=function(){return new n(0,0,1)},n.Black=function(){return new n(0,0,0)},n.White=function(){return new n(1,1,1)},n.Purple=function(){return new n(.5,0,.5)},n.Magenta=function(){return new n(1,0,1)},n.Yellow=function(){return new n(1,1,0)},n.Gray=function(){return new n(.5,.5,.5)},n}();t.Color3=n;var r=function(){function t(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,i.a=this.a*t.a,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var n=parseInt(i.substring(1,3),16),r=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(n,r,o,e)},t.Lerp=function(i,n,r){var o=new t(0,0,0,0);return t.LerpToRef(i,n,r,o),o},t.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},t.FromArray=function(i,n){return void 0===n&&(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.FromInts=function(i,n,r,o){return new t(i/255,n/255,r/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},t}();t.Color4=r;var o=function(){function n(t,i){this.x=t,this.y=i}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},n.prototype.getClassName=function(){return\"Vector2\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},n.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},n.prototype.addVector3=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},n.prototype.multiplyByFloats=function(t,i){return new n(this.x*t,this.y*i)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},n.prototype.negate=function(){return new n(-this.x,-this.y)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t)},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},n.prototype.clone=function(){return new n(this.x,this.y)},n.Zero=function(){return new n(0,0)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},n.CatmullRom=function(t,i,r,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+r.x)*e+(2*t.x-5*i.x+4*r.x-o.x)*s+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*e+(2*t.y-5*i.y+4*r.y-o.y)*s+(-t.y+3*i.y-3*r.y+o.y)*h);return new n(a,u)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>r.y?r.y:e,e=e<i.y?i.y:e,new n(o,e)},n.Hermite=function(t,i,r,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y;return new n(c,p)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,e=t.y+(i.y-t.y)*r;return new n(o,e)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y},n.Normalize=function(t){var i=t.clone();return i.normalize(),i},n.Minimize=function(t,i){var r=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new n(r,o)},n.Maximize=function(t,i){var r=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new n(r,o)},n.Transform=function(t,i){var r=n.Zero();return n.TransformToRef(t,i,r),r},n.TransformToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];n.x=r,n.y=o},n.PointInTriangle=function(t,i,n,r){var o=.5*(-n.y*r.x+i.y*(-n.x+r.x)+i.x*(n.y-r.y)+n.x*r.y),e=0>o?-1:1,s=(i.y*r.x-i.x*r.y+(r.y-i.y)*t.x+(i.x-r.x)*t.y)*e,h=(i.x*n.y-i.y*n.x+(i.y-n.y)*t.x+(n.x-i.x)*t.y)*e;return s>0&&h>0&&2*o*e>s+h},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.DistanceOfPointFromSegment=function(t,i,r){var o=n.DistanceSquared(i,r);if(0===o)return n.Distance(t,i);var e=r.subtract(i),s=Math.max(0,Math.min(1,n.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return n.Distance(t,h)},n}();t.Vector2=o;var e=function(){function n(t,i,n){this.x=t,this.y=i,this.z=n}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},n.prototype.getClassName=function(){return\"Vector3\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},n.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),e=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return t.x=r*s,t.y=-o*s,t.z=n*e,t.w=i*e,t},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},n.prototype.subtractFromFloats=function(t,i,r){return new n(this.x-t,this.y-i,this.z-r)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)},n.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},n.prototype.multiplyByFloats=function(t,i,r){return new n(this.x*t,this.y*i,this.z*r)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},n.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},n.prototype.clone=function(){return new n(this.x,this.y,this.z)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},n.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},n.GetClipFactor=function(t,i,r,o){var e=n.Dot(t,r)-o,s=n.Dot(i,r)-o,h=e/(e-s);return h},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromFloatArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},n.Zero=function(){return new n(0,0,0)},n.Up=function(){return new n(0,1,0)},n.TransformCoordinates=function(t,i){var r=n.Zero();return n.TransformCoordinatesToRef(t,i,r),r},n.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/s,n.y=o/s,n.z=e/s},n.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var e=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],s=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=e/a,o.y=s/a,o.z=h/a},n.TransformNormal=function(t,i){var r=n.Zero();return n.TransformNormalToRef(t,i,r),r},n.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},n.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},n.CatmullRom=function(t,i,r,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+r.x)*e+(2*t.x-5*i.x+4*r.x-o.x)*s+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*e+(2*t.y-5*i.y+4*r.y-o.y)*s+(-t.y+3*i.y-3*r.y+o.y)*h),m=.5*(2*i.z+(-t.z+r.z)*e+(2*t.z-5*i.z+4*r.z-o.z)*s+(-t.z+3*i.z-3*r.z+o.z)*h);return new n(a,u,m)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>r.y?r.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>r.z?r.z:s,s=s<i.z?i.z:s,new n(o,e,s)},n.Hermite=function(t,i,r,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y,f=t.z*a+r.z*u+i.z*m+o.z*y;return new n(c,p,f)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,e=t.y+(i.y-t.y)*r,s=t.z+(i.z-t.z)*r;return new n(o,e,s)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},n.Cross=function(t,i){var r=n.Zero();return n.CrossToRef(t,i,r),r},n.CrossToRef=function(t,i,n){M.Vector3[0].x=t.y*i.z-t.z*i.y,M.Vector3[0].y=t.z*i.x-t.x*i.z,M.Vector3[0].z=t.x*i.y-t.y*i.x,n.copyFrom(M.Vector3[0])},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Project=function(t,i,r,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=n._viewportMatrixCache?n._viewportMatrixCache:n._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,1,0,h+e/2,s/2+a,0,1,m);var y=n._matrixCache?n._matrixCache:n._matrixCache=new u;return i.multiplyToRef(r,y),y.multiplyToRef(m,y),n.TransformCoordinates(t,y)},n.UnprojectFromTransform=function(t,r,o,e,s){var h=n._matrixCache?n._matrixCache:n._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/r*2-1,t.y=-(t.y/o*2-1);var a=n.TransformCoordinates(t,h),m=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(m,1)&&(a=a.scale(1/m)),a},n.Unproject=function(t,r,o,e,s,h){var a=n._matrixCache?n._matrixCache:n._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new n(t.x/r*2-1,-(t.y/o*2-1),t.z),y=n.TransformCoordinates(m,a),c=m.x*a.m[3]+m.y*a.m[7]+m.z*a.m[11]+a.m[15];return i.WithinEpsilon(c,1)&&(y=y.scale(1/c)),y},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.RotationFromAxis=function(t,i,r){var o=n.Zero();return n.RotationFromAxisToRef(t,i,r,o),o},n.RotationFromAxisToRef=function(r,o,e,s){var h=r.normalize(),a=e.normalize(),u=p.X,m=p.Y,y=0,c=0,f=0,l=0,x=0,z=0,w=0,v=-1,d=0,g=M.Vector3[0],T=0,R=M.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?l=1:(w=a.z/a.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),R.x=l,R.y=x,R.z=z,R.normalize(),n.CrossToRef(h,R,g),g.normalize(),n.Dot(a,g)<0&&(v=1),T=n.Dot(h,R),T=Math.min(1,Math.max(-1,T)),f=Math.acos(T)*v,n.Dot(R,u)<0&&(f=Math.PI+f,R=R.scaleInPlace(-1),d++);var _=M.Vector3[2],b=M.Vector3[3];l=0,x=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?l=1:(w=R.z/R.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),_.x=l,_.y=x,_.z=z,_.normalize(),n.CrossToRef(_,R,b),b.normalize(),n.CrossToRef(a,_,g),g.normalize(),n.Dot(R,g)<0&&(v=1),T=n.Dot(a,_),T=Math.min(1,Math.max(-1,T)),c=Math.acos(T)*v,n.Dot(b,m)<0&&(c=Math.PI+c,d++),v=-1,n.CrossToRef(u,R,g),g.normalize(),n.Dot(g,m)<0&&(v=1),T=n.Dot(R,u),T=Math.min(1,Math.max(-1,T)),y=-Math.acos(T)*v,0>T&&2>d&&(y=Math.PI+y),s.x=c,s.y=y,s.z=f},n}();t.Vector3=e;var s=function(){function n(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},n.prototype.getClassName=function(){return\"Vector4\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},n.prototype.subtractFromFloats=function(t,i,r,o){return new n(this.x-t,this.y-i,this.z-r,this.w-o)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z,-this.w)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t,this.w*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)&&i.WithinEpsilon(this.w,n.w,r)},n.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},n.prototype.multiplyByFloats=function(t,i,r,o){return new n(this.x*t,this.y*i,this.z*r,this.w*o)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},n.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},n.prototype.clone=function(){return new n(this.x,this.y,this.z,this.w)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},n.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2],t[i+3])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},n.Zero=function(){return new n(0,0,0,0)},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return n*n+r*r+o*o+e*e},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n}();t.Vector4=s;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.toString=function(){return\"{W: \"+this.width+\", H: \"+this.height+\"}\"},t.prototype.getClassName=function(){return\"Size\"},t.prototype.getHashCode=function(){var t=this.width||0;return t=397*t^(this.height||0)},t.prototype.copyFrom=function(t){this.width=t.width,this.height=t.height},t.prototype.copyFromFloats=function(t,i){this.width=t,this.height=i},t.prototype.multiplyByFloats=function(i,n){return new t(this.width*i,this.height*n)},t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return t?this.width===t.width&&this.height===t.height:!1},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t.prototype.add=function(i){var n=new t(this.width+i.width,this.height+i.height);return n},t.prototype.substract=function(i){var n=new t(this.width-i.width,this.height-i.height);return n},t.Lerp=function(i,n,r){var o=i.width+(n.width-i.width)*r,e=i.height+(n.height-i.height)*r;return new t(o,e)},t}();t.Size=h;var a=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.getClassName=function(){return\"Quaternion\"},t.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,e=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,e),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t(-this.x,-this.y,-this.z,this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n,r,o,e=this.x,s=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=e*s+h*a;if(u>.499&&(n=2*Math.atan2(e,a),r=Math.PI/2,o=0),-.499>u&&(n=-2*Math.atan2(e,a),r=-Math.PI/2,o=0),isNaN(n)){var m=e*e,y=s*s,c=h*h;n=Math.atan2(2*s*a-2*e*h,1-2*y-2*c),r=Math.asin(2*u),o=Math.atan2(2*e*a-2*s*h,1-2*m-2*c)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=n,t.z=r,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,e=this.z*this.w,s=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+e),t.m[2]=2*(s-h),t.m[3]=0,t.m[4]=2*(o-e),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(s+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],e=r[4],s=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(s-m)*n,i.z=(h-e)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(e+h)/n,i.z=(s+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(s-m)/n,i.x=(e+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-e)/n,i.x=(s+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){return t.RotationAxisToRef(i,n,new t)},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(i/2);return t.normalize(),n.w=Math.cos(i/2),n.x=t.x*r,n.y=t.y*r,n.z=t.z*r,n},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,e=.5*i,s=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(e),m=Math.cos(e),y=Math.sin(s),c=Math.cos(s);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),e=.5*(n-t),s=.5*i;r.x=Math.cos(e)*Math.sin(s),r.y=Math.sin(e)*Math.sin(s),r.z=Math.sin(o)*Math.cos(s),r.w=Math.cos(o)*Math.cos(s)},t.Slerp=function(i,n,r){var o,e,s=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(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*n.x,e*i.y+o*n.y,e*i.z+o*n.z,e*i.w+o*n.w)},t}();t.Quaternion=a;var u=function(){function t(){this.m=new Float32Array(16)}return t.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14]},t.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],e=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*e)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*e)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},t.prototype.add=function(i){var n=new t;return this.addToRef(i,n),n},t.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},t.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],e=this.m[4],s=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,d=u*x-c*p,g=u*l-y*p,T=u*f-m*p,R=s*z-h*w+a*v,_=-(e*z-h*d+a*g),M=e*w-s*d+a*T,b=-(e*v-s*g+h*T),F=1/(i*R+n*_+r*M+o*b),A=h*x-a*l,L=s*x-a*f,C=s*l-h*f,P=e*x-a*p,Z=e*l-h*p,S=e*f-s*p,I=h*c-a*y,q=s*c-a*m,H=s*y-h*m,N=e*c-a*u,V=e*y-h*u,D=e*m-s*u;return t.m[0]=R*F,t.m[4]=_*F,t.m[8]=M*F,t.m[12]=b*F,t.m[1]=-(n*z-r*w+o*v)*F,t.m[5]=(i*z-r*d+o*g)*F,t.m[9]=-(i*w-n*d+o*T)*F,t.m[13]=(i*v-n*g+r*T)*F,t.m[2]=(n*A-r*L+o*C)*F,t.m[6]=-(i*A-r*P+o*Z)*F,t.m[10]=(i*L-n*P+o*S)*F,t.m[14]=-(i*C-n*Z+r*S)*F,t.m[3]=-(n*I-r*q+o*H)*F,t.m[7]=(i*I-r*N+o*V)*F,t.m[11]=-(i*q-n*N+o*D)*F,t.m[15]=(i*H-n*V+r*D)*F,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},t.prototype.multiply=function(i){var n=new t;return this.multiplyToRef(i,n),n},t.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},t.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),\nthis},t.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],e=this.m[2],s=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],b=t.m[7],F=t.m[8],A=t.m[9],L=t.m[10],C=t.m[11],P=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];return i[n]=r*v+o*R+e*F+s*P,i[n+1]=r*d+o*_+e*A+s*Z,i[n+2]=r*g+o*M+e*L+s*S,i[n+3]=r*T+o*b+e*C+s*I,i[n+4]=h*v+a*R+u*F+m*P,i[n+5]=h*d+a*_+u*A+m*Z,i[n+6]=h*g+a*M+u*L+m*S,i[n+7]=h*T+a*b+u*C+m*I,i[n+8]=y*v+c*R+p*F+f*P,i[n+9]=y*d+c*_+p*A+f*Z,i[n+10]=y*g+c*M+p*L+f*S,i[n+11]=y*T+c*b+p*C+f*I,i[n+12]=l*v+x*R+z*F+w*P,i[n+13]=l*d+x*_+z*A+w*Z,i[n+14]=l*g+x*M+z*L+w*S,i[n+15]=l*T+x*b+z*C+w*I,this},t.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},t.prototype.clone=function(){return t.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},t.prototype.getClassName=function(){return\"Matrix\"},t.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;16>i;i++)t=397*t^(this.m[i]||0);return t},t.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var e=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,s=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=t.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return a.FromRotationMatrixToRef(u,r),!0},t.FromArray=function(i,n){var r=new t;return n||(n=0),t.FromArrayToRef(i,n,r),r},t.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},t.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},t.FromValuesToRef=function(t,i,n,r,o,e,s,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=e,x.m[6]=s,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},t.prototype.getRow=function(t){if(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 n=4*t;return this.m[n+0]=i.x,this.m[n+1]=i.y,this.m[n+2]=i.z,this.m[n+3]=i.w,this},t.FromValues=function(i,n,r,o,e,s,h,a,u,m,y,c,p,f,l,x){var z=new t;return z.m[0]=i,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=e,z.m[5]=s,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},t.Compose=function(i,n,r){var o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),e=t.Identity();return n.toRotationMatrix(e),o=o.multiply(e),o.setTranslation(r),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var n=new t;return t.RotationXToRef(i,n),n},t.Invert=function(i){var n=new t;return i.invertToRef(n),n},t.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationY=function(i){var n=new t;return t.RotationYToRef(i,n),n},t.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationZ=function(i){var n=new t;return t.RotationZToRef(i,n),n},t.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationAxis=function(i,n){var r=t.Zero();return t.RotationAxisToRef(i,n,r),r},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),e=1-o;t.normalize(),n.m[0]=t.x*t.x*e+o,n.m[1]=t.x*t.y*e-t.z*r,n.m[2]=t.x*t.z*e+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*e+t.z*r,n.m[5]=t.y*t.y*e+o,n.m[6]=t.y*t.z*e-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*e-t.y*r,n.m[9]=t.z*t.y*e+t.x*r,n.m[10]=t.z*t.z*e+o,n.m[11]=0,n.m[15]=1},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){a.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},t.Scaling=function(i,n,r){var o=t.Zero();return t.ScalingToRef(i,n,r,o),o},t.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},t.Translation=function(i,n,r){var o=t.Identity();return t.TranslationToRef(i,n,r,o),o},t.TranslationToRef=function(i,n,r,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,n,r,1,o)},t.Lerp=function(i,n,r){for(var o=t.Zero(),e=0;16>e;e++)o.m[e]=i.m[e]*(1-r)+n.m[e]*r;return o},t.DecomposeLerp=function(i,n,r){var o=new e(0,0,0),s=new a,h=new e(0,0,0);i.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);n.decompose(u,m,y);var c=e.Lerp(o,u,r),p=a.Slerp(s,m,r),f=e.Lerp(h,y,r);return t.Compose(c,p,f)},t.LookAtLH=function(i,n,r){var o=t.Zero();return t.LookAtLHToRef(i,n,r,o),o},t.LookAtLHToRef=function(i,n,r,o){n.subtractToRef(i,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,i),h=-e.Dot(this._yAxis,i),a=-e.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},t.OrthoLH=function(i,n,r,o){var e=t.Zero();return t.OrthoLHToRef(i,n,r,o,e),e},t.OrthoLHToRef=function(i,n,r,o,e){var s=2/i,h=2/n,a=1/(o-r),u=r/(r-o);t.FromValuesToRef(s,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,e)},t.OrthoOffCenterLH=function(i,n,r,o,e,s){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,n,r,o,e,s,h),h},t.OrthoOffCenterLHToRef=function(t,i,n,r,o,e,s){s.m[0]=2/(i-t),s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2/(r-n),s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-1/(o-e),s.m[8]=s.m[9]=s.m[11]=0,s.m[12]=(t+i)/(t-i),s.m[13]=(r+n)/(n-r),s.m[14]=o/(o-e),s.m[15]=1},t.PerspectiveLH=function(i,n,r,o){var e=t.Zero();return e.m[0]=2*r/i,e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2*r/n,e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-o/(r-o),e.m[8]=e.m[9]=0,e.m[11]=1,e.m[12]=e.m[13]=e.m[15]=0,e.m[14]=r*o/(r-o),e},t.PerspectiveFovLH=function(i,n,r,o){var e=t.Zero();return t.PerspectiveFovLHToRef(i,n,r,o,e),e},t.PerspectiveFovLHToRef=function(t,i,n,r,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=-r/(n-r),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=n*r/(n-r)},t.GetFinalMatrix=function(i,n,r,o,e,s){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,s-e,0,u+h/2,a/2+m,e,1);return n.multiply(r).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},t.Transpose=function(i){var n=new t;return n.m[0]=i.m[0],n.m[1]=i.m[4],n.m[2]=i.m[8],n.m[3]=i.m[12],n.m[4]=i.m[1],n.m[5]=i.m[5],n.m[6]=i.m[9],n.m[7]=i.m[13],n.m[8]=i.m[2],n.m[9]=i.m[6],n.m[10]=i.m[10],n.m[11]=i.m[14],n.m[12]=i.m[3],n.m[13]=i.m[7],n.m[14]=i.m[11],n.m[15]=i.m[15],n},t.Reflection=function(i){var n=new t;return t.ReflectionToRef(i,n),n},t.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,e=-2*n,s=-2*r,h=-2*o;i.m[0]=e*n+1,i.m[1]=s*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=e*r,i.m[5]=s*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=e*o,i.m[9]=s*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=e*t.d,i.m[13]=s*t.d,i.m[14]=h*t.d,i.m[15]=1},t._tempQuaternion=new a,t._xAxis=e.Zero(),t._yAxis=e.Zero(),t._zAxis=e.Zero(),t}();t.Matrix=u;var m=function(){function t(t,i,n,r){this.normal=new e(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.getClassName=function(){return\"Plane\"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=u.Transpose(i),r=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=r*n.m[0]+o*n.m[1]+e*n.m[2]+s*n.m[3],a=r*n.m[4]+o*n.m[5]+e*n.m[6]+s*n.m[7],m=r*n.m[8]+o*n.m[9]+e*n.m[10]+s*n.m[11],y=r*n.m[12]+o*n.m[13]+e*n.m[14]+s*n.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=e*u-s*a,y=s*h-o*u,c=o*a-e*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=e.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(n,i)+r},t}();t.Plane=m;var y=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i,n){return new t(this.x*i,this.y*n,this.width*i,this.height*n)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new m(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var p=(t.Space,function(){function t(){}return t.X=new e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=p;var f=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var e=1-3*r+3*i,s=3*r-6*i,h=3*i,a=t,u=0;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*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=f,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var l=t.Orientation,x=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=x;var z=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,s=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-n.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-n.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=x.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=x.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=x.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?l.CW:l.CCW,this.angle=x.FromDegrees(this.orientation===l.CW?a-m:m-a)}return t}();t.Arc2=z;var w=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var n=new o(t,i),r=this._points[this._points.length-1];return this._points.push(n),this._length+=n.subtract(r).length(),this},t.prototype.addArcTo=function(t,i,n,r,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(n,r),u=new z(s,h,a),m=u.angle.radians()/e;u.orientation===l.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;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],n=this._points[0];t+=n.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(0>t||t>1)return o.Zero();for(var i=t*this.length(),n=0,r=0;r<this._points.length;r++){var e=(r+1)%this._points.length,s=this._points[r],h=this._points[e],a=h.subtract(s),u=a.length()+n;if(i>=n&&u>=i){var m=a.normalize(),y=i-n;return new o(s.x+m.x*y,s.y+m.y*y)}n=u}return o.Zero()},t.StartingAt=function(i,n){return new t(i,n)},t}();t.Path2=w;var v=function(){function n(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return n.prototype.getCurve=function(){return this._curve},n.prototype.getTangents=function(){return this._tangents},n.prototype.getNormals=function(){return this._normals},n.prototype.getBinormals=function(){return this._binormals},n.prototype.getDistances=function(){return this._distances},n.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},n.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;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()},n.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},n.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},n.prototype._normalVector=function(n,r,o){var s,h=r.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(r.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(r.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(r.z)/h,1,t.Epsilon)||(a=new e(0,0,1)):a=new e(1,0,0):a=new e(0,-1,0),s=e.Cross(r,a)}else s=e.Cross(r,o),e.CrossToRef(s,r,s);return s.normalize(),s},n}();t.Path3D=v;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;o>=a;a++)s.push(new e(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(s)},t.CreateCubicBezier=function(i,n,r,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,n,r,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return e},u=0;s>=u;u++)h.push(new e(a(u/s,i.x,n.x,r.x,o.x),a(u/s,i.y,n.y,r.y,o.y),a(u/s,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,s){for(var h=new Array,a=1/s,u=0;s>=u;u++)h.push(e.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)r.push(o[e].subtract(o[0]).add(n));var s=new t(r);return s},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=d;var g=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,n){var r=new e(i.r,i.g,i.b),o=r.scale(n);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=g;var T=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=T;var R=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=R;var _=function(){function t(t,i,n){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===n&&(n=o.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var M=function(){function t(){}return t.Color3=[n.Black(),n.Black(),n.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],t.Vector4=[s.Zero(),s.Zero(),s.Zero()],t.Quaternion=[new a(0,0,0,0)],t.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
  61473. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  61474. module.exports = BABYLON;
  61475. };