babylon.max.js 3.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196
  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._uintIndicesCurrentlySet = false;
  6206. this._currentBoundBuffer = new Array();
  6207. this._currentBufferPointers = [];
  6208. this._currentInstanceLocations = new Array();
  6209. this._currentInstanceBuffers = new Array();
  6210. this._renderingCanvas = canvas;
  6211. this._externalData = new BABYLON.StringDictionary();
  6212. options = options || {};
  6213. if (antialias != null) {
  6214. options.antialias = antialias;
  6215. }
  6216. if (options.preserveDrawingBuffer === undefined) {
  6217. options.preserveDrawingBuffer = false;
  6218. }
  6219. // Checks if some of the format renders first to allow the use of webgl inspector.
  6220. var renderToFullFloat = this._canRenderToFloatTexture();
  6221. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  6222. // GL
  6223. //try {
  6224. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6225. // if (this._gl) {
  6226. // this._webGLVersion = "2.0";
  6227. // }
  6228. //} catch (e) {
  6229. // // Do nothing
  6230. //}
  6231. if (!this._gl) {
  6232. try {
  6233. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6234. }
  6235. catch (e) {
  6236. throw new Error("WebGL not supported");
  6237. }
  6238. }
  6239. if (!this._gl) {
  6240. throw new Error("WebGL not supported");
  6241. }
  6242. this._onBlur = function () {
  6243. _this._windowIsBackground = true;
  6244. };
  6245. this._onFocus = function () {
  6246. _this._windowIsBackground = false;
  6247. };
  6248. window.addEventListener("blur", this._onBlur);
  6249. window.addEventListener("focus", this._onFocus);
  6250. // Viewport
  6251. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6252. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6253. this.resize();
  6254. // Caps
  6255. this._isStencilEnable = options.stencil;
  6256. this._caps = new EngineCapabilities();
  6257. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6258. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6259. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6260. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6261. // Infos
  6262. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6263. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6264. if (rendererInfo != null) {
  6265. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6266. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6267. }
  6268. if (!this._glVendor) {
  6269. this._glVendor = "Unknown vendor";
  6270. }
  6271. if (!this._glRenderer) {
  6272. this._glRenderer = "Unknown renderer";
  6273. }
  6274. // Extensions
  6275. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6276. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6277. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6278. 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');
  6279. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6280. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6281. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6282. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6283. this._caps.highPrecisionShaderSupported = true;
  6284. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6285. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6286. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6287. this._caps.textureFloatRender = renderToFullFloat;
  6288. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  6289. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  6290. this._caps.textureHalfFloatRender = renderToHalfFloat;
  6291. if (this._gl.getShaderPrecisionFormat) {
  6292. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6293. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6294. }
  6295. // Depth buffer
  6296. this.setDepthBuffer(true);
  6297. this.setDepthFunctionToLessOrEqual();
  6298. this.setDepthWrite(true);
  6299. // Fullscreen
  6300. this._onFullscreenChange = function () {
  6301. if (document.fullscreen !== undefined) {
  6302. _this.isFullscreen = document.fullscreen;
  6303. }
  6304. else if (document.mozFullScreen !== undefined) {
  6305. _this.isFullscreen = document.mozFullScreen;
  6306. }
  6307. else if (document.webkitIsFullScreen !== undefined) {
  6308. _this.isFullscreen = document.webkitIsFullScreen;
  6309. }
  6310. else if (document.msIsFullScreen !== undefined) {
  6311. _this.isFullscreen = document.msIsFullScreen;
  6312. }
  6313. // Pointer lock
  6314. if (_this.isFullscreen && _this._pointerLockRequested) {
  6315. canvas.requestPointerLock = canvas.requestPointerLock ||
  6316. canvas.msRequestPointerLock ||
  6317. canvas.mozRequestPointerLock ||
  6318. canvas.webkitRequestPointerLock;
  6319. if (canvas.requestPointerLock) {
  6320. canvas.requestPointerLock();
  6321. }
  6322. }
  6323. };
  6324. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6325. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6326. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6327. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6328. // Pointer lock
  6329. this._onPointerLockChange = function () {
  6330. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6331. document.webkitPointerLockElement === canvas ||
  6332. document.msPointerLockElement === canvas ||
  6333. document.pointerLockElement === canvas);
  6334. };
  6335. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6336. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6337. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6338. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6339. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6340. Engine.audioEngine = new BABYLON.AudioEngine();
  6341. }
  6342. //default loading screen
  6343. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6344. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6345. }
  6346. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6347. get: function () {
  6348. return Engine._ALPHA_DISABLE;
  6349. },
  6350. enumerable: true,
  6351. configurable: true
  6352. });
  6353. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6354. get: function () {
  6355. return Engine._ALPHA_ONEONE;
  6356. },
  6357. enumerable: true,
  6358. configurable: true
  6359. });
  6360. Object.defineProperty(Engine, "ALPHA_ADD", {
  6361. get: function () {
  6362. return Engine._ALPHA_ADD;
  6363. },
  6364. enumerable: true,
  6365. configurable: true
  6366. });
  6367. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6368. get: function () {
  6369. return Engine._ALPHA_COMBINE;
  6370. },
  6371. enumerable: true,
  6372. configurable: true
  6373. });
  6374. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6375. get: function () {
  6376. return Engine._ALPHA_SUBTRACT;
  6377. },
  6378. enumerable: true,
  6379. configurable: true
  6380. });
  6381. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6382. get: function () {
  6383. return Engine._ALPHA_MULTIPLY;
  6384. },
  6385. enumerable: true,
  6386. configurable: true
  6387. });
  6388. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6389. get: function () {
  6390. return Engine._ALPHA_MAXIMIZED;
  6391. },
  6392. enumerable: true,
  6393. configurable: true
  6394. });
  6395. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6396. get: function () {
  6397. return Engine._DELAYLOADSTATE_NONE;
  6398. },
  6399. enumerable: true,
  6400. configurable: true
  6401. });
  6402. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6403. get: function () {
  6404. return Engine._DELAYLOADSTATE_LOADED;
  6405. },
  6406. enumerable: true,
  6407. configurable: true
  6408. });
  6409. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6410. get: function () {
  6411. return Engine._DELAYLOADSTATE_LOADING;
  6412. },
  6413. enumerable: true,
  6414. configurable: true
  6415. });
  6416. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6417. get: function () {
  6418. return Engine._DELAYLOADSTATE_NOTLOADED;
  6419. },
  6420. enumerable: true,
  6421. configurable: true
  6422. });
  6423. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6424. get: function () {
  6425. return Engine._TEXTUREFORMAT_ALPHA;
  6426. },
  6427. enumerable: true,
  6428. configurable: true
  6429. });
  6430. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6431. get: function () {
  6432. return Engine._TEXTUREFORMAT_LUMINANCE;
  6433. },
  6434. enumerable: true,
  6435. configurable: true
  6436. });
  6437. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6438. get: function () {
  6439. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6440. },
  6441. enumerable: true,
  6442. configurable: true
  6443. });
  6444. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6445. get: function () {
  6446. return Engine._TEXTUREFORMAT_RGB;
  6447. },
  6448. enumerable: true,
  6449. configurable: true
  6450. });
  6451. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6452. get: function () {
  6453. return Engine._TEXTUREFORMAT_RGBA;
  6454. },
  6455. enumerable: true,
  6456. configurable: true
  6457. });
  6458. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6459. get: function () {
  6460. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6461. },
  6462. enumerable: true,
  6463. configurable: true
  6464. });
  6465. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6466. get: function () {
  6467. return Engine._TEXTURETYPE_FLOAT;
  6468. },
  6469. enumerable: true,
  6470. configurable: true
  6471. });
  6472. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  6473. get: function () {
  6474. return Engine._TEXTURETYPE_HALF_FLOAT;
  6475. },
  6476. enumerable: true,
  6477. configurable: true
  6478. });
  6479. Object.defineProperty(Engine, "Version", {
  6480. get: function () {
  6481. return "2.5-alpha";
  6482. },
  6483. enumerable: true,
  6484. configurable: true
  6485. });
  6486. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6487. get: function () {
  6488. return this._webGLVersion;
  6489. },
  6490. enumerable: true,
  6491. configurable: true
  6492. });
  6493. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  6494. /**
  6495. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  6496. */
  6497. get: function () {
  6498. return this._isStencilEnable;
  6499. },
  6500. enumerable: true,
  6501. configurable: true
  6502. });
  6503. Engine.prototype._prepareWorkingCanvas = function () {
  6504. if (this._workingCanvas) {
  6505. return;
  6506. }
  6507. this._workingCanvas = document.createElement("canvas");
  6508. this._workingContext = this._workingCanvas.getContext("2d");
  6509. };
  6510. Engine.prototype.resetTextureCache = function () {
  6511. for (var index = 0; index < this._maxTextureChannels; index++) {
  6512. this._activeTexturesCache[index] = null;
  6513. }
  6514. };
  6515. Engine.prototype.getGlInfo = function () {
  6516. return {
  6517. vendor: this._glVendor,
  6518. renderer: this._glRenderer,
  6519. version: this._glVersion
  6520. };
  6521. };
  6522. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  6523. if (useScreen === void 0) { useScreen = false; }
  6524. var viewport = camera.viewport;
  6525. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  6526. };
  6527. Engine.prototype.getRenderWidth = function (useScreen) {
  6528. if (useScreen === void 0) { useScreen = false; }
  6529. if (!useScreen && this._currentRenderTarget) {
  6530. return this._currentRenderTarget._width;
  6531. }
  6532. return this._renderingCanvas.width;
  6533. };
  6534. Engine.prototype.getRenderHeight = function (useScreen) {
  6535. if (useScreen === void 0) { useScreen = false; }
  6536. if (!useScreen && this._currentRenderTarget) {
  6537. return this._currentRenderTarget._height;
  6538. }
  6539. return this._renderingCanvas.height;
  6540. };
  6541. Engine.prototype.getRenderingCanvas = function () {
  6542. return this._renderingCanvas;
  6543. };
  6544. Engine.prototype.getRenderingCanvasClientRect = function () {
  6545. return this._renderingCanvas.getBoundingClientRect();
  6546. };
  6547. Engine.prototype.setHardwareScalingLevel = function (level) {
  6548. this._hardwareScalingLevel = level;
  6549. this.resize();
  6550. };
  6551. Engine.prototype.getHardwareScalingLevel = function () {
  6552. return this._hardwareScalingLevel;
  6553. };
  6554. Engine.prototype.getLoadedTexturesCache = function () {
  6555. return this._loadedTexturesCache;
  6556. };
  6557. Engine.prototype.getCaps = function () {
  6558. return this._caps;
  6559. };
  6560. Object.defineProperty(Engine.prototype, "drawCalls", {
  6561. get: function () {
  6562. return this._drawCalls.current;
  6563. },
  6564. enumerable: true,
  6565. configurable: true
  6566. });
  6567. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  6568. get: function () {
  6569. return this._drawCalls;
  6570. },
  6571. enumerable: true,
  6572. configurable: true
  6573. });
  6574. Engine.prototype.getDepthFunction = function () {
  6575. return this._depthCullingState.depthFunc;
  6576. };
  6577. Engine.prototype.setDepthFunction = function (depthFunc) {
  6578. this._depthCullingState.depthFunc = depthFunc;
  6579. };
  6580. Engine.prototype.setDepthFunctionToGreater = function () {
  6581. this._depthCullingState.depthFunc = this._gl.GREATER;
  6582. };
  6583. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  6584. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  6585. };
  6586. Engine.prototype.setDepthFunctionToLess = function () {
  6587. this._depthCullingState.depthFunc = this._gl.LESS;
  6588. };
  6589. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  6590. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  6591. };
  6592. Engine.prototype.getStencilBuffer = function () {
  6593. return this._stencilState.stencilTest;
  6594. };
  6595. Engine.prototype.setStencilBuffer = function (enable) {
  6596. this._stencilState.stencilTest = enable;
  6597. };
  6598. Engine.prototype.getStencilMask = function () {
  6599. return this._stencilState.stencilMask;
  6600. };
  6601. Engine.prototype.setStencilMask = function (mask) {
  6602. this._stencilState.stencilMask = mask;
  6603. };
  6604. Engine.prototype.getStencilFunction = function () {
  6605. return this._stencilState.stencilFunc;
  6606. };
  6607. Engine.prototype.getStencilFunctionReference = function () {
  6608. return this._stencilState.stencilFuncRef;
  6609. };
  6610. Engine.prototype.getStencilFunctionMask = function () {
  6611. return this._stencilState.stencilFuncMask;
  6612. };
  6613. Engine.prototype.setStencilFunction = function (stencilFunc) {
  6614. this._stencilState.stencilFunc = stencilFunc;
  6615. };
  6616. Engine.prototype.setStencilFunctionReference = function (reference) {
  6617. this._stencilState.stencilFuncRef = reference;
  6618. };
  6619. Engine.prototype.setStencilFunctionMask = function (mask) {
  6620. this._stencilState.stencilFuncMask = mask;
  6621. };
  6622. Engine.prototype.getStencilOperationFail = function () {
  6623. return this._stencilState.stencilOpStencilFail;
  6624. };
  6625. Engine.prototype.getStencilOperationDepthFail = function () {
  6626. return this._stencilState.stencilOpDepthFail;
  6627. };
  6628. Engine.prototype.getStencilOperationPass = function () {
  6629. return this._stencilState.stencilOpStencilDepthPass;
  6630. };
  6631. Engine.prototype.setStencilOperationFail = function (operation) {
  6632. this._stencilState.stencilOpStencilFail = operation;
  6633. };
  6634. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  6635. this._stencilState.stencilOpDepthFail = operation;
  6636. };
  6637. Engine.prototype.setStencilOperationPass = function (operation) {
  6638. this._stencilState.stencilOpStencilDepthPass = operation;
  6639. };
  6640. /**
  6641. * stop executing a render loop function and remove it from the execution array
  6642. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  6643. */
  6644. Engine.prototype.stopRenderLoop = function (renderFunction) {
  6645. if (!renderFunction) {
  6646. this._activeRenderLoops = [];
  6647. return;
  6648. }
  6649. var index = this._activeRenderLoops.indexOf(renderFunction);
  6650. if (index >= 0) {
  6651. this._activeRenderLoops.splice(index, 1);
  6652. }
  6653. };
  6654. Engine.prototype._renderLoop = function () {
  6655. var shouldRender = true;
  6656. if (!this.renderEvenInBackground && this._windowIsBackground) {
  6657. shouldRender = false;
  6658. }
  6659. if (shouldRender) {
  6660. // Start new frame
  6661. this.beginFrame();
  6662. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  6663. var renderFunction = this._activeRenderLoops[index];
  6664. renderFunction();
  6665. }
  6666. // Present
  6667. this.endFrame();
  6668. }
  6669. if (this._activeRenderLoops.length > 0) {
  6670. // Register new frame
  6671. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6672. }
  6673. else {
  6674. this._renderingQueueLaunched = false;
  6675. }
  6676. };
  6677. /**
  6678. * Register and execute a render loop. The engine can have more than one render function.
  6679. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  6680. * @example
  6681. * engine.runRenderLoop(function () {
  6682. * scene.render()
  6683. * })
  6684. */
  6685. Engine.prototype.runRenderLoop = function (renderFunction) {
  6686. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  6687. return;
  6688. }
  6689. this._activeRenderLoops.push(renderFunction);
  6690. if (!this._renderingQueueLaunched) {
  6691. this._renderingQueueLaunched = true;
  6692. this._bindedRenderFunction = this._renderLoop.bind(this);
  6693. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6694. }
  6695. };
  6696. /**
  6697. * Toggle full screen mode.
  6698. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  6699. * @param {any} options - an options object to be sent to the requestFullscreen function
  6700. */
  6701. Engine.prototype.switchFullscreen = function (requestPointerLock, options) {
  6702. if (this.isFullscreen) {
  6703. BABYLON.Tools.ExitFullscreen();
  6704. }
  6705. else {
  6706. this._pointerLockRequested = requestPointerLock;
  6707. BABYLON.Tools.RequestFullscreen(this._renderingCanvas, options);
  6708. }
  6709. };
  6710. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  6711. if (stencil === void 0) { stencil = false; }
  6712. this.applyStates();
  6713. var mode = 0;
  6714. if (backBuffer) {
  6715. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  6716. mode |= this._gl.COLOR_BUFFER_BIT;
  6717. }
  6718. if (depth) {
  6719. this._gl.clearDepth(1.0);
  6720. mode |= this._gl.DEPTH_BUFFER_BIT;
  6721. }
  6722. if (stencil) {
  6723. this._gl.clearStencil(0);
  6724. mode |= this._gl.STENCIL_BUFFER_BIT;
  6725. }
  6726. this._gl.clear(mode);
  6727. };
  6728. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  6729. var gl = this._gl;
  6730. // Save state
  6731. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  6732. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  6733. // Change state
  6734. gl.enable(gl.SCISSOR_TEST);
  6735. gl.scissor(x, y, width, height);
  6736. // Clear
  6737. this.clear(clearColor, true, true, true);
  6738. // Restore state
  6739. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  6740. if (curScissor === true) {
  6741. gl.enable(gl.SCISSOR_TEST);
  6742. }
  6743. else {
  6744. gl.disable(gl.SCISSOR_TEST);
  6745. }
  6746. };
  6747. /**
  6748. * Set the WebGL's viewport
  6749. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  6750. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  6751. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  6752. */
  6753. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  6754. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  6755. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  6756. var x = viewport.x || 0;
  6757. var y = viewport.y || 0;
  6758. this._cachedViewport = viewport;
  6759. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  6760. };
  6761. /**
  6762. * Directly set the WebGL Viewport
  6763. * The x, y, width & height are directly passed to the WebGL call
  6764. * @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.
  6765. */
  6766. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  6767. var currentViewport = this._cachedViewport;
  6768. this._cachedViewport = null;
  6769. this._gl.viewport(x, y, width, height);
  6770. return currentViewport;
  6771. };
  6772. Engine.prototype.beginFrame = function () {
  6773. this._measureFps();
  6774. };
  6775. Engine.prototype.endFrame = function () {
  6776. //this.flushFramebuffer();
  6777. };
  6778. /**
  6779. * resize the view according to the canvas' size.
  6780. * @example
  6781. * window.addEventListener("resize", function () {
  6782. * engine.resize();
  6783. * });
  6784. */
  6785. Engine.prototype.resize = function () {
  6786. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  6787. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  6788. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  6789. for (var index = 0; index < this.scenes.length; index++) {
  6790. var scene = this.scenes[index];
  6791. if (BABYLON.DebugLayer && scene.debugLayer.isVisible()) {
  6792. scene.debugLayer._syncPositions();
  6793. }
  6794. }
  6795. };
  6796. /**
  6797. * force a specific size of the canvas
  6798. * @param {number} width - the new canvas' width
  6799. * @param {number} height - the new canvas' height
  6800. */
  6801. Engine.prototype.setSize = function (width, height) {
  6802. this._renderingCanvas.width = width;
  6803. this._renderingCanvas.height = height;
  6804. for (var index = 0; index < this.scenes.length; index++) {
  6805. var scene = this.scenes[index];
  6806. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  6807. var cam = scene.cameras[camIndex];
  6808. cam._currentRenderId = 0;
  6809. }
  6810. }
  6811. };
  6812. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  6813. this._currentRenderTarget = texture;
  6814. this.bindUnboundFramebuffer(texture._framebuffer);
  6815. var gl = this._gl;
  6816. if (texture.isCube) {
  6817. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  6818. }
  6819. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  6820. this.wipeCaches();
  6821. };
  6822. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  6823. if (this._currentFramebuffer !== framebuffer) {
  6824. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  6825. this._currentFramebuffer = framebuffer;
  6826. }
  6827. };
  6828. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  6829. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  6830. this._currentRenderTarget = null;
  6831. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  6832. var gl = this._gl;
  6833. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6834. gl.generateMipmap(gl.TEXTURE_2D);
  6835. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  6836. }
  6837. this.bindUnboundFramebuffer(null);
  6838. };
  6839. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  6840. if (texture.generateMipMaps) {
  6841. var gl = this._gl;
  6842. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  6843. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6844. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  6845. }
  6846. };
  6847. Engine.prototype.flushFramebuffer = function () {
  6848. this._gl.flush();
  6849. };
  6850. Engine.prototype.restoreDefaultFramebuffer = function () {
  6851. this._currentRenderTarget = null;
  6852. this.bindUnboundFramebuffer(null);
  6853. this.setViewport(this._cachedViewport);
  6854. this.wipeCaches();
  6855. };
  6856. // VBOs
  6857. Engine.prototype._resetVertexBufferBinding = function () {
  6858. this.bindArrayBuffer(null);
  6859. this._cachedVertexBuffers = null;
  6860. };
  6861. Engine.prototype.createVertexBuffer = function (vertices) {
  6862. var vbo = this._gl.createBuffer();
  6863. this.bindArrayBuffer(vbo);
  6864. if (vertices instanceof Float32Array) {
  6865. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  6866. }
  6867. else {
  6868. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  6869. }
  6870. this._resetVertexBufferBinding();
  6871. vbo.references = 1;
  6872. return vbo;
  6873. };
  6874. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  6875. var vbo = this._gl.createBuffer();
  6876. this.bindArrayBuffer(vbo);
  6877. if (vertices instanceof Float32Array) {
  6878. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  6879. }
  6880. else {
  6881. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  6882. }
  6883. this._resetVertexBufferBinding();
  6884. vbo.references = 1;
  6885. return vbo;
  6886. };
  6887. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  6888. this.bindArrayBuffer(vertexBuffer);
  6889. if (offset === undefined) {
  6890. offset = 0;
  6891. }
  6892. if (count === undefined) {
  6893. if (vertices instanceof Float32Array) {
  6894. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6895. }
  6896. else {
  6897. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6898. }
  6899. }
  6900. else {
  6901. if (vertices instanceof Float32Array) {
  6902. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  6903. }
  6904. else {
  6905. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  6906. }
  6907. }
  6908. this._resetVertexBufferBinding();
  6909. };
  6910. Engine.prototype._resetIndexBufferBinding = function () {
  6911. this.bindIndexBuffer(null);
  6912. this._cachedIndexBuffer = null;
  6913. };
  6914. Engine.prototype.createIndexBuffer = function (indices) {
  6915. var vbo = this._gl.createBuffer();
  6916. this.bindIndexBuffer(vbo);
  6917. // Check for 32 bits indices
  6918. var arrayBuffer;
  6919. var need32Bits = false;
  6920. if (this._caps.uintIndices) {
  6921. for (var index = 0; index < indices.length; index++) {
  6922. if (indices[index] > 65535) {
  6923. need32Bits = true;
  6924. break;
  6925. }
  6926. }
  6927. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6928. }
  6929. else {
  6930. arrayBuffer = new Uint16Array(indices);
  6931. }
  6932. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6933. this._resetIndexBufferBinding();
  6934. vbo.references = 1;
  6935. vbo.is32Bits = need32Bits;
  6936. return vbo;
  6937. };
  6938. Engine.prototype.bindArrayBuffer = function (buffer) {
  6939. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  6940. };
  6941. Engine.prototype.bindIndexBuffer = function (buffer) {
  6942. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  6943. };
  6944. Engine.prototype.bindBuffer = function (buffer, target) {
  6945. if (this._currentBoundBuffer[target] !== buffer) {
  6946. this._gl.bindBuffer(target, buffer);
  6947. this._currentBoundBuffer[target] = buffer;
  6948. }
  6949. };
  6950. Engine.prototype.updateArrayBuffer = function (data) {
  6951. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6952. };
  6953. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  6954. var pointer = this._currentBufferPointers[indx];
  6955. var changed = false;
  6956. if (!pointer) {
  6957. changed = true;
  6958. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  6959. }
  6960. else {
  6961. if (pointer.buffer !== buffer) {
  6962. pointer.buffer = buffer;
  6963. changed = true;
  6964. }
  6965. if (pointer.size !== size) {
  6966. pointer.size = size;
  6967. changed = true;
  6968. }
  6969. if (pointer.type !== type) {
  6970. pointer.type = type;
  6971. changed = true;
  6972. }
  6973. if (pointer.normalized !== normalized) {
  6974. pointer.normalized = normalized;
  6975. changed = true;
  6976. }
  6977. if (pointer.stride !== stride) {
  6978. pointer.stride = stride;
  6979. changed = true;
  6980. }
  6981. if (pointer.offset !== offset) {
  6982. pointer.offset = offset;
  6983. changed = true;
  6984. }
  6985. }
  6986. if (changed) {
  6987. this.bindArrayBuffer(buffer);
  6988. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  6989. }
  6990. };
  6991. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6992. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6993. this._cachedVertexBuffers = vertexBuffer;
  6994. this._cachedEffectForVertexBuffers = effect;
  6995. var offset = 0;
  6996. for (var index = 0; index < vertexDeclaration.length; index++) {
  6997. var order = effect.getAttributeLocation(index);
  6998. if (order >= 0) {
  6999. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7000. }
  7001. offset += vertexDeclaration[index] * 4;
  7002. }
  7003. }
  7004. if (this._cachedIndexBuffer !== indexBuffer) {
  7005. this._cachedIndexBuffer = indexBuffer;
  7006. this.bindIndexBuffer(indexBuffer);
  7007. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7008. }
  7009. };
  7010. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7011. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7012. this._cachedVertexBuffers = vertexBuffers;
  7013. this._cachedEffectForVertexBuffers = effect;
  7014. var attributes = effect.getAttributesNames();
  7015. for (var index = 0; index < attributes.length; index++) {
  7016. var order = effect.getAttributeLocation(index);
  7017. if (order >= 0) {
  7018. var vertexBuffer = vertexBuffers[attributes[index]];
  7019. if (!vertexBuffer) {
  7020. continue;
  7021. }
  7022. var buffer = vertexBuffer.getBuffer();
  7023. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7024. if (vertexBuffer.getIsInstanced()) {
  7025. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  7026. this._currentInstanceLocations.push(order);
  7027. this._currentInstanceBuffers.push(buffer);
  7028. }
  7029. }
  7030. }
  7031. }
  7032. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  7033. this._cachedIndexBuffer = indexBuffer;
  7034. this.bindIndexBuffer(indexBuffer);
  7035. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7036. }
  7037. };
  7038. Engine.prototype.unbindInstanceAttributes = function () {
  7039. var boundBuffer;
  7040. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7041. var instancesBuffer = this._currentInstanceBuffers[i];
  7042. if (boundBuffer != instancesBuffer) {
  7043. boundBuffer = instancesBuffer;
  7044. this.bindArrayBuffer(instancesBuffer);
  7045. }
  7046. var offsetLocation = this._currentInstanceLocations[i];
  7047. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  7048. }
  7049. this._currentInstanceBuffers.length = 0;
  7050. this._currentInstanceLocations.length = 0;
  7051. };
  7052. Engine.prototype._releaseBuffer = function (buffer) {
  7053. buffer.references--;
  7054. if (buffer.references === 0) {
  7055. this._gl.deleteBuffer(buffer);
  7056. return true;
  7057. }
  7058. return false;
  7059. };
  7060. Engine.prototype.createInstancesBuffer = function (capacity) {
  7061. var buffer = this._gl.createBuffer();
  7062. buffer.capacity = capacity;
  7063. this.bindArrayBuffer(buffer);
  7064. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7065. return buffer;
  7066. };
  7067. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7068. this._gl.deleteBuffer(buffer);
  7069. };
  7070. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7071. this.bindArrayBuffer(instancesBuffer);
  7072. if (data) {
  7073. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7074. }
  7075. if (offsetLocations[0].index !== undefined) {
  7076. var stride = 0;
  7077. for (var i = 0; i < offsetLocations.length; i++) {
  7078. var ai = offsetLocations[i];
  7079. stride += ai.attributeSize * 4;
  7080. }
  7081. for (var i = 0; i < offsetLocations.length; i++) {
  7082. var ai = offsetLocations[i];
  7083. this._gl.enableVertexAttribArray(ai.index);
  7084. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7085. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  7086. this._currentInstanceLocations.push(ai.index);
  7087. this._currentInstanceBuffers.push(instancesBuffer);
  7088. }
  7089. }
  7090. else {
  7091. for (var index = 0; index < 4; index++) {
  7092. var offsetLocation = offsetLocations[index];
  7093. this._gl.enableVertexAttribArray(offsetLocation);
  7094. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7095. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  7096. this._currentInstanceLocations.push(offsetLocation);
  7097. this._currentInstanceBuffers.push(instancesBuffer);
  7098. }
  7099. }
  7100. };
  7101. Engine.prototype.applyStates = function () {
  7102. this._depthCullingState.apply(this._gl);
  7103. this._stencilState.apply(this._gl);
  7104. this._alphaState.apply(this._gl);
  7105. };
  7106. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7107. // Apply states
  7108. this.applyStates();
  7109. this._drawCalls.addCount(1, false);
  7110. // Render
  7111. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7112. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7113. if (instancesCount) {
  7114. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7115. return;
  7116. }
  7117. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7118. };
  7119. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7120. // Apply states
  7121. this.applyStates();
  7122. this._drawCalls.addCount(1, false);
  7123. if (instancesCount) {
  7124. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7125. return;
  7126. }
  7127. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7128. };
  7129. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7130. // Apply states
  7131. this.applyStates();
  7132. this._drawCalls.addCount(1, false);
  7133. if (instancesCount) {
  7134. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7135. return;
  7136. }
  7137. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7138. };
  7139. // Shaders
  7140. Engine.prototype._releaseEffect = function (effect) {
  7141. if (this._compiledEffects[effect._key]) {
  7142. delete this._compiledEffects[effect._key];
  7143. if (effect.getProgram()) {
  7144. this._gl.deleteProgram(effect.getProgram());
  7145. }
  7146. }
  7147. };
  7148. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7149. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7150. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7151. var name = vertex + "+" + fragment + "@" + defines;
  7152. if (this._compiledEffects[name]) {
  7153. return this._compiledEffects[name];
  7154. }
  7155. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7156. effect._key = name;
  7157. this._compiledEffects[name] = effect;
  7158. return effect;
  7159. };
  7160. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7161. if (uniformsNames === void 0) { uniformsNames = []; }
  7162. if (samplers === void 0) { samplers = []; }
  7163. if (defines === void 0) { defines = ""; }
  7164. return this.createEffect({
  7165. vertex: "particles",
  7166. fragmentElement: fragmentName
  7167. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7168. };
  7169. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7170. context = context || this._gl;
  7171. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  7172. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  7173. var shaderProgram = context.createProgram();
  7174. context.attachShader(shaderProgram, vertexShader);
  7175. context.attachShader(shaderProgram, fragmentShader);
  7176. context.linkProgram(shaderProgram);
  7177. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7178. if (!linked) {
  7179. var error = context.getProgramInfoLog(shaderProgram);
  7180. if (error) {
  7181. throw new Error(error);
  7182. }
  7183. }
  7184. context.deleteShader(vertexShader);
  7185. context.deleteShader(fragmentShader);
  7186. return shaderProgram;
  7187. };
  7188. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7189. var results = [];
  7190. for (var index = 0; index < uniformsNames.length; index++) {
  7191. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7192. }
  7193. return results;
  7194. };
  7195. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7196. var results = [];
  7197. for (var index = 0; index < attributesNames.length; index++) {
  7198. try {
  7199. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7200. }
  7201. catch (e) {
  7202. results.push(-1);
  7203. }
  7204. }
  7205. return results;
  7206. };
  7207. Engine.prototype.enableEffect = function (effect) {
  7208. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  7209. if (effect && effect.onBind) {
  7210. effect.onBind(effect);
  7211. }
  7212. return;
  7213. }
  7214. this._vertexAttribArraysToUse = this._vertexAttribArraysToUse || [];
  7215. this._vertexAttribArraysEnabled = this._vertexAttribArraysEnabled || [];
  7216. // Use program
  7217. this.setProgram(effect.getProgram());
  7218. var i, ul;
  7219. for (i = 0, ul = this._vertexAttribArraysToUse.length; i < ul; i++) {
  7220. this._vertexAttribArraysToUse[i] = false;
  7221. }
  7222. var attributesCount = effect.getAttributesCount();
  7223. for (i = 0; i < attributesCount; i++) {
  7224. // Attributes
  7225. var order = effect.getAttributeLocation(i);
  7226. if (order >= 0) {
  7227. this._vertexAttribArraysToUse[order] = true;
  7228. }
  7229. }
  7230. for (i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  7231. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArraysEnabled[i] || this._vertexAttribArraysToUse[i]) {
  7232. continue;
  7233. }
  7234. this._vertexAttribArraysEnabled[i] = false;
  7235. this._gl.disableVertexAttribArray(i);
  7236. }
  7237. for (i = 0, ul = this._vertexAttribArraysToUse.length; i < ul; i++) {
  7238. if (this._vertexAttribArraysToUse[i] && !this._vertexAttribArraysEnabled[i]) {
  7239. this._vertexAttribArraysEnabled[i] = true;
  7240. this._gl.enableVertexAttribArray(i);
  7241. }
  7242. }
  7243. this._currentEffect = effect;
  7244. if (effect.onBind) {
  7245. effect.onBind(effect);
  7246. }
  7247. };
  7248. Engine.prototype.setIntArray = function (uniform, array) {
  7249. if (!uniform)
  7250. return;
  7251. this._gl.uniform1iv(uniform, array);
  7252. };
  7253. Engine.prototype.setIntArray2 = function (uniform, array) {
  7254. if (!uniform || array.length % 2 !== 0)
  7255. return;
  7256. this._gl.uniform2iv(uniform, array);
  7257. };
  7258. Engine.prototype.setIntArray3 = function (uniform, array) {
  7259. if (!uniform || array.length % 3 !== 0)
  7260. return;
  7261. this._gl.uniform3iv(uniform, array);
  7262. };
  7263. Engine.prototype.setIntArray4 = function (uniform, array) {
  7264. if (!uniform || array.length % 4 !== 0)
  7265. return;
  7266. this._gl.uniform4iv(uniform, array);
  7267. };
  7268. Engine.prototype.setFloatArray = function (uniform, array) {
  7269. if (!uniform)
  7270. return;
  7271. this._gl.uniform1fv(uniform, array);
  7272. };
  7273. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7274. if (!uniform || array.length % 2 !== 0)
  7275. return;
  7276. this._gl.uniform2fv(uniform, array);
  7277. };
  7278. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7279. if (!uniform || array.length % 3 !== 0)
  7280. return;
  7281. this._gl.uniform3fv(uniform, array);
  7282. };
  7283. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7284. if (!uniform || array.length % 4 !== 0)
  7285. return;
  7286. this._gl.uniform4fv(uniform, array);
  7287. };
  7288. Engine.prototype.setArray = function (uniform, array) {
  7289. if (!uniform)
  7290. return;
  7291. this._gl.uniform1fv(uniform, array);
  7292. };
  7293. Engine.prototype.setArray2 = function (uniform, array) {
  7294. if (!uniform || array.length % 2 !== 0)
  7295. return;
  7296. this._gl.uniform2fv(uniform, array);
  7297. };
  7298. Engine.prototype.setArray3 = function (uniform, array) {
  7299. if (!uniform || array.length % 3 !== 0)
  7300. return;
  7301. this._gl.uniform3fv(uniform, array);
  7302. };
  7303. Engine.prototype.setArray4 = function (uniform, array) {
  7304. if (!uniform || array.length % 4 !== 0)
  7305. return;
  7306. this._gl.uniform4fv(uniform, array);
  7307. };
  7308. Engine.prototype.setMatrices = function (uniform, matrices) {
  7309. if (!uniform)
  7310. return;
  7311. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7312. };
  7313. Engine.prototype.setMatrix = function (uniform, matrix) {
  7314. if (!uniform)
  7315. return;
  7316. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7317. };
  7318. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7319. if (!uniform)
  7320. return;
  7321. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7322. };
  7323. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7324. if (!uniform)
  7325. return;
  7326. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7327. };
  7328. Engine.prototype.setFloat = function (uniform, value) {
  7329. if (!uniform)
  7330. return;
  7331. this._gl.uniform1f(uniform, value);
  7332. };
  7333. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7334. if (!uniform)
  7335. return;
  7336. this._gl.uniform2f(uniform, x, y);
  7337. };
  7338. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7339. if (!uniform)
  7340. return;
  7341. this._gl.uniform3f(uniform, x, y, z);
  7342. };
  7343. Engine.prototype.setBool = function (uniform, bool) {
  7344. if (!uniform)
  7345. return;
  7346. this._gl.uniform1i(uniform, bool);
  7347. };
  7348. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7349. if (!uniform)
  7350. return;
  7351. this._gl.uniform4f(uniform, x, y, z, w);
  7352. };
  7353. Engine.prototype.setColor3 = function (uniform, color3) {
  7354. if (!uniform)
  7355. return;
  7356. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7357. };
  7358. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7359. if (!uniform)
  7360. return;
  7361. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7362. };
  7363. // States
  7364. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7365. if (zOffset === void 0) { zOffset = 0; }
  7366. if (reverseSide === void 0) { reverseSide = false; }
  7367. // Culling
  7368. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7369. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7370. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7371. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7372. if (culling) {
  7373. this._depthCullingState.cullFace = cullFace;
  7374. this._depthCullingState.cull = true;
  7375. }
  7376. else {
  7377. this._depthCullingState.cull = false;
  7378. }
  7379. }
  7380. // Z offset
  7381. this._depthCullingState.zOffset = zOffset;
  7382. };
  7383. Engine.prototype.setDepthBuffer = function (enable) {
  7384. this._depthCullingState.depthTest = enable;
  7385. };
  7386. Engine.prototype.getDepthWrite = function () {
  7387. return this._depthCullingState.depthMask;
  7388. };
  7389. Engine.prototype.setDepthWrite = function (enable) {
  7390. this._depthCullingState.depthMask = enable;
  7391. };
  7392. Engine.prototype.setColorWrite = function (enable) {
  7393. this._gl.colorMask(enable, enable, enable, enable);
  7394. };
  7395. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7396. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7397. if (this._alphaMode === mode) {
  7398. return;
  7399. }
  7400. switch (mode) {
  7401. case Engine.ALPHA_DISABLE:
  7402. this._alphaState.alphaBlend = false;
  7403. break;
  7404. case Engine.ALPHA_COMBINE:
  7405. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7406. this._alphaState.alphaBlend = true;
  7407. break;
  7408. case Engine.ALPHA_ONEONE:
  7409. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7410. this._alphaState.alphaBlend = true;
  7411. break;
  7412. case Engine.ALPHA_ADD:
  7413. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7414. this._alphaState.alphaBlend = true;
  7415. break;
  7416. case Engine.ALPHA_SUBTRACT:
  7417. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7418. this._alphaState.alphaBlend = true;
  7419. break;
  7420. case Engine.ALPHA_MULTIPLY:
  7421. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7422. this._alphaState.alphaBlend = true;
  7423. break;
  7424. case Engine.ALPHA_MAXIMIZED:
  7425. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7426. this._alphaState.alphaBlend = true;
  7427. break;
  7428. }
  7429. if (!noDepthWriteChange) {
  7430. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7431. }
  7432. this._alphaMode = mode;
  7433. };
  7434. Engine.prototype.getAlphaMode = function () {
  7435. return this._alphaMode;
  7436. };
  7437. Engine.prototype.setAlphaTesting = function (enable) {
  7438. this._alphaTest = enable;
  7439. };
  7440. Engine.prototype.getAlphaTesting = function () {
  7441. return this._alphaTest;
  7442. };
  7443. // Textures
  7444. Engine.prototype.wipeCaches = function () {
  7445. this.resetTextureCache();
  7446. this._currentEffect = null;
  7447. this._stencilState.reset();
  7448. this._depthCullingState.reset();
  7449. this.setDepthFunctionToLessOrEqual();
  7450. this._alphaState.reset();
  7451. this._cachedVertexBuffers = null;
  7452. this._cachedIndexBuffer = null;
  7453. this._cachedEffectForVertexBuffers = null;
  7454. };
  7455. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7456. var gl = this._gl;
  7457. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7458. var magFilter = gl.NEAREST;
  7459. var minFilter = gl.NEAREST;
  7460. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7461. magFilter = gl.LINEAR;
  7462. minFilter = gl.LINEAR;
  7463. }
  7464. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7465. magFilter = gl.LINEAR;
  7466. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7467. }
  7468. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  7469. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  7470. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7471. texture.samplingMode = samplingMode;
  7472. };
  7473. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  7474. var _this = this;
  7475. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7476. if (onLoad === void 0) { onLoad = null; }
  7477. if (onError === void 0) { onError = null; }
  7478. if (buffer === void 0) { buffer = null; }
  7479. var texture = this._gl.createTexture();
  7480. var extension;
  7481. var fromData = false;
  7482. if (url.substr(0, 5) === "data:") {
  7483. fromData = true;
  7484. }
  7485. if (!fromData)
  7486. extension = url.substr(url.length - 4, 4).toLowerCase();
  7487. else {
  7488. var oldUrl = url;
  7489. fromData = oldUrl.split(':');
  7490. url = oldUrl;
  7491. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  7492. }
  7493. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7494. var isTGA = (extension === ".tga");
  7495. scene._addPendingData(texture);
  7496. texture.url = url;
  7497. texture.noMipmap = noMipmap;
  7498. texture.references = 1;
  7499. texture.samplingMode = samplingMode;
  7500. this._loadedTexturesCache.push(texture);
  7501. var onerror = function () {
  7502. scene._removePendingData(texture);
  7503. if (onError) {
  7504. onError();
  7505. }
  7506. };
  7507. var callback;
  7508. if (isTGA) {
  7509. callback = function (arrayBuffer) {
  7510. var data = new Uint8Array(arrayBuffer);
  7511. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  7512. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  7513. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  7514. }, onLoad, samplingMode);
  7515. };
  7516. if (!(fromData instanceof Array))
  7517. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  7518. callback(arrayBuffer);
  7519. }, onerror, scene.database, true);
  7520. else
  7521. callback(buffer);
  7522. }
  7523. else if (isDDS) {
  7524. callback = function (data) {
  7525. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7526. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  7527. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  7528. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  7529. }, onLoad, samplingMode);
  7530. };
  7531. if (!(fromData instanceof Array))
  7532. BABYLON.Tools.LoadFile(url, function (data) {
  7533. callback(data);
  7534. }, onerror, scene.database, true);
  7535. else
  7536. callback(buffer);
  7537. }
  7538. else {
  7539. var onload = function (img) {
  7540. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  7541. var isPot = (img.width === potWidth && img.height === potHeight);
  7542. if (!isPot) {
  7543. _this._prepareWorkingCanvas();
  7544. _this._workingCanvas.width = potWidth;
  7545. _this._workingCanvas.height = potHeight;
  7546. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7547. _this._workingContext.imageSmoothingEnabled = false;
  7548. _this._workingContext.mozImageSmoothingEnabled = false;
  7549. _this._workingContext.oImageSmoothingEnabled = false;
  7550. _this._workingContext.webkitImageSmoothingEnabled = false;
  7551. _this._workingContext.msImageSmoothingEnabled = false;
  7552. }
  7553. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  7554. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7555. _this._workingContext.imageSmoothingEnabled = true;
  7556. _this._workingContext.mozImageSmoothingEnabled = true;
  7557. _this._workingContext.oImageSmoothingEnabled = true;
  7558. _this._workingContext.webkitImageSmoothingEnabled = true;
  7559. _this._workingContext.msImageSmoothingEnabled = true;
  7560. }
  7561. }
  7562. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  7563. }, onLoad, samplingMode);
  7564. };
  7565. if (!(fromData instanceof Array))
  7566. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7567. else
  7568. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  7569. }
  7570. return texture;
  7571. };
  7572. Engine.prototype._getInternalFormat = function (format) {
  7573. var internalFormat = this._gl.RGBA;
  7574. switch (format) {
  7575. case Engine.TEXTUREFORMAT_ALPHA:
  7576. internalFormat = this._gl.ALPHA;
  7577. break;
  7578. case Engine.TEXTUREFORMAT_LUMINANCE:
  7579. internalFormat = this._gl.LUMINANCE;
  7580. break;
  7581. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  7582. internalFormat = this._gl.LUMINANCE_ALPHA;
  7583. break;
  7584. case Engine.TEXTUREFORMAT_RGB:
  7585. internalFormat = this._gl.RGB;
  7586. break;
  7587. case Engine.TEXTUREFORMAT_RGBA:
  7588. internalFormat = this._gl.RGBA;
  7589. break;
  7590. }
  7591. return internalFormat;
  7592. };
  7593. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  7594. if (compression === void 0) { compression = null; }
  7595. var internalFormat = this._getInternalFormat(format);
  7596. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7597. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7598. if (texture._width % 4 !== 0) {
  7599. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  7600. }
  7601. if (compression) {
  7602. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  7603. }
  7604. else {
  7605. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  7606. }
  7607. if (texture.generateMipMaps) {
  7608. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7609. }
  7610. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7611. this.resetTextureCache();
  7612. texture.isReady = true;
  7613. };
  7614. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  7615. if (compression === void 0) { compression = null; }
  7616. var texture = this._gl.createTexture();
  7617. texture._baseWidth = width;
  7618. texture._baseHeight = height;
  7619. texture._width = width;
  7620. texture._height = height;
  7621. texture.references = 1;
  7622. this.updateRawTexture(texture, data, format, invertY, compression);
  7623. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7624. // Filters
  7625. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  7626. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7627. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7628. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7629. texture.samplingMode = samplingMode;
  7630. this._loadedTexturesCache.push(texture);
  7631. return texture;
  7632. };
  7633. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  7634. var texture = this._gl.createTexture();
  7635. texture._baseWidth = width;
  7636. texture._baseHeight = height;
  7637. if (generateMipMaps) {
  7638. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  7639. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  7640. }
  7641. this.resetTextureCache();
  7642. texture._width = width;
  7643. texture._height = height;
  7644. texture.isReady = false;
  7645. texture.generateMipMaps = generateMipMaps;
  7646. texture.references = 1;
  7647. texture.samplingMode = samplingMode;
  7648. this.updateTextureSamplingMode(samplingMode, texture);
  7649. this._loadedTexturesCache.push(texture);
  7650. return texture;
  7651. };
  7652. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  7653. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  7654. if (texture.isCube) {
  7655. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  7656. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7657. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7658. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7659. }
  7660. else {
  7661. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7662. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7663. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7664. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7665. }
  7666. };
  7667. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  7668. if (premulAlpha === void 0) { premulAlpha = false; }
  7669. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7670. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  7671. if (premulAlpha) {
  7672. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  7673. }
  7674. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  7675. if (texture.generateMipMaps) {
  7676. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7677. }
  7678. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7679. this.resetTextureCache();
  7680. texture.isReady = true;
  7681. };
  7682. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  7683. if (texture._isDisabled) {
  7684. return;
  7685. }
  7686. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7687. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  7688. try {
  7689. // Testing video texture support
  7690. if (this._videoTextureSupported === undefined) {
  7691. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7692. if (this._gl.getError() !== 0) {
  7693. this._videoTextureSupported = false;
  7694. }
  7695. else {
  7696. this._videoTextureSupported = true;
  7697. }
  7698. }
  7699. // Copy video through the current working canvas if video texture is not supported
  7700. if (!this._videoTextureSupported) {
  7701. if (!texture._workingCanvas) {
  7702. texture._workingCanvas = document.createElement("canvas");
  7703. texture._workingContext = texture._workingCanvas.getContext("2d");
  7704. texture._workingCanvas.width = texture._width;
  7705. texture._workingCanvas.height = texture._height;
  7706. }
  7707. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  7708. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  7709. }
  7710. else {
  7711. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7712. }
  7713. if (texture.generateMipMaps) {
  7714. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7715. }
  7716. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7717. this.resetTextureCache();
  7718. texture.isReady = true;
  7719. }
  7720. catch (ex) {
  7721. // Something unexpected
  7722. // Let's disable the texture
  7723. texture._isDisabled = true;
  7724. }
  7725. };
  7726. Engine.prototype.createRenderTargetTexture = function (size, options) {
  7727. // old version had a "generateMipMaps" arg instead of options.
  7728. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  7729. // in the same way, generateDepthBuffer is defaulted to true
  7730. var generateMipMaps = false;
  7731. var generateDepthBuffer = true;
  7732. var generateStencilBuffer = false;
  7733. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7734. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7735. if (options !== undefined) {
  7736. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7737. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  7738. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  7739. type = options.type === undefined ? type : options.type;
  7740. if (options.samplingMode !== undefined) {
  7741. samplingMode = options.samplingMode;
  7742. }
  7743. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  7744. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  7745. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7746. }
  7747. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  7748. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  7749. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7750. }
  7751. }
  7752. var gl = this._gl;
  7753. var texture = gl.createTexture();
  7754. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7755. var width = size.width || size;
  7756. var height = size.height || size;
  7757. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7758. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  7759. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7760. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  7761. }
  7762. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7763. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7764. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7765. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7766. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  7767. var depthStencilBuffer;
  7768. // Create the depth/stencil buffer
  7769. if (generateStencilBuffer) {
  7770. depthStencilBuffer = gl.createRenderbuffer();
  7771. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  7772. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  7773. }
  7774. else if (generateDepthBuffer) {
  7775. depthStencilBuffer = gl.createRenderbuffer();
  7776. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  7777. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  7778. }
  7779. // Create the framebuffer
  7780. var framebuffer = gl.createFramebuffer();
  7781. this.bindUnboundFramebuffer(framebuffer);
  7782. // Manage attachments
  7783. if (generateStencilBuffer) {
  7784. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  7785. }
  7786. else if (generateDepthBuffer) {
  7787. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  7788. }
  7789. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  7790. if (generateMipMaps) {
  7791. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7792. }
  7793. // Unbind
  7794. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7795. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7796. this.bindUnboundFramebuffer(null);
  7797. texture._framebuffer = framebuffer;
  7798. if (generateDepthBuffer) {
  7799. texture._depthBuffer = depthStencilBuffer;
  7800. }
  7801. texture._baseWidth = width;
  7802. texture._baseHeight = height;
  7803. texture._width = width;
  7804. texture._height = height;
  7805. texture.isReady = true;
  7806. texture.generateMipMaps = generateMipMaps;
  7807. texture.references = 1;
  7808. texture.samplingMode = samplingMode;
  7809. texture.type = type;
  7810. this.resetTextureCache();
  7811. this._loadedTexturesCache.push(texture);
  7812. return texture;
  7813. };
  7814. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  7815. var gl = this._gl;
  7816. var texture = gl.createTexture();
  7817. var generateMipMaps = true;
  7818. var generateDepthBuffer = true;
  7819. var generateStencilBuffer = false;
  7820. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7821. if (options !== undefined) {
  7822. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7823. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  7824. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  7825. if (options.samplingMode !== undefined) {
  7826. samplingMode = options.samplingMode;
  7827. }
  7828. }
  7829. texture.isCube = true;
  7830. texture.references = 1;
  7831. texture.generateMipMaps = generateMipMaps;
  7832. texture.references = 1;
  7833. texture.samplingMode = samplingMode;
  7834. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7835. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7836. for (var face = 0; face < 6; face++) {
  7837. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  7838. }
  7839. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  7840. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  7841. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7842. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7843. // Create the depth buffer
  7844. var depthStencilBuffer;
  7845. // Create the depth/stencil buffer
  7846. if (generateStencilBuffer) {
  7847. depthStencilBuffer = gl.createRenderbuffer();
  7848. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  7849. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  7850. }
  7851. else if (generateDepthBuffer) {
  7852. depthStencilBuffer = gl.createRenderbuffer();
  7853. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  7854. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  7855. }
  7856. // Create the framebuffer
  7857. var framebuffer = gl.createFramebuffer();
  7858. this.bindUnboundFramebuffer(framebuffer);
  7859. // Manage attachments
  7860. if (generateStencilBuffer) {
  7861. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  7862. }
  7863. else if (generateDepthBuffer) {
  7864. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  7865. }
  7866. // Mipmaps
  7867. if (texture.generateMipMaps) {
  7868. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7869. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7870. }
  7871. // Unbind
  7872. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7873. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7874. this.bindUnboundFramebuffer(null);
  7875. texture._framebuffer = framebuffer;
  7876. if (generateDepthBuffer) {
  7877. texture._depthBuffer = depthStencilBuffer;
  7878. }
  7879. texture._width = size;
  7880. texture._height = size;
  7881. texture.isReady = true;
  7882. this.resetTextureCache();
  7883. this._loadedTexturesCache.push(texture);
  7884. return texture;
  7885. };
  7886. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  7887. var _this = this;
  7888. var gl = this._gl;
  7889. var texture = gl.createTexture();
  7890. texture.isCube = true;
  7891. texture.url = rootUrl;
  7892. texture.references = 1;
  7893. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  7894. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7895. if (isDDS) {
  7896. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  7897. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7898. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  7899. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7900. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  7901. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  7902. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  7903. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7904. }
  7905. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7906. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  7907. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7908. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7909. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7910. _this.resetTextureCache();
  7911. texture._width = info.width;
  7912. texture._height = info.height;
  7913. texture.isReady = true;
  7914. }, null, null, true);
  7915. }
  7916. else {
  7917. cascadeLoad(rootUrl, scene, function (imgs) {
  7918. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  7919. var height = width;
  7920. _this._prepareWorkingCanvas();
  7921. _this._workingCanvas.width = width;
  7922. _this._workingCanvas.height = height;
  7923. var faces = [
  7924. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7925. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7926. ];
  7927. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7928. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7929. for (var index = 0; index < faces.length; index++) {
  7930. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  7931. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  7932. }
  7933. if (!noMipmap) {
  7934. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7935. }
  7936. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7937. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7938. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7939. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7940. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7941. _this.resetTextureCache();
  7942. texture._width = width;
  7943. texture._height = height;
  7944. texture.isReady = true;
  7945. }, files);
  7946. }
  7947. return texture;
  7948. };
  7949. Engine.prototype.updateTextureSize = function (texture, width, height) {
  7950. texture._width = width;
  7951. texture._height = height;
  7952. texture._size = width * height;
  7953. texture._baseWidth = width;
  7954. texture._baseHeight = height;
  7955. };
  7956. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  7957. var _this = this;
  7958. var gl = this._gl;
  7959. var texture = gl.createTexture();
  7960. scene._addPendingData(texture);
  7961. texture.isCube = true;
  7962. texture.references = 1;
  7963. texture.url = url;
  7964. var internalFormat = this._getInternalFormat(format);
  7965. var textureType = gl.UNSIGNED_BYTE;
  7966. if (type === Engine.TEXTURETYPE_FLOAT) {
  7967. textureType = gl.FLOAT;
  7968. }
  7969. var width = size;
  7970. var height = width;
  7971. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7972. texture._width = width;
  7973. texture._height = height;
  7974. var onerror = function () {
  7975. scene._removePendingData(texture);
  7976. };
  7977. var internalCallback = function (data) {
  7978. var rgbeDataArrays = callback(data);
  7979. var facesIndex = [
  7980. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7981. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7982. ];
  7983. width = texture._width;
  7984. height = texture._height;
  7985. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7986. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7987. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7988. if (!noMipmap && isPot) {
  7989. if (mipmmapGenerator) {
  7990. var arrayTemp = [];
  7991. // Data are known to be in +X +Y +Z -X -Y -Z
  7992. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  7993. arrayTemp.push(rgbeDataArrays[0]); // +X
  7994. arrayTemp.push(rgbeDataArrays[3]); // -X
  7995. arrayTemp.push(rgbeDataArrays[1]); // +Y
  7996. arrayTemp.push(rgbeDataArrays[4]); // -Y
  7997. arrayTemp.push(rgbeDataArrays[2]); // +Z
  7998. arrayTemp.push(rgbeDataArrays[5]); // -Z
  7999. var mipData = mipmmapGenerator(arrayTemp);
  8000. for (var level = 0; level < mipData.length; level++) {
  8001. var mipSize = width >> level;
  8002. // mipData is order in +X -X +Y -Y +Z -Z
  8003. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  8004. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  8005. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  8006. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  8007. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  8008. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  8009. }
  8010. }
  8011. else {
  8012. // Data are known to be in +X +Y +Z -X -Y -Z
  8013. for (var index = 0; index < facesIndex.length; index++) {
  8014. var faceData = rgbeDataArrays[index];
  8015. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  8016. }
  8017. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8018. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  8019. // By following the webgl standard changes from Revision 7, 2014/11/24
  8020. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  8021. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  8022. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  8023. // Data are known to be in +X +Y +Z -X -Y -Z
  8024. for (var index = 0; index < facesIndex.length; index++) {
  8025. var faceData = rgbeDataArrays[index];
  8026. // Create a new RGBA Face.
  8027. var newFaceData = new Float32Array(width * height * 4);
  8028. for (var x = 0; x < width; x++) {
  8029. for (var y = 0; y < height; y++) {
  8030. var index_1 = (y * width + x) * 3;
  8031. var newIndex = (y * width + x) * 4;
  8032. // Map Old Value to new value.
  8033. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  8034. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  8035. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  8036. // Add fully opaque alpha channel.
  8037. newFaceData[newIndex + 3] = 1;
  8038. }
  8039. }
  8040. // Reupload the face.
  8041. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  8042. }
  8043. // Try to generate mipmap again.
  8044. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8045. }
  8046. }
  8047. }
  8048. else {
  8049. noMipmap = true;
  8050. }
  8051. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8052. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8053. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8054. }
  8055. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  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 {
  8060. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8061. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8062. }
  8063. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8064. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8065. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8066. texture.isReady = true;
  8067. _this.resetTextureCache();
  8068. scene._removePendingData(texture);
  8069. };
  8070. BABYLON.Tools.LoadFile(url, function (data) {
  8071. internalCallback(data);
  8072. }, onerror, scene.database, true);
  8073. return texture;
  8074. };
  8075. ;
  8076. Engine.prototype._releaseTexture = function (texture) {
  8077. var gl = this._gl;
  8078. if (texture._framebuffer) {
  8079. gl.deleteFramebuffer(texture._framebuffer);
  8080. }
  8081. if (texture._depthBuffer) {
  8082. gl.deleteRenderbuffer(texture._depthBuffer);
  8083. }
  8084. gl.deleteTexture(texture);
  8085. // Unbind channels
  8086. this.unbindAllTextures();
  8087. var index = this._loadedTexturesCache.indexOf(texture);
  8088. if (index !== -1) {
  8089. this._loadedTexturesCache.splice(index, 1);
  8090. }
  8091. };
  8092. Engine.prototype.setProgram = function (program) {
  8093. if (this._currentProgram !== program) {
  8094. this._gl.useProgram(program);
  8095. this._currentProgram = program;
  8096. }
  8097. };
  8098. Engine.prototype.bindSamplers = function (effect) {
  8099. this.setProgram(effect.getProgram());
  8100. var samplers = effect.getSamplers();
  8101. for (var index = 0; index < samplers.length; index++) {
  8102. var uniform = effect.getUniform(samplers[index]);
  8103. this._gl.uniform1i(uniform, index);
  8104. }
  8105. this._currentEffect = null;
  8106. };
  8107. Engine.prototype.activateTexture = function (texture) {
  8108. if (this._activeTexture !== texture) {
  8109. this._gl.activeTexture(texture);
  8110. this._activeTexture = texture;
  8111. }
  8112. };
  8113. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8114. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8115. this._gl.bindTexture(target, texture);
  8116. this._activeTexturesCache[this._activeTexture] = texture;
  8117. }
  8118. };
  8119. Engine.prototype._bindTexture = function (channel, texture) {
  8120. if (channel < 0) {
  8121. return;
  8122. }
  8123. this.activateTexture(this._gl["TEXTURE" + channel]);
  8124. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8125. };
  8126. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8127. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8128. };
  8129. Engine.prototype.unbindAllTextures = function () {
  8130. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8131. this.activateTexture(this._gl["TEXTURE" + channel]);
  8132. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8133. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8134. }
  8135. };
  8136. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8137. if (channel < 0) {
  8138. return;
  8139. }
  8140. this._gl.uniform1i(uniform, channel);
  8141. this._setTexture(channel, texture);
  8142. };
  8143. Engine.prototype._setTexture = function (channel, texture) {
  8144. // Not ready?
  8145. if (!texture || !texture.isReady()) {
  8146. if (this._activeTexturesCache[channel] != null) {
  8147. this.activateTexture(this._gl["TEXTURE" + channel]);
  8148. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8149. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8150. }
  8151. return;
  8152. }
  8153. // Video
  8154. var alreadyActivated = false;
  8155. if (texture instanceof BABYLON.VideoTexture) {
  8156. this.activateTexture(this._gl["TEXTURE" + channel]);
  8157. alreadyActivated = true;
  8158. texture.update();
  8159. }
  8160. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8161. texture.delayLoad();
  8162. return;
  8163. }
  8164. var internalTexture = texture.getInternalTexture();
  8165. if (this._activeTexturesCache[channel] === internalTexture) {
  8166. return;
  8167. }
  8168. if (!alreadyActivated) {
  8169. this.activateTexture(this._gl["TEXTURE" + channel]);
  8170. }
  8171. if (internalTexture.isCube) {
  8172. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8173. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8174. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8175. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8176. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8177. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8178. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8179. }
  8180. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8181. }
  8182. else {
  8183. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8184. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8185. internalTexture._cachedWrapU = texture.wrapU;
  8186. switch (texture.wrapU) {
  8187. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8188. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8189. break;
  8190. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8191. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8192. break;
  8193. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8194. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8195. break;
  8196. }
  8197. }
  8198. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8199. internalTexture._cachedWrapV = texture.wrapV;
  8200. switch (texture.wrapV) {
  8201. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8202. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8203. break;
  8204. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8205. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8206. break;
  8207. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8208. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8209. break;
  8210. }
  8211. }
  8212. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8213. }
  8214. };
  8215. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8216. if (channel < 0) {
  8217. return;
  8218. }
  8219. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8220. this._textureUnits = new Int32Array(textures.length);
  8221. }
  8222. for (var i = 0; i < textures.length; i++) {
  8223. this._textureUnits[i] = channel + i;
  8224. }
  8225. this._gl.uniform1iv(uniform, this._textureUnits);
  8226. for (var index = 0; index < textures.length; index++) {
  8227. this._setTexture(channel + index, textures[index]);
  8228. }
  8229. };
  8230. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8231. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8232. var value = texture.anisotropicFilteringLevel;
  8233. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8234. value = 1;
  8235. }
  8236. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8237. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8238. texture._cachedAnisotropicFilteringLevel = value;
  8239. }
  8240. };
  8241. Engine.prototype.readPixels = function (x, y, width, height) {
  8242. var data = new Uint8Array(height * width * 4);
  8243. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8244. return data;
  8245. };
  8246. /**
  8247. * Add an externaly attached data from its key.
  8248. * This method call will fail and return false, if such key already exists.
  8249. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8250. * @param key the unique key that identifies the data
  8251. * @param data the data object to associate to the key for this Engine instance
  8252. * @return true if no such key were already present and the data was added successfully, false otherwise
  8253. */
  8254. Engine.prototype.addExternalData = function (key, data) {
  8255. return this._externalData.add(key, data);
  8256. };
  8257. /**
  8258. * Get an externaly attached data from its key
  8259. * @param key the unique key that identifies the data
  8260. * @return the associated data, if present (can be null), or undefined if not present
  8261. */
  8262. Engine.prototype.getExternalData = function (key) {
  8263. return this._externalData.get(key);
  8264. };
  8265. /**
  8266. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8267. * @param key the unique key that identifies the data
  8268. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8269. * @return the associated data, can be null if the factory returned null.
  8270. */
  8271. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8272. return this._externalData.getOrAddWithFactory(key, factory);
  8273. };
  8274. /**
  8275. * Remove an externaly attached data from the Engine instance
  8276. * @param key the unique key that identifies the data
  8277. * @return true if the data was successfully removed, false if it doesn't exist
  8278. */
  8279. Engine.prototype.removeExternalData = function (key) {
  8280. return this._externalData.remove(key);
  8281. };
  8282. Engine.prototype.releaseInternalTexture = function (texture) {
  8283. if (!texture) {
  8284. return;
  8285. }
  8286. texture.references--;
  8287. // Final reference ?
  8288. if (texture.references === 0) {
  8289. var texturesCache = this.getLoadedTexturesCache();
  8290. var index = texturesCache.indexOf(texture);
  8291. if (index > -1) {
  8292. texturesCache.splice(index, 1);
  8293. }
  8294. this._releaseTexture(texture);
  8295. }
  8296. };
  8297. // Dispose
  8298. Engine.prototype.dispose = function () {
  8299. this.hideLoadingUI();
  8300. this.stopRenderLoop();
  8301. // Release scenes
  8302. while (this.scenes.length) {
  8303. this.scenes[0].dispose();
  8304. }
  8305. // Release audio engine
  8306. Engine.audioEngine.dispose();
  8307. // Release effects
  8308. for (var name in this._compiledEffects) {
  8309. this._gl.deleteProgram(this._compiledEffects[name]._program);
  8310. }
  8311. // Unbind
  8312. if (this._vertexAttribArraysEnabled) {
  8313. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  8314. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArraysEnabled[i]) {
  8315. continue;
  8316. }
  8317. this._gl.disableVertexAttribArray(i);
  8318. }
  8319. }
  8320. this._gl = null;
  8321. // Events
  8322. window.removeEventListener("blur", this._onBlur);
  8323. window.removeEventListener("focus", this._onFocus);
  8324. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  8325. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  8326. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  8327. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  8328. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  8329. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  8330. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  8331. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  8332. };
  8333. // Loading screen
  8334. Engine.prototype.displayLoadingUI = function () {
  8335. this._loadingScreen.displayLoadingUI();
  8336. };
  8337. Engine.prototype.hideLoadingUI = function () {
  8338. this._loadingScreen.hideLoadingUI();
  8339. };
  8340. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8341. get: function () {
  8342. return this._loadingScreen;
  8343. },
  8344. set: function (loadingScreen) {
  8345. this._loadingScreen = loadingScreen;
  8346. },
  8347. enumerable: true,
  8348. configurable: true
  8349. });
  8350. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8351. set: function (text) {
  8352. this._loadingScreen.loadingUIText = text;
  8353. },
  8354. enumerable: true,
  8355. configurable: true
  8356. });
  8357. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  8358. set: function (color) {
  8359. this._loadingScreen.loadingUIBackgroundColor = color;
  8360. },
  8361. enumerable: true,
  8362. configurable: true
  8363. });
  8364. Engine.prototype.attachContextLostEvent = function (callback) {
  8365. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  8366. };
  8367. Engine.prototype.attachContextRestoredEvent = function (callback) {
  8368. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  8369. };
  8370. // FPS
  8371. Engine.prototype.getFps = function () {
  8372. return this.fps;
  8373. };
  8374. Engine.prototype.getDeltaTime = function () {
  8375. return this.deltaTime;
  8376. };
  8377. Engine.prototype._measureFps = function () {
  8378. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8379. var length = this.previousFramesDuration.length;
  8380. if (length >= 2) {
  8381. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8382. }
  8383. if (length >= this.fpsRange) {
  8384. if (length > this.fpsRange) {
  8385. this.previousFramesDuration.splice(0, 1);
  8386. length = this.previousFramesDuration.length;
  8387. }
  8388. var sum = 0;
  8389. for (var id = 0; id < length - 1; id++) {
  8390. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8391. }
  8392. this.fps = 1000.0 / (sum / (length - 1));
  8393. }
  8394. };
  8395. Engine.prototype._canRenderToFloatTexture = function () {
  8396. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  8397. };
  8398. Engine.prototype._canRenderToHalfFloatTexture = function () {
  8399. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  8400. };
  8401. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  8402. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  8403. var tempcanvas = document.createElement("canvas");
  8404. tempcanvas.height = 16;
  8405. tempcanvas.width = 16;
  8406. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  8407. // extension.
  8408. var ext = gl.getExtension(extension);
  8409. if (!ext) {
  8410. return false;
  8411. }
  8412. // setup GLSL program
  8413. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  8414. 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 }";
  8415. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  8416. gl.useProgram(program);
  8417. // look up where the vertex data needs to go.
  8418. var positionLocation = gl.getAttribLocation(program, "a_position");
  8419. var colorLoc = gl.getUniformLocation(program, "u_color");
  8420. // provide texture coordinates for the rectangle.
  8421. var positionBuffer = gl.createBuffer();
  8422. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  8423. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  8424. -1.0, -1.0,
  8425. 1.0, -1.0,
  8426. -1.0, 1.0,
  8427. -1.0, 1.0,
  8428. 1.0, -1.0,
  8429. 1.0, 1.0]), gl.STATIC_DRAW);
  8430. gl.enableVertexAttribArray(positionLocation);
  8431. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  8432. var whiteTex = gl.createTexture();
  8433. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8434. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  8435. var tex = gl.createTexture();
  8436. gl.bindTexture(gl.TEXTURE_2D, tex);
  8437. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  8438. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8439. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8440. var fb = gl.createFramebuffer();
  8441. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  8442. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  8443. var cleanup = function () {
  8444. gl.deleteProgram(program);
  8445. gl.disableVertexAttribArray(positionLocation);
  8446. gl.deleteBuffer(positionBuffer);
  8447. gl.deleteFramebuffer(fb);
  8448. gl.deleteTexture(whiteTex);
  8449. gl.deleteTexture(tex);
  8450. };
  8451. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  8452. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  8453. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  8454. cleanup();
  8455. return false;
  8456. }
  8457. // Draw the rectangle.
  8458. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8459. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  8460. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8461. gl.bindTexture(gl.TEXTURE_2D, tex);
  8462. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  8463. gl.clearColor(1, 0, 0, 1);
  8464. gl.clear(gl.COLOR_BUFFER_BIT);
  8465. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  8466. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8467. var pixel = new Uint8Array(4);
  8468. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  8469. if (pixel[0] !== 0 ||
  8470. pixel[1] < 248 ||
  8471. pixel[2] < 248 ||
  8472. pixel[3] < 254) {
  8473. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  8474. cleanup();
  8475. return false;
  8476. }
  8477. // Succesfully rendered to "format" texture.
  8478. cleanup();
  8479. return true;
  8480. };
  8481. // Statics
  8482. Engine.isSupported = function () {
  8483. try {
  8484. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  8485. if (navigator.isCocoonJS) {
  8486. return true;
  8487. }
  8488. var tempcanvas = document.createElement("canvas");
  8489. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  8490. return gl != null && !!window.WebGLRenderingContext;
  8491. }
  8492. catch (e) {
  8493. return false;
  8494. }
  8495. };
  8496. // Const statics
  8497. Engine._ALPHA_DISABLE = 0;
  8498. Engine._ALPHA_ADD = 1;
  8499. Engine._ALPHA_COMBINE = 2;
  8500. Engine._ALPHA_SUBTRACT = 3;
  8501. Engine._ALPHA_MULTIPLY = 4;
  8502. Engine._ALPHA_MAXIMIZED = 5;
  8503. Engine._ALPHA_ONEONE = 6;
  8504. Engine._DELAYLOADSTATE_NONE = 0;
  8505. Engine._DELAYLOADSTATE_LOADED = 1;
  8506. Engine._DELAYLOADSTATE_LOADING = 2;
  8507. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  8508. Engine._TEXTUREFORMAT_ALPHA = 0;
  8509. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  8510. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  8511. Engine._TEXTUREFORMAT_RGB = 4;
  8512. Engine._TEXTUREFORMAT_RGBA = 5;
  8513. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  8514. Engine._TEXTURETYPE_FLOAT = 1;
  8515. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  8516. // Updatable statics so stick with vars here
  8517. Engine.CollisionsEpsilon = 0.001;
  8518. Engine.CodeRepository = "src/";
  8519. Engine.ShadersRepository = "src/Shaders/";
  8520. return Engine;
  8521. })();
  8522. BABYLON.Engine = Engine;
  8523. })(BABYLON || (BABYLON = {}));
  8524. var BABYLON;
  8525. (function (BABYLON) {
  8526. /**
  8527. * Node is the basic class for all scene objects (Mesh, Light Camera).
  8528. */
  8529. var Node = (function () {
  8530. /**
  8531. * @constructor
  8532. * @param {string} name - the name and id to be given to this node
  8533. * @param {BABYLON.Scene} the scene this node will be added to
  8534. */
  8535. function Node(name, scene) {
  8536. this.state = "";
  8537. this.animations = new Array();
  8538. this._ranges = {};
  8539. this._childrenFlag = -1;
  8540. this._isEnabled = true;
  8541. this._isReady = true;
  8542. this._currentRenderId = -1;
  8543. this._parentRenderId = -1;
  8544. this.name = name;
  8545. this.id = name;
  8546. this._scene = scene;
  8547. this._initCache();
  8548. }
  8549. Object.defineProperty(Node.prototype, "parent", {
  8550. get: function () {
  8551. return this._parentNode;
  8552. },
  8553. set: function (parent) {
  8554. if (this._parentNode === parent) {
  8555. return;
  8556. }
  8557. if (this._parentNode) {
  8558. var index = this._parentNode._children.indexOf(this);
  8559. if (index !== -1) {
  8560. this._parentNode._children.splice(index, 1);
  8561. }
  8562. }
  8563. this._parentNode = parent;
  8564. if (this._parentNode) {
  8565. if (!this._parentNode._children) {
  8566. this._parentNode._children = new Array();
  8567. }
  8568. this._parentNode._children.push(this);
  8569. }
  8570. },
  8571. enumerable: true,
  8572. configurable: true
  8573. });
  8574. Node.prototype.getScene = function () {
  8575. return this._scene;
  8576. };
  8577. Node.prototype.getEngine = function () {
  8578. return this._scene.getEngine();
  8579. };
  8580. // override it in derived class
  8581. Node.prototype.getWorldMatrix = function () {
  8582. return BABYLON.Matrix.Identity();
  8583. };
  8584. // override it in derived class if you add new variables to the cache
  8585. // and call the parent class method
  8586. Node.prototype._initCache = function () {
  8587. this._cache = {};
  8588. this._cache.parent = undefined;
  8589. };
  8590. Node.prototype.updateCache = function (force) {
  8591. if (!force && this.isSynchronized())
  8592. return;
  8593. this._cache.parent = this.parent;
  8594. this._updateCache();
  8595. };
  8596. // override it in derived class if you add new variables to the cache
  8597. // and call the parent class method if !ignoreParentClass
  8598. Node.prototype._updateCache = function (ignoreParentClass) {
  8599. };
  8600. // override it in derived class if you add new variables to the cache
  8601. Node.prototype._isSynchronized = function () {
  8602. return true;
  8603. };
  8604. Node.prototype._markSyncedWithParent = function () {
  8605. this._parentRenderId = this.parent._currentRenderId;
  8606. };
  8607. Node.prototype.isSynchronizedWithParent = function () {
  8608. if (!this.parent) {
  8609. return true;
  8610. }
  8611. if (this._parentRenderId !== this.parent._currentRenderId) {
  8612. return false;
  8613. }
  8614. return this.parent.isSynchronized();
  8615. };
  8616. Node.prototype.isSynchronized = function (updateCache) {
  8617. var check = this.hasNewParent();
  8618. check = check || !this.isSynchronizedWithParent();
  8619. check = check || !this._isSynchronized();
  8620. if (updateCache)
  8621. this.updateCache(true);
  8622. return !check;
  8623. };
  8624. Node.prototype.hasNewParent = function (update) {
  8625. if (this._cache.parent === this.parent)
  8626. return false;
  8627. if (update)
  8628. this._cache.parent = this.parent;
  8629. return true;
  8630. };
  8631. /**
  8632. * Is this node ready to be used/rendered
  8633. * @return {boolean} is it ready
  8634. */
  8635. Node.prototype.isReady = function () {
  8636. return this._isReady;
  8637. };
  8638. /**
  8639. * Is this node enabled.
  8640. * If the node has a parent and is enabled, the parent will be inspected as well.
  8641. * @return {boolean} whether this node (and its parent) is enabled.
  8642. * @see setEnabled
  8643. */
  8644. Node.prototype.isEnabled = function () {
  8645. if (!this._isEnabled) {
  8646. return false;
  8647. }
  8648. if (this.parent) {
  8649. return this.parent.isEnabled();
  8650. }
  8651. return true;
  8652. };
  8653. /**
  8654. * Set the enabled state of this node.
  8655. * @param {boolean} value - the new enabled state
  8656. * @see isEnabled
  8657. */
  8658. Node.prototype.setEnabled = function (value) {
  8659. this._isEnabled = value;
  8660. };
  8661. /**
  8662. * Is this node a descendant of the given node.
  8663. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  8664. * @param {BABYLON.Node} ancestor - The parent node to inspect
  8665. * @see parent
  8666. */
  8667. Node.prototype.isDescendantOf = function (ancestor) {
  8668. if (this.parent) {
  8669. if (this.parent === ancestor) {
  8670. return true;
  8671. }
  8672. return this.parent.isDescendantOf(ancestor);
  8673. }
  8674. return false;
  8675. };
  8676. /**
  8677. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  8678. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  8679. * @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.
  8680. * @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.
  8681. */
  8682. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  8683. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  8684. if (!this._children) {
  8685. return;
  8686. }
  8687. for (var index = 0; index < this._children.length; index++) {
  8688. var item = this._children[index];
  8689. if (!predicate || predicate(item)) {
  8690. results.push(item);
  8691. }
  8692. if (!directDescendantsOnly) {
  8693. item._getDescendants(results, false, predicate);
  8694. }
  8695. }
  8696. };
  8697. /**
  8698. * Will return all nodes that have this node as ascendant.
  8699. * @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.
  8700. * @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.
  8701. * @return {BABYLON.Node[]} all children nodes of all types.
  8702. */
  8703. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  8704. var results = [];
  8705. this._getDescendants(results, directDescendantsOnly, predicate);
  8706. return results;
  8707. };
  8708. /**
  8709. * @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.
  8710. * @Deprecated, legacy support.
  8711. * use getDecendants instead.
  8712. */
  8713. Node.prototype.getChildren = function (predicate) {
  8714. return this.getDescendants(true, predicate);
  8715. };
  8716. /**
  8717. * Get all child-meshes of this node.
  8718. */
  8719. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  8720. var results = [];
  8721. this._getDescendants(results, directDecendantsOnly, function (node) {
  8722. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  8723. });
  8724. return results;
  8725. };
  8726. Node.prototype._setReady = function (state) {
  8727. if (state === this._isReady) {
  8728. return;
  8729. }
  8730. if (!state) {
  8731. this._isReady = false;
  8732. return;
  8733. }
  8734. this._isReady = true;
  8735. if (this.onReady) {
  8736. this.onReady(this);
  8737. }
  8738. };
  8739. Node.prototype.getAnimationByName = function (name) {
  8740. for (var i = 0; i < this.animations.length; i++) {
  8741. var animation = this.animations[i];
  8742. if (animation.name === name) {
  8743. return animation;
  8744. }
  8745. }
  8746. return null;
  8747. };
  8748. Node.prototype.createAnimationRange = function (name, from, to) {
  8749. // check name not already in use
  8750. if (!this._ranges[name]) {
  8751. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  8752. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8753. if (this.animations[i]) {
  8754. this.animations[i].createRange(name, from, to);
  8755. }
  8756. }
  8757. }
  8758. };
  8759. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  8760. if (deleteFrames === void 0) { deleteFrames = true; }
  8761. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8762. if (this.animations[i]) {
  8763. this.animations[i].deleteRange(name, deleteFrames);
  8764. }
  8765. }
  8766. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  8767. };
  8768. Node.prototype.getAnimationRange = function (name) {
  8769. return this._ranges[name];
  8770. };
  8771. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  8772. var range = this.getAnimationRange(name);
  8773. if (!range) {
  8774. return null;
  8775. }
  8776. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  8777. };
  8778. Node.prototype.serializeAnimationRanges = function () {
  8779. var serializationRanges = [];
  8780. for (var name in this._ranges) {
  8781. var range = {};
  8782. range.name = name;
  8783. range.from = this._ranges[name].from;
  8784. range.to = this._ranges[name].to;
  8785. serializationRanges.push(range);
  8786. }
  8787. return serializationRanges;
  8788. };
  8789. Node.prototype.dispose = function () {
  8790. this.parent = null;
  8791. };
  8792. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  8793. if (parsedNode.ranges) {
  8794. for (var index = 0; index < parsedNode.ranges.length; index++) {
  8795. var data = parsedNode.ranges[index];
  8796. node.createAnimationRange(data.name, data.from, data.to);
  8797. }
  8798. }
  8799. };
  8800. __decorate([
  8801. BABYLON.serialize()
  8802. ], Node.prototype, "name", void 0);
  8803. __decorate([
  8804. BABYLON.serialize()
  8805. ], Node.prototype, "id", void 0);
  8806. __decorate([
  8807. BABYLON.serialize()
  8808. ], Node.prototype, "uniqueId", void 0);
  8809. __decorate([
  8810. BABYLON.serialize()
  8811. ], Node.prototype, "state", void 0);
  8812. return Node;
  8813. })();
  8814. BABYLON.Node = Node;
  8815. })(BABYLON || (BABYLON = {}));
  8816. var BABYLON;
  8817. (function (BABYLON) {
  8818. var FilesInput = (function () {
  8819. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  8820. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  8821. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  8822. this._engine = p_engine;
  8823. this._canvas = p_canvas;
  8824. this._currentScene = p_scene;
  8825. this._sceneLoadedCallback = p_sceneLoadedCallback;
  8826. this._progressCallback = p_progressCallback;
  8827. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  8828. this._textureLoadingCallback = p_textureLoadingCallback;
  8829. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  8830. }
  8831. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  8832. var _this = this;
  8833. if (p_elementToMonitor) {
  8834. this._elementToMonitor = p_elementToMonitor;
  8835. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  8836. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  8837. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  8838. }
  8839. };
  8840. FilesInput.prototype.renderFunction = function () {
  8841. if (this._additionnalRenderLoopLogicCallback) {
  8842. this._additionnalRenderLoopLogicCallback();
  8843. }
  8844. if (this._currentScene) {
  8845. if (this._textureLoadingCallback) {
  8846. var remaining = this._currentScene.getWaitingItemsCount();
  8847. if (remaining > 0) {
  8848. this._textureLoadingCallback(remaining);
  8849. }
  8850. }
  8851. this._currentScene.render();
  8852. }
  8853. };
  8854. FilesInput.prototype.drag = function (e) {
  8855. e.stopPropagation();
  8856. e.preventDefault();
  8857. };
  8858. FilesInput.prototype.drop = function (eventDrop) {
  8859. eventDrop.stopPropagation();
  8860. eventDrop.preventDefault();
  8861. this.loadFiles(eventDrop);
  8862. };
  8863. FilesInput.prototype.loadFiles = function (event) {
  8864. if (this._startingProcessingFilesCallback)
  8865. this._startingProcessingFilesCallback();
  8866. // Handling data transfer via drag'n'drop
  8867. if (event && event.dataTransfer && event.dataTransfer.files) {
  8868. this._filesToLoad = event.dataTransfer.files;
  8869. }
  8870. // Handling files from input files
  8871. if (event && event.target && event.target.files) {
  8872. this._filesToLoad = event.target.files;
  8873. }
  8874. if (this._filesToLoad && this._filesToLoad.length > 0) {
  8875. for (var i = 0; i < this._filesToLoad.length; i++) {
  8876. switch (this._filesToLoad[i].type) {
  8877. case "image/jpeg":
  8878. case "image/png":
  8879. case "image/bmp":
  8880. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8881. break;
  8882. case "image/targa":
  8883. case "image/vnd.ms-dds":
  8884. case "audio/wav":
  8885. case "audio/x-wav":
  8886. case "audio/mp3":
  8887. case "audio/mpeg":
  8888. case "audio/mpeg3":
  8889. case "audio/x-mpeg-3":
  8890. case "audio/ogg":
  8891. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8892. break;
  8893. default:
  8894. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  8895. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8896. }
  8897. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  8898. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  8899. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  8900. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  8901. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  8902. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  8903. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  8904. this._sceneFileToLoad = this._filesToLoad[i];
  8905. }
  8906. break;
  8907. }
  8908. }
  8909. this.reload();
  8910. }
  8911. };
  8912. FilesInput.prototype.reload = function () {
  8913. var _this = this;
  8914. var that = this;
  8915. // If a ".babylon" file has been provided
  8916. if (this._sceneFileToLoad) {
  8917. if (this._currentScene) {
  8918. if (BABYLON.Tools.errorsCount > 0) {
  8919. BABYLON.Tools.ClearLogCache();
  8920. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  8921. }
  8922. this._engine.stopRenderLoop();
  8923. this._currentScene.dispose();
  8924. }
  8925. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  8926. that._currentScene = newScene;
  8927. // Wait for textures and shaders to be ready
  8928. that._currentScene.executeWhenReady(function () {
  8929. // Attach camera to canvas inputs
  8930. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  8931. that._currentScene.createDefaultCameraOrLight();
  8932. }
  8933. that._currentScene.activeCamera.attachControl(that._canvas);
  8934. if (that._sceneLoadedCallback) {
  8935. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  8936. }
  8937. that._engine.runRenderLoop(function () { that.renderFunction(); });
  8938. });
  8939. }, function (progress) {
  8940. if (_this._progressCallback) {
  8941. _this._progressCallback(progress);
  8942. }
  8943. });
  8944. }
  8945. else {
  8946. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  8947. }
  8948. };
  8949. FilesInput.FilesTextures = new Array();
  8950. FilesInput.FilesToLoad = new Array();
  8951. return FilesInput;
  8952. })();
  8953. BABYLON.FilesInput = FilesInput;
  8954. })(BABYLON || (BABYLON = {}));
  8955. var BABYLON;
  8956. (function (BABYLON) {
  8957. var IntersectionInfo = (function () {
  8958. function IntersectionInfo(bu, bv, distance) {
  8959. this.bu = bu;
  8960. this.bv = bv;
  8961. this.distance = distance;
  8962. this.faceId = 0;
  8963. this.subMeshId = 0;
  8964. }
  8965. return IntersectionInfo;
  8966. })();
  8967. BABYLON.IntersectionInfo = IntersectionInfo;
  8968. var PickingInfo = (function () {
  8969. function PickingInfo() {
  8970. this.hit = false;
  8971. this.distance = 0;
  8972. this.pickedPoint = null;
  8973. this.pickedMesh = null;
  8974. this.bu = 0;
  8975. this.bv = 0;
  8976. this.faceId = -1;
  8977. this.subMeshId = 0;
  8978. this.pickedSprite = null;
  8979. }
  8980. // Methods
  8981. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  8982. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  8983. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  8984. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8985. return null;
  8986. }
  8987. var indices = this.pickedMesh.getIndices();
  8988. var result;
  8989. if (useVerticesNormals) {
  8990. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8991. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  8992. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  8993. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  8994. normal0 = normal0.scale(this.bu);
  8995. normal1 = normal1.scale(this.bv);
  8996. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  8997. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  8998. }
  8999. else {
  9000. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9001. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9002. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9003. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9004. var p1p2 = vertex1.subtract(vertex2);
  9005. var p3p2 = vertex3.subtract(vertex2);
  9006. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9007. }
  9008. if (useWorldCoordinates) {
  9009. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9010. }
  9011. return BABYLON.Vector3.Normalize(result);
  9012. };
  9013. PickingInfo.prototype.getTextureCoordinates = function () {
  9014. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9015. return null;
  9016. }
  9017. var indices = this.pickedMesh.getIndices();
  9018. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9019. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9020. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9021. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9022. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9023. uv1 = uv1.scale(this.bu);
  9024. uv2 = uv2.scale(this.bv);
  9025. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9026. };
  9027. return PickingInfo;
  9028. })();
  9029. BABYLON.PickingInfo = PickingInfo;
  9030. })(BABYLON || (BABYLON = {}));
  9031. var BABYLON;
  9032. (function (BABYLON) {
  9033. var BoundingSphere = (function () {
  9034. function BoundingSphere(minimum, maximum) {
  9035. this.minimum = minimum;
  9036. this.maximum = maximum;
  9037. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9038. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9039. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9040. this.radius = distance * 0.5;
  9041. this.centerWorld = BABYLON.Vector3.Zero();
  9042. this._update(BABYLON.Matrix.Identity());
  9043. }
  9044. // Methods
  9045. BoundingSphere.prototype._update = function (world) {
  9046. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9047. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9048. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9049. };
  9050. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9051. for (var i = 0; i < 6; i++) {
  9052. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9053. return false;
  9054. }
  9055. return true;
  9056. };
  9057. BoundingSphere.prototype.intersectsPoint = function (point) {
  9058. var x = this.centerWorld.x - point.x;
  9059. var y = this.centerWorld.y - point.y;
  9060. var z = this.centerWorld.z - point.z;
  9061. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9062. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9063. return false;
  9064. return true;
  9065. };
  9066. // Statics
  9067. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9068. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9069. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9070. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9071. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9072. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9073. return false;
  9074. return true;
  9075. };
  9076. return BoundingSphere;
  9077. })();
  9078. BABYLON.BoundingSphere = BoundingSphere;
  9079. })(BABYLON || (BABYLON = {}));
  9080. var BABYLON;
  9081. (function (BABYLON) {
  9082. var BoundingBox = (function () {
  9083. function BoundingBox(minimum, maximum) {
  9084. this.minimum = minimum;
  9085. this.maximum = maximum;
  9086. this.vectors = new Array();
  9087. this.vectorsWorld = new Array();
  9088. // Bounding vectors
  9089. this.vectors.push(this.minimum.clone());
  9090. this.vectors.push(this.maximum.clone());
  9091. this.vectors.push(this.minimum.clone());
  9092. this.vectors[2].x = this.maximum.x;
  9093. this.vectors.push(this.minimum.clone());
  9094. this.vectors[3].y = this.maximum.y;
  9095. this.vectors.push(this.minimum.clone());
  9096. this.vectors[4].z = this.maximum.z;
  9097. this.vectors.push(this.maximum.clone());
  9098. this.vectors[5].z = this.minimum.z;
  9099. this.vectors.push(this.maximum.clone());
  9100. this.vectors[6].x = this.minimum.x;
  9101. this.vectors.push(this.maximum.clone());
  9102. this.vectors[7].y = this.minimum.y;
  9103. // OBB
  9104. this.center = this.maximum.add(this.minimum).scale(0.5);
  9105. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9106. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9107. // World
  9108. for (var index = 0; index < this.vectors.length; index++) {
  9109. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9110. }
  9111. this.minimumWorld = BABYLON.Vector3.Zero();
  9112. this.maximumWorld = BABYLON.Vector3.Zero();
  9113. this._update(BABYLON.Matrix.Identity());
  9114. }
  9115. // Methods
  9116. BoundingBox.prototype.getWorldMatrix = function () {
  9117. return this._worldMatrix;
  9118. };
  9119. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9120. this._worldMatrix.copyFrom(matrix);
  9121. return this;
  9122. };
  9123. BoundingBox.prototype._update = function (world) {
  9124. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9125. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9126. for (var index = 0; index < this.vectors.length; index++) {
  9127. var v = this.vectorsWorld[index];
  9128. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9129. if (v.x < this.minimumWorld.x)
  9130. this.minimumWorld.x = v.x;
  9131. if (v.y < this.minimumWorld.y)
  9132. this.minimumWorld.y = v.y;
  9133. if (v.z < this.minimumWorld.z)
  9134. this.minimumWorld.z = v.z;
  9135. if (v.x > this.maximumWorld.x)
  9136. this.maximumWorld.x = v.x;
  9137. if (v.y > this.maximumWorld.y)
  9138. this.maximumWorld.y = v.y;
  9139. if (v.z > this.maximumWorld.z)
  9140. this.maximumWorld.z = v.z;
  9141. }
  9142. // OBB
  9143. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9144. this.center.scaleInPlace(0.5);
  9145. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9146. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9147. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9148. this._worldMatrix = world;
  9149. };
  9150. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9151. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9152. };
  9153. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9154. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9155. };
  9156. BoundingBox.prototype.intersectsPoint = function (point) {
  9157. var delta = -BABYLON.Epsilon;
  9158. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9159. return false;
  9160. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9161. return false;
  9162. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9163. return false;
  9164. return true;
  9165. };
  9166. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9167. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9168. };
  9169. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9170. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9171. return false;
  9172. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9173. return false;
  9174. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9175. return false;
  9176. return true;
  9177. };
  9178. // Statics
  9179. BoundingBox.Intersects = function (box0, box1) {
  9180. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9181. return false;
  9182. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9183. return false;
  9184. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9185. return false;
  9186. return true;
  9187. };
  9188. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9189. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9190. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9191. return (num <= (sphereRadius * sphereRadius));
  9192. };
  9193. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9194. for (var p = 0; p < 6; p++) {
  9195. for (var i = 0; i < 8; i++) {
  9196. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9197. return false;
  9198. }
  9199. }
  9200. }
  9201. return true;
  9202. };
  9203. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9204. for (var p = 0; p < 6; p++) {
  9205. var inCount = 8;
  9206. for (var i = 0; i < 8; i++) {
  9207. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9208. --inCount;
  9209. }
  9210. else {
  9211. break;
  9212. }
  9213. }
  9214. if (inCount === 0)
  9215. return false;
  9216. }
  9217. return true;
  9218. };
  9219. return BoundingBox;
  9220. })();
  9221. BABYLON.BoundingBox = BoundingBox;
  9222. })(BABYLON || (BABYLON = {}));
  9223. var BABYLON;
  9224. (function (BABYLON) {
  9225. var computeBoxExtents = function (axis, box) {
  9226. var p = BABYLON.Vector3.Dot(box.center, axis);
  9227. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9228. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9229. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9230. var r = r0 + r1 + r2;
  9231. return {
  9232. min: p - r,
  9233. max: p + r
  9234. };
  9235. };
  9236. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  9237. var axisOverlap = function (axis, box0, box1) {
  9238. var result0 = computeBoxExtents(axis, box0);
  9239. var result1 = computeBoxExtents(axis, box1);
  9240. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  9241. };
  9242. var BoundingInfo = (function () {
  9243. function BoundingInfo(minimum, maximum) {
  9244. this.minimum = minimum;
  9245. this.maximum = maximum;
  9246. this._isLocked = false;
  9247. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  9248. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  9249. }
  9250. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  9251. get: function () {
  9252. return this._isLocked;
  9253. },
  9254. set: function (value) {
  9255. this._isLocked = value;
  9256. },
  9257. enumerable: true,
  9258. configurable: true
  9259. });
  9260. // Methods
  9261. BoundingInfo.prototype.update = function (world) {
  9262. if (this._isLocked) {
  9263. return;
  9264. }
  9265. this.boundingBox._update(world);
  9266. this.boundingSphere._update(world);
  9267. };
  9268. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  9269. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  9270. return false;
  9271. return this.boundingBox.isInFrustum(frustumPlanes);
  9272. };
  9273. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9274. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  9275. };
  9276. BoundingInfo.prototype._checkCollision = function (collider) {
  9277. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  9278. };
  9279. BoundingInfo.prototype.intersectsPoint = function (point) {
  9280. if (!this.boundingSphere.centerWorld) {
  9281. return false;
  9282. }
  9283. if (!this.boundingSphere.intersectsPoint(point)) {
  9284. return false;
  9285. }
  9286. if (!this.boundingBox.intersectsPoint(point)) {
  9287. return false;
  9288. }
  9289. return true;
  9290. };
  9291. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  9292. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  9293. return false;
  9294. }
  9295. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  9296. return false;
  9297. }
  9298. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  9299. return false;
  9300. }
  9301. if (!precise) {
  9302. return true;
  9303. }
  9304. var box0 = this.boundingBox;
  9305. var box1 = boundingInfo.boundingBox;
  9306. if (!axisOverlap(box0.directions[0], box0, box1))
  9307. return false;
  9308. if (!axisOverlap(box0.directions[1], box0, box1))
  9309. return false;
  9310. if (!axisOverlap(box0.directions[2], box0, box1))
  9311. return false;
  9312. if (!axisOverlap(box1.directions[0], box0, box1))
  9313. return false;
  9314. if (!axisOverlap(box1.directions[1], box0, box1))
  9315. return false;
  9316. if (!axisOverlap(box1.directions[2], box0, box1))
  9317. return false;
  9318. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  9319. return false;
  9320. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  9321. return false;
  9322. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  9323. return false;
  9324. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  9325. return false;
  9326. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  9327. return false;
  9328. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  9329. return false;
  9330. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  9331. return false;
  9332. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  9333. return false;
  9334. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  9335. return false;
  9336. return true;
  9337. };
  9338. return BoundingInfo;
  9339. })();
  9340. BABYLON.BoundingInfo = BoundingInfo;
  9341. })(BABYLON || (BABYLON = {}));
  9342. var BABYLON;
  9343. (function (BABYLON) {
  9344. var Ray = (function () {
  9345. function Ray(origin, direction, length) {
  9346. if (length === void 0) { length = Number.MAX_VALUE; }
  9347. this.origin = origin;
  9348. this.direction = direction;
  9349. this.length = length;
  9350. }
  9351. // Methods
  9352. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  9353. var d = 0.0;
  9354. var maxValue = Number.MAX_VALUE;
  9355. var inv;
  9356. var min;
  9357. var max;
  9358. var temp;
  9359. if (Math.abs(this.direction.x) < 0.0000001) {
  9360. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  9361. return false;
  9362. }
  9363. }
  9364. else {
  9365. inv = 1.0 / this.direction.x;
  9366. min = (minimum.x - this.origin.x) * inv;
  9367. max = (maximum.x - this.origin.x) * inv;
  9368. if (max === -Infinity) {
  9369. max = Infinity;
  9370. }
  9371. if (min > max) {
  9372. temp = min;
  9373. min = max;
  9374. max = temp;
  9375. }
  9376. d = Math.max(min, d);
  9377. maxValue = Math.min(max, maxValue);
  9378. if (d > maxValue) {
  9379. return false;
  9380. }
  9381. }
  9382. if (Math.abs(this.direction.y) < 0.0000001) {
  9383. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  9384. return false;
  9385. }
  9386. }
  9387. else {
  9388. inv = 1.0 / this.direction.y;
  9389. min = (minimum.y - this.origin.y) * inv;
  9390. max = (maximum.y - this.origin.y) * inv;
  9391. if (max === -Infinity) {
  9392. max = Infinity;
  9393. }
  9394. if (min > max) {
  9395. temp = min;
  9396. min = max;
  9397. max = temp;
  9398. }
  9399. d = Math.max(min, d);
  9400. maxValue = Math.min(max, maxValue);
  9401. if (d > maxValue) {
  9402. return false;
  9403. }
  9404. }
  9405. if (Math.abs(this.direction.z) < 0.0000001) {
  9406. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  9407. return false;
  9408. }
  9409. }
  9410. else {
  9411. inv = 1.0 / this.direction.z;
  9412. min = (minimum.z - this.origin.z) * inv;
  9413. max = (maximum.z - this.origin.z) * inv;
  9414. if (max === -Infinity) {
  9415. max = Infinity;
  9416. }
  9417. if (min > max) {
  9418. temp = min;
  9419. min = max;
  9420. max = temp;
  9421. }
  9422. d = Math.max(min, d);
  9423. maxValue = Math.min(max, maxValue);
  9424. if (d > maxValue) {
  9425. return false;
  9426. }
  9427. }
  9428. return true;
  9429. };
  9430. Ray.prototype.intersectsBox = function (box) {
  9431. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  9432. };
  9433. Ray.prototype.intersectsSphere = function (sphere) {
  9434. var x = sphere.center.x - this.origin.x;
  9435. var y = sphere.center.y - this.origin.y;
  9436. var z = sphere.center.z - this.origin.z;
  9437. var pyth = (x * x) + (y * y) + (z * z);
  9438. var rr = sphere.radius * sphere.radius;
  9439. if (pyth <= rr) {
  9440. return true;
  9441. }
  9442. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  9443. if (dot < 0.0) {
  9444. return false;
  9445. }
  9446. var temp = pyth - (dot * dot);
  9447. return temp <= rr;
  9448. };
  9449. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  9450. if (!this._edge1) {
  9451. this._edge1 = BABYLON.Vector3.Zero();
  9452. this._edge2 = BABYLON.Vector3.Zero();
  9453. this._pvec = BABYLON.Vector3.Zero();
  9454. this._tvec = BABYLON.Vector3.Zero();
  9455. this._qvec = BABYLON.Vector3.Zero();
  9456. }
  9457. vertex1.subtractToRef(vertex0, this._edge1);
  9458. vertex2.subtractToRef(vertex0, this._edge2);
  9459. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  9460. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  9461. if (det === 0) {
  9462. return null;
  9463. }
  9464. var invdet = 1 / det;
  9465. this.origin.subtractToRef(vertex0, this._tvec);
  9466. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  9467. if (bu < 0 || bu > 1.0) {
  9468. return null;
  9469. }
  9470. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  9471. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  9472. if (bv < 0 || bu + bv > 1.0) {
  9473. return null;
  9474. }
  9475. //check if the distance is longer than the predefined length.
  9476. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  9477. if (distance > this.length) {
  9478. return null;
  9479. }
  9480. return new BABYLON.IntersectionInfo(bu, bv, distance);
  9481. };
  9482. Ray.prototype.intersectsPlane = function (plane) {
  9483. var distance;
  9484. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  9485. if (Math.abs(result1) < 9.99999997475243E-07) {
  9486. return null;
  9487. }
  9488. else {
  9489. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  9490. distance = (-plane.d - result2) / result1;
  9491. if (distance < 0.0) {
  9492. if (distance < -9.99999997475243E-07) {
  9493. return null;
  9494. }
  9495. else {
  9496. return 0;
  9497. }
  9498. }
  9499. return distance;
  9500. }
  9501. };
  9502. /**
  9503. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  9504. * @param sega the first point of the segment to test the intersection against
  9505. * @param segb the second point of the segment to test the intersection against
  9506. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  9507. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  9508. */
  9509. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  9510. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  9511. var u = segb.subtract(sega);
  9512. var v = rsegb.subtract(this.origin);
  9513. var w = sega.subtract(this.origin);
  9514. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  9515. var b = BABYLON.Vector3.Dot(u, v);
  9516. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  9517. var d = BABYLON.Vector3.Dot(u, w);
  9518. var e = BABYLON.Vector3.Dot(v, w);
  9519. var D = a * c - b * b; // always >= 0
  9520. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  9521. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  9522. // compute the line parameters of the two closest points
  9523. if (D < Ray.smallnum) {
  9524. sN = 0.0; // force using point P0 on segment S1
  9525. sD = 1.0; // to prevent possible division by 0.0 later
  9526. tN = e;
  9527. tD = c;
  9528. }
  9529. else {
  9530. sN = (b * e - c * d);
  9531. tN = (a * e - b * d);
  9532. if (sN < 0.0) {
  9533. sN = 0.0;
  9534. tN = e;
  9535. tD = c;
  9536. }
  9537. else if (sN > sD) {
  9538. sN = sD;
  9539. tN = e + b;
  9540. tD = c;
  9541. }
  9542. }
  9543. if (tN < 0.0) {
  9544. tN = 0.0;
  9545. // recompute sc for this edge
  9546. if (-d < 0.0) {
  9547. sN = 0.0;
  9548. }
  9549. else if (-d > a)
  9550. sN = sD;
  9551. else {
  9552. sN = -d;
  9553. sD = a;
  9554. }
  9555. }
  9556. else if (tN > tD) {
  9557. tN = tD;
  9558. // recompute sc for this edge
  9559. if ((-d + b) < 0.0) {
  9560. sN = 0;
  9561. }
  9562. else if ((-d + b) > a) {
  9563. sN = sD;
  9564. }
  9565. else {
  9566. sN = (-d + b);
  9567. sD = a;
  9568. }
  9569. }
  9570. // finally do the division to get sc and tc
  9571. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  9572. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  9573. // get the difference of the two closest points
  9574. var qtc = v.multiplyByFloats(tc, tc, tc);
  9575. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  9576. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  9577. if (isIntersected) {
  9578. return qtc.length();
  9579. }
  9580. return -1;
  9581. };
  9582. // Statics
  9583. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  9584. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  9585. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  9586. var direction = end.subtract(start);
  9587. direction.normalize();
  9588. return new Ray(start, direction);
  9589. };
  9590. /**
  9591. * 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
  9592. * transformed to the given world matrix.
  9593. * @param origin The origin point
  9594. * @param end The end point
  9595. * @param world a matrix to transform the ray to. Default is the identity matrix.
  9596. */
  9597. Ray.CreateNewFromTo = function (origin, end, world) {
  9598. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  9599. var direction = end.subtract(origin);
  9600. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  9601. direction.normalize();
  9602. return Ray.Transform(new Ray(origin, direction, length), world);
  9603. };
  9604. Ray.Transform = function (ray, matrix) {
  9605. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  9606. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  9607. newDirection.normalize();
  9608. return new Ray(newOrigin, newDirection, ray.length);
  9609. };
  9610. Ray.smallnum = 0.00000001;
  9611. Ray.rayl = 10e8;
  9612. return Ray;
  9613. })();
  9614. BABYLON.Ray = Ray;
  9615. })(BABYLON || (BABYLON = {}));
  9616. var BABYLON;
  9617. (function (BABYLON) {
  9618. var AbstractMesh = (function (_super) {
  9619. __extends(AbstractMesh, _super);
  9620. // Constructor
  9621. function AbstractMesh(name, scene) {
  9622. var _this = this;
  9623. _super.call(this, name, scene);
  9624. // Events
  9625. /**
  9626. * An event triggered when the mesh is disposed.
  9627. * @type {BABYLON.Observable}
  9628. */
  9629. this.onDisposeObservable = new BABYLON.Observable();
  9630. /**
  9631. * An event triggered when this mesh collides with another one
  9632. * @type {BABYLON.Observable}
  9633. */
  9634. this.onCollideObservable = new BABYLON.Observable();
  9635. /**
  9636. * An event triggered when the collision's position changes
  9637. * @type {BABYLON.Observable}
  9638. */
  9639. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  9640. /**
  9641. * An event triggered after the world matrix is updated
  9642. * @type {BABYLON.Observable}
  9643. */
  9644. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  9645. // Properties
  9646. this.definedFacingForward = true; // orientation for POV movement & rotation
  9647. this.position = new BABYLON.Vector3(0, 0, 0);
  9648. this._rotation = new BABYLON.Vector3(0, 0, 0);
  9649. this._scaling = new BABYLON.Vector3(1, 1, 1);
  9650. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9651. this.visibility = 1.0;
  9652. this.alphaIndex = Number.MAX_VALUE;
  9653. this.infiniteDistance = false;
  9654. this.isVisible = true;
  9655. this.isPickable = true;
  9656. this.showBoundingBox = false;
  9657. this.showSubMeshesBoundingBox = false;
  9658. this.isBlocker = false;
  9659. this.renderingGroupId = 0;
  9660. this.receiveShadows = false;
  9661. this.renderOutline = false;
  9662. this.outlineColor = BABYLON.Color3.Red();
  9663. this.outlineWidth = 0.02;
  9664. this.renderOverlay = false;
  9665. this.overlayColor = BABYLON.Color3.Red();
  9666. this.overlayAlpha = 0.5;
  9667. this.hasVertexAlpha = false;
  9668. this.useVertexColors = true;
  9669. this.applyFog = true;
  9670. this.computeBonesUsingShaders = true;
  9671. this.scalingDeterminant = 1;
  9672. this.numBoneInfluencers = 4;
  9673. this.useOctreeForRenderingSelection = true;
  9674. this.useOctreeForPicking = true;
  9675. this.useOctreeForCollisions = true;
  9676. this.layerMask = 0x0FFFFFFF;
  9677. this.alwaysSelectAsActiveMesh = false;
  9678. // Collisions
  9679. this._checkCollisions = false;
  9680. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9681. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9682. this._collider = new BABYLON.Collider();
  9683. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9684. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9685. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9686. // Edges
  9687. this.edgesWidth = 1;
  9688. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  9689. // Cache
  9690. this._localWorld = BABYLON.Matrix.Zero();
  9691. this._worldMatrix = BABYLON.Matrix.Zero();
  9692. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9693. this._absolutePosition = BABYLON.Vector3.Zero();
  9694. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9695. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9696. this._isDirty = false;
  9697. this._pivotMatrix = BABYLON.Matrix.Identity();
  9698. this._isDisposed = false;
  9699. this._renderId = 0;
  9700. this._intersectionsInProgress = new Array();
  9701. this._isWorldMatrixFrozen = false;
  9702. this._unIndexed = false;
  9703. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  9704. if (collidedMesh === void 0) { collidedMesh = null; }
  9705. //TODO move this to the collision coordinator!
  9706. if (_this.getScene().workerCollisions)
  9707. newPosition.multiplyInPlace(_this._collider.radius);
  9708. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  9709. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9710. _this.position.addInPlace(_this._diffPositionForCollisions);
  9711. }
  9712. if (collidedMesh) {
  9713. _this.onCollideObservable.notifyObservers(collidedMesh);
  9714. }
  9715. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  9716. };
  9717. scene.addMesh(this);
  9718. }
  9719. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9720. get: function () {
  9721. return AbstractMesh._BILLBOARDMODE_NONE;
  9722. },
  9723. enumerable: true,
  9724. configurable: true
  9725. });
  9726. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9727. get: function () {
  9728. return AbstractMesh._BILLBOARDMODE_X;
  9729. },
  9730. enumerable: true,
  9731. configurable: true
  9732. });
  9733. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9734. get: function () {
  9735. return AbstractMesh._BILLBOARDMODE_Y;
  9736. },
  9737. enumerable: true,
  9738. configurable: true
  9739. });
  9740. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9741. get: function () {
  9742. return AbstractMesh._BILLBOARDMODE_Z;
  9743. },
  9744. enumerable: true,
  9745. configurable: true
  9746. });
  9747. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9748. get: function () {
  9749. return AbstractMesh._BILLBOARDMODE_ALL;
  9750. },
  9751. enumerable: true,
  9752. configurable: true
  9753. });
  9754. Object.defineProperty(AbstractMesh.prototype, "onDispose", {
  9755. set: function (callback) {
  9756. if (this._onDisposeObserver) {
  9757. this.onDisposeObservable.remove(this._onDisposeObserver);
  9758. }
  9759. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9760. },
  9761. enumerable: true,
  9762. configurable: true
  9763. });
  9764. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  9765. set: function (callback) {
  9766. if (this._onCollideObserver) {
  9767. this.onCollideObservable.remove(this._onCollideObserver);
  9768. }
  9769. this._onCollideObserver = this.onCollideObservable.add(callback);
  9770. },
  9771. enumerable: true,
  9772. configurable: true
  9773. });
  9774. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  9775. set: function (callback) {
  9776. if (this._onCollisionPositionChangeObserver) {
  9777. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  9778. }
  9779. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  9780. },
  9781. enumerable: true,
  9782. configurable: true
  9783. });
  9784. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  9785. get: function () {
  9786. return this._skeleton;
  9787. },
  9788. set: function (value) {
  9789. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  9790. this._skeleton._unregisterMeshWithPoseMatrix(this);
  9791. }
  9792. if (value && value.needInitialSkinMatrix) {
  9793. value._registerMeshWithPoseMatrix(this);
  9794. }
  9795. this._skeleton = value;
  9796. if (!this._skeleton) {
  9797. this._bonesTransformMatrices = null;
  9798. }
  9799. },
  9800. enumerable: true,
  9801. configurable: true
  9802. });
  9803. /**
  9804. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9805. */
  9806. AbstractMesh.prototype.toString = function (fullDetails) {
  9807. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  9808. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  9809. if (this._skeleton) {
  9810. ret += ", skeleton: " + this._skeleton.name;
  9811. }
  9812. if (fullDetails) {
  9813. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  9814. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  9815. }
  9816. return ret;
  9817. };
  9818. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  9819. /**
  9820. * Getting the rotation object.
  9821. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  9822. */
  9823. get: function () {
  9824. return this._rotation;
  9825. },
  9826. set: function (newRotation) {
  9827. this._rotation = newRotation;
  9828. },
  9829. enumerable: true,
  9830. configurable: true
  9831. });
  9832. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  9833. get: function () {
  9834. return this._scaling;
  9835. },
  9836. set: function (newScaling) {
  9837. this._scaling = newScaling;
  9838. if (this.physicsImpostor) {
  9839. this.physicsImpostor.forceUpdate();
  9840. }
  9841. },
  9842. enumerable: true,
  9843. configurable: true
  9844. });
  9845. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  9846. get: function () {
  9847. return this._rotationQuaternion;
  9848. },
  9849. set: function (quaternion) {
  9850. this._rotationQuaternion = quaternion;
  9851. //reset the rotation vector.
  9852. if (quaternion && this.rotation.length()) {
  9853. this.rotation.copyFromFloats(0, 0, 0);
  9854. }
  9855. },
  9856. enumerable: true,
  9857. configurable: true
  9858. });
  9859. // Methods
  9860. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  9861. this._poseMatrix.copyFrom(matrix);
  9862. };
  9863. AbstractMesh.prototype.getPoseMatrix = function () {
  9864. return this._poseMatrix;
  9865. };
  9866. AbstractMesh.prototype.disableEdgesRendering = function () {
  9867. if (this._edgesRenderer !== undefined) {
  9868. this._edgesRenderer.dispose();
  9869. this._edgesRenderer = undefined;
  9870. }
  9871. };
  9872. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  9873. if (epsilon === void 0) { epsilon = 0.95; }
  9874. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  9875. this.disableEdgesRendering();
  9876. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  9877. };
  9878. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9879. get: function () {
  9880. return false;
  9881. },
  9882. enumerable: true,
  9883. configurable: true
  9884. });
  9885. AbstractMesh.prototype.getLOD = function (camera) {
  9886. return this;
  9887. };
  9888. AbstractMesh.prototype.getTotalVertices = function () {
  9889. return 0;
  9890. };
  9891. AbstractMesh.prototype.getIndices = function () {
  9892. return null;
  9893. };
  9894. AbstractMesh.prototype.getVerticesData = function (kind) {
  9895. return null;
  9896. };
  9897. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9898. return false;
  9899. };
  9900. AbstractMesh.prototype.getBoundingInfo = function () {
  9901. if (this._masterMesh) {
  9902. return this._masterMesh.getBoundingInfo();
  9903. }
  9904. if (!this._boundingInfo) {
  9905. this._updateBoundingInfo();
  9906. }
  9907. return this._boundingInfo;
  9908. };
  9909. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  9910. this._boundingInfo = boundingInfo;
  9911. };
  9912. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9913. get: function () {
  9914. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9915. },
  9916. enumerable: true,
  9917. configurable: true
  9918. });
  9919. AbstractMesh.prototype._preActivate = function () {
  9920. };
  9921. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  9922. };
  9923. AbstractMesh.prototype._activate = function (renderId) {
  9924. this._renderId = renderId;
  9925. };
  9926. AbstractMesh.prototype.getWorldMatrix = function () {
  9927. if (this._masterMesh) {
  9928. return this._masterMesh.getWorldMatrix();
  9929. }
  9930. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9931. this.computeWorldMatrix();
  9932. }
  9933. return this._worldMatrix;
  9934. };
  9935. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9936. get: function () {
  9937. return this._worldMatrix;
  9938. },
  9939. enumerable: true,
  9940. configurable: true
  9941. });
  9942. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9943. get: function () {
  9944. return this._absolutePosition;
  9945. },
  9946. enumerable: true,
  9947. configurable: true
  9948. });
  9949. AbstractMesh.prototype.freezeWorldMatrix = function () {
  9950. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  9951. this.computeWorldMatrix(true);
  9952. this._isWorldMatrixFrozen = true;
  9953. };
  9954. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  9955. this._isWorldMatrixFrozen = false;
  9956. this.computeWorldMatrix(true);
  9957. };
  9958. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  9959. get: function () {
  9960. return this._isWorldMatrixFrozen;
  9961. },
  9962. enumerable: true,
  9963. configurable: true
  9964. });
  9965. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9966. axis.normalize();
  9967. if (!this.rotationQuaternion) {
  9968. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9969. this.rotation = BABYLON.Vector3.Zero();
  9970. }
  9971. var rotationQuaternion;
  9972. if (!space || space === BABYLON.Space.LOCAL) {
  9973. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  9974. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  9975. }
  9976. else {
  9977. if (this.parent) {
  9978. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9979. invertParentWorldMatrix.invert();
  9980. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9981. }
  9982. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  9983. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  9984. }
  9985. };
  9986. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9987. var displacementVector = axis.scale(distance);
  9988. if (!space || space === BABYLON.Space.LOCAL) {
  9989. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9990. this.setPositionWithLocalVector(tempV3);
  9991. }
  9992. else {
  9993. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9994. }
  9995. };
  9996. AbstractMesh.prototype.getAbsolutePosition = function () {
  9997. this.computeWorldMatrix();
  9998. return this._absolutePosition;
  9999. };
  10000. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10001. if (!absolutePosition) {
  10002. return;
  10003. }
  10004. var absolutePositionX;
  10005. var absolutePositionY;
  10006. var absolutePositionZ;
  10007. if (absolutePosition.x === undefined) {
  10008. if (arguments.length < 3) {
  10009. return;
  10010. }
  10011. absolutePositionX = arguments[0];
  10012. absolutePositionY = arguments[1];
  10013. absolutePositionZ = arguments[2];
  10014. }
  10015. else {
  10016. absolutePositionX = absolutePosition.x;
  10017. absolutePositionY = absolutePosition.y;
  10018. absolutePositionZ = absolutePosition.z;
  10019. }
  10020. if (this.parent) {
  10021. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10022. invertParentWorldMatrix.invert();
  10023. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10024. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10025. }
  10026. else {
  10027. this.position.x = absolutePositionX;
  10028. this.position.y = absolutePositionY;
  10029. this.position.z = absolutePositionZ;
  10030. }
  10031. };
  10032. // ================================== Point of View Movement =================================
  10033. /**
  10034. * Perform relative position change from the point of view of behind the front of the mesh.
  10035. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10036. * Supports definition of mesh facing forward or backward.
  10037. * @param {number} amountRight
  10038. * @param {number} amountUp
  10039. * @param {number} amountForward
  10040. */
  10041. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10042. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10043. };
  10044. /**
  10045. * Calculate relative position change from the point of view of behind the front of the mesh.
  10046. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10047. * Supports definition of mesh facing forward or backward.
  10048. * @param {number} amountRight
  10049. * @param {number} amountUp
  10050. * @param {number} amountForward
  10051. */
  10052. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10053. var rotMatrix = new BABYLON.Matrix();
  10054. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10055. rotQuaternion.toRotationMatrix(rotMatrix);
  10056. var translationDelta = BABYLON.Vector3.Zero();
  10057. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10058. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10059. return translationDelta;
  10060. };
  10061. // ================================== Point of View Rotation =================================
  10062. /**
  10063. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10064. * Supports definition of mesh facing forward or backward.
  10065. * @param {number} flipBack
  10066. * @param {number} twirlClockwise
  10067. * @param {number} tiltRight
  10068. */
  10069. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10070. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10071. };
  10072. /**
  10073. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10074. * Supports definition of mesh facing forward or backward.
  10075. * @param {number} flipBack
  10076. * @param {number} twirlClockwise
  10077. * @param {number} tiltRight
  10078. */
  10079. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10080. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10081. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10082. };
  10083. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10084. this._pivotMatrix = matrix;
  10085. this._cache.pivotMatrixUpdated = true;
  10086. };
  10087. AbstractMesh.prototype.getPivotMatrix = function () {
  10088. return this._pivotMatrix;
  10089. };
  10090. AbstractMesh.prototype._isSynchronized = function () {
  10091. if (this._isDirty) {
  10092. return false;
  10093. }
  10094. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10095. return false;
  10096. if (this._cache.pivotMatrixUpdated) {
  10097. return false;
  10098. }
  10099. if (this.infiniteDistance) {
  10100. return false;
  10101. }
  10102. if (!this._cache.position.equals(this.position))
  10103. return false;
  10104. if (this.rotationQuaternion) {
  10105. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10106. return false;
  10107. }
  10108. if (!this._cache.rotation.equals(this.rotation))
  10109. return false;
  10110. if (!this._cache.scaling.equals(this.scaling))
  10111. return false;
  10112. return true;
  10113. };
  10114. AbstractMesh.prototype._initCache = function () {
  10115. _super.prototype._initCache.call(this);
  10116. this._cache.localMatrixUpdated = false;
  10117. this._cache.position = BABYLON.Vector3.Zero();
  10118. this._cache.scaling = BABYLON.Vector3.Zero();
  10119. this._cache.rotation = BABYLON.Vector3.Zero();
  10120. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10121. this._cache.billboardMode = -1;
  10122. };
  10123. AbstractMesh.prototype.markAsDirty = function (property) {
  10124. if (property === "rotation") {
  10125. this.rotationQuaternion = null;
  10126. }
  10127. this._currentRenderId = Number.MAX_VALUE;
  10128. this._isDirty = true;
  10129. };
  10130. AbstractMesh.prototype._updateBoundingInfo = function () {
  10131. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10132. this._boundingInfo.update(this.worldMatrixFromCache);
  10133. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10134. };
  10135. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10136. if (!this.subMeshes) {
  10137. return;
  10138. }
  10139. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10140. var subMesh = this.subMeshes[subIndex];
  10141. if (!subMesh.IsGlobal) {
  10142. subMesh.updateBoundingInfo(matrix);
  10143. }
  10144. }
  10145. };
  10146. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10147. if (this._isWorldMatrixFrozen) {
  10148. return this._worldMatrix;
  10149. }
  10150. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10151. this._currentRenderId = this.getScene().getRenderId();
  10152. return this._worldMatrix;
  10153. }
  10154. this._cache.position.copyFrom(this.position);
  10155. this._cache.scaling.copyFrom(this.scaling);
  10156. this._cache.pivotMatrixUpdated = false;
  10157. this._cache.billboardMode = this.billboardMode;
  10158. this._currentRenderId = this.getScene().getRenderId();
  10159. this._isDirty = false;
  10160. // Scaling
  10161. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  10162. // Rotation
  10163. //rotate, if quaternion is set and rotation was used
  10164. if (this.rotationQuaternion) {
  10165. var len = this.rotation.length();
  10166. if (len) {
  10167. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  10168. this.rotation.copyFromFloats(0, 0, 0);
  10169. }
  10170. }
  10171. if (this.rotationQuaternion) {
  10172. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  10173. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10174. }
  10175. else {
  10176. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  10177. this._cache.rotation.copyFrom(this.rotation);
  10178. }
  10179. // Translation
  10180. if (this.infiniteDistance && !this.parent) {
  10181. var camera = this.getScene().activeCamera;
  10182. if (camera) {
  10183. var cameraWorldMatrix = camera.getWorldMatrix();
  10184. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10185. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  10186. }
  10187. }
  10188. else {
  10189. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  10190. }
  10191. // Composing transformations
  10192. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  10193. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  10194. // Billboarding
  10195. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10196. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  10197. var localPosition = BABYLON.Tmp.Vector3[0];
  10198. if (this.parent && this.parent.getWorldMatrix) {
  10199. this._markSyncedWithParent();
  10200. var parentMatrix;
  10201. if (this._meshToBoneReferal) {
  10202. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10203. parentMatrix = BABYLON.Tmp.Matrix[6];
  10204. }
  10205. else {
  10206. parentMatrix = this.parent.getWorldMatrix();
  10207. }
  10208. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  10209. localPosition = BABYLON.Tmp.Vector3[1];
  10210. }
  10211. var zero = this.getScene().activeCamera.globalPosition.clone();
  10212. if (this.parent && this.parent.position) {
  10213. localPosition.addInPlace(this.parent.position);
  10214. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  10215. }
  10216. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  10217. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10218. zero.x = localPosition.x + BABYLON.Epsilon;
  10219. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10220. zero.y = localPosition.y + BABYLON.Epsilon;
  10221. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10222. zero.z = localPosition.z + BABYLON.Epsilon;
  10223. }
  10224. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  10225. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  10226. BABYLON.Tmp.Matrix[3].invert();
  10227. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  10228. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  10229. }
  10230. // Local world
  10231. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  10232. // Parent
  10233. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10234. this._markSyncedWithParent();
  10235. if (this._meshToBoneReferal) {
  10236. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10237. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  10238. }
  10239. else {
  10240. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10241. }
  10242. }
  10243. else {
  10244. this._worldMatrix.copyFrom(this._localWorld);
  10245. }
  10246. // Bounding info
  10247. this._updateBoundingInfo();
  10248. // Absolute position
  10249. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10250. // Callbacks
  10251. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  10252. if (!this._poseMatrix) {
  10253. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  10254. }
  10255. return this._worldMatrix;
  10256. };
  10257. /**
  10258. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10259. * @param func: callback function to add
  10260. */
  10261. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10262. this.onAfterWorldMatrixUpdateObservable.add(func);
  10263. };
  10264. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10265. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  10266. };
  10267. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10268. this.computeWorldMatrix();
  10269. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10270. };
  10271. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10272. this.computeWorldMatrix();
  10273. var invLocalWorldMatrix = this._localWorld.clone();
  10274. invLocalWorldMatrix.invert();
  10275. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10276. };
  10277. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10278. this.computeWorldMatrix(true);
  10279. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10280. };
  10281. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  10282. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10283. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10284. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10285. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10286. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10287. /// <returns>Mesh oriented towards targetMesh</returns>
  10288. if (yawCor === void 0) { yawCor = 0; }
  10289. if (pitchCor === void 0) { pitchCor = 0; }
  10290. if (rollCor === void 0) { rollCor = 0; }
  10291. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  10292. var dv = AbstractMesh._lookAtVectorCache;
  10293. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  10294. targetPoint.subtractToRef(pos, dv);
  10295. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10296. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10297. var pitch = Math.atan2(dv.y, len);
  10298. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  10299. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  10300. };
  10301. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  10302. this._meshToBoneReferal = affectedMesh;
  10303. this.parent = bone;
  10304. if (bone.getWorldMatrix().determinant() < 0) {
  10305. this.scalingDeterminant *= -1;
  10306. }
  10307. };
  10308. AbstractMesh.prototype.detachFromBone = function () {
  10309. if (this.parent.getWorldMatrix().determinant() < 0) {
  10310. this.scalingDeterminant *= -1;
  10311. }
  10312. this._meshToBoneReferal = null;
  10313. this.parent = null;
  10314. };
  10315. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10316. return this._boundingInfo.isInFrustum(frustumPlanes);
  10317. };
  10318. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10319. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  10320. ;
  10321. };
  10322. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10323. if (!this._boundingInfo || !mesh._boundingInfo) {
  10324. return false;
  10325. }
  10326. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10327. };
  10328. AbstractMesh.prototype.intersectsPoint = function (point) {
  10329. if (!this._boundingInfo) {
  10330. return false;
  10331. }
  10332. return this._boundingInfo.intersectsPoint(point);
  10333. };
  10334. // Physics
  10335. /**
  10336. * @Deprecated. Use new PhysicsImpostor instead.
  10337. * */
  10338. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10339. //legacy support
  10340. if (impostor.impostor) {
  10341. options = impostor;
  10342. impostor = impostor.impostor;
  10343. }
  10344. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  10345. return this.physicsImpostor.physicsBody;
  10346. };
  10347. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10348. return this.physicsImpostor;
  10349. };
  10350. /**
  10351. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  10352. */
  10353. AbstractMesh.prototype.getPhysicsMass = function () {
  10354. return this.physicsImpostor.getParam("mass");
  10355. };
  10356. /**
  10357. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  10358. */
  10359. AbstractMesh.prototype.getPhysicsFriction = function () {
  10360. return this.physicsImpostor.getParam("friction");
  10361. };
  10362. /**
  10363. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  10364. */
  10365. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10366. return this.physicsImpostor.getParam("restitution");
  10367. };
  10368. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10369. if (!camera) {
  10370. camera = this.getScene().activeCamera;
  10371. }
  10372. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10373. };
  10374. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10375. if (!camera) {
  10376. camera = this.getScene().activeCamera;
  10377. }
  10378. return this.absolutePosition.subtract(camera.position).length();
  10379. };
  10380. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10381. if (!this.physicsImpostor) {
  10382. return;
  10383. }
  10384. this.physicsImpostor.applyImpulse(force, contactPoint);
  10385. };
  10386. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10387. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  10388. return;
  10389. }
  10390. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  10391. mainPivot: pivot1,
  10392. connectedPivot: pivot2,
  10393. nativeParams: options
  10394. });
  10395. };
  10396. /**
  10397. * @Deprecated
  10398. */
  10399. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10400. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  10401. this.updatePhysicsBody();
  10402. };
  10403. /**
  10404. * @Deprecated
  10405. * Calling this function is not needed anymore.
  10406. * The physics engine takes care of transofmration automatically.
  10407. */
  10408. AbstractMesh.prototype.updatePhysicsBody = function () {
  10409. //Unneeded
  10410. };
  10411. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  10412. // Collisions
  10413. get: function () {
  10414. return this._checkCollisions;
  10415. },
  10416. set: function (collisionEnabled) {
  10417. this._checkCollisions = collisionEnabled;
  10418. if (this.getScene().workerCollisions) {
  10419. this.getScene().collisionCoordinator.onMeshUpdated(this);
  10420. }
  10421. },
  10422. enumerable: true,
  10423. configurable: true
  10424. });
  10425. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10426. var globalPosition = this.getAbsolutePosition();
  10427. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10428. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10429. this._collider.radius = this.ellipsoid;
  10430. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  10431. };
  10432. // Submeshes octree
  10433. /**
  10434. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10435. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10436. */
  10437. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10438. if (maxCapacity === void 0) { maxCapacity = 64; }
  10439. if (maxDepth === void 0) { maxDepth = 2; }
  10440. if (!this._submeshesOctree) {
  10441. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10442. }
  10443. this.computeWorldMatrix(true);
  10444. // Update octree
  10445. var bbox = this.getBoundingInfo().boundingBox;
  10446. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10447. return this._submeshesOctree;
  10448. };
  10449. // Collisions
  10450. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10451. this._generatePointsArray();
  10452. // Transformation
  10453. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10454. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10455. subMesh._lastColliderWorldVertices = [];
  10456. subMesh._trianglePlanes = [];
  10457. var start = subMesh.verticesStart;
  10458. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10459. for (var i = start; i < end; i++) {
  10460. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10461. }
  10462. }
  10463. // Collide
  10464. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  10465. if (collider.collisionFound) {
  10466. collider.collidedMesh = this;
  10467. }
  10468. };
  10469. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10470. var subMeshes;
  10471. var len;
  10472. // Octrees
  10473. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10474. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10475. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10476. len = intersections.length;
  10477. subMeshes = intersections.data;
  10478. }
  10479. else {
  10480. subMeshes = this.subMeshes;
  10481. len = subMeshes.length;
  10482. }
  10483. for (var index = 0; index < len; index++) {
  10484. var subMesh = subMeshes[index];
  10485. // Bounding test
  10486. if (len > 1 && !subMesh._checkCollision(collider))
  10487. continue;
  10488. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10489. }
  10490. };
  10491. AbstractMesh.prototype._checkCollision = function (collider) {
  10492. // Bounding box test
  10493. if (!this._boundingInfo._checkCollision(collider))
  10494. return;
  10495. // Transformation matrix
  10496. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10497. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10498. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10499. };
  10500. // Picking
  10501. AbstractMesh.prototype._generatePointsArray = function () {
  10502. return false;
  10503. };
  10504. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10505. var pickingInfo = new BABYLON.PickingInfo();
  10506. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10507. return pickingInfo;
  10508. }
  10509. if (!this._generatePointsArray()) {
  10510. return pickingInfo;
  10511. }
  10512. var intersectInfo = null;
  10513. // Octrees
  10514. var subMeshes;
  10515. var len;
  10516. if (this._submeshesOctree && this.useOctreeForPicking) {
  10517. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10518. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10519. len = intersections.length;
  10520. subMeshes = intersections.data;
  10521. }
  10522. else {
  10523. subMeshes = this.subMeshes;
  10524. len = subMeshes.length;
  10525. }
  10526. for (var index = 0; index < len; index++) {
  10527. var subMesh = subMeshes[index];
  10528. // Bounding test
  10529. if (len > 1 && !subMesh.canIntersects(ray))
  10530. continue;
  10531. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10532. if (currentIntersectInfo) {
  10533. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10534. intersectInfo = currentIntersectInfo;
  10535. intersectInfo.subMeshId = index;
  10536. if (fastCheck) {
  10537. break;
  10538. }
  10539. }
  10540. }
  10541. }
  10542. if (intersectInfo) {
  10543. // Get picked point
  10544. var world = this.getWorldMatrix();
  10545. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10546. var direction = ray.direction.clone();
  10547. direction = direction.scale(intersectInfo.distance);
  10548. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10549. var pickedPoint = worldOrigin.add(worldDirection);
  10550. // Return result
  10551. pickingInfo.hit = true;
  10552. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10553. pickingInfo.pickedPoint = pickedPoint;
  10554. pickingInfo.pickedMesh = this;
  10555. pickingInfo.bu = intersectInfo.bu;
  10556. pickingInfo.bv = intersectInfo.bv;
  10557. pickingInfo.faceId = intersectInfo.faceId;
  10558. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10559. return pickingInfo;
  10560. }
  10561. return pickingInfo;
  10562. };
  10563. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10564. return null;
  10565. };
  10566. AbstractMesh.prototype.releaseSubMeshes = function () {
  10567. if (this.subMeshes) {
  10568. while (this.subMeshes.length) {
  10569. this.subMeshes[0].dispose();
  10570. }
  10571. }
  10572. else {
  10573. this.subMeshes = new Array();
  10574. }
  10575. };
  10576. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10577. var _this = this;
  10578. var index;
  10579. // Action manager
  10580. if (this.actionManager) {
  10581. this.actionManager.dispose();
  10582. this.actionManager = null;
  10583. }
  10584. // Skeleton
  10585. this.skeleton = null;
  10586. // Animations
  10587. this.getScene().stopAnimation(this);
  10588. // Physics
  10589. if (this.physicsImpostor) {
  10590. this.physicsImpostor.dispose();
  10591. }
  10592. // Intersections in progress
  10593. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10594. var other = this._intersectionsInProgress[index];
  10595. var pos = other._intersectionsInProgress.indexOf(this);
  10596. other._intersectionsInProgress.splice(pos, 1);
  10597. }
  10598. this._intersectionsInProgress = [];
  10599. // Lights
  10600. var lights = this.getScene().lights;
  10601. lights.forEach(function (light) {
  10602. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  10603. if (meshIndex !== -1) {
  10604. light.includedOnlyMeshes.splice(meshIndex, 1);
  10605. }
  10606. meshIndex = light.excludedMeshes.indexOf(_this);
  10607. if (meshIndex !== -1) {
  10608. light.excludedMeshes.splice(meshIndex, 1);
  10609. }
  10610. });
  10611. // Edges
  10612. if (this._edgesRenderer) {
  10613. this._edgesRenderer.dispose();
  10614. this._edgesRenderer = null;
  10615. }
  10616. // SubMeshes
  10617. this.releaseSubMeshes();
  10618. // Remove from scene
  10619. this.getScene().removeMesh(this);
  10620. if (!doNotRecurse) {
  10621. // Particles
  10622. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10623. if (this.getScene().particleSystems[index].emitter === this) {
  10624. this.getScene().particleSystems[index].dispose();
  10625. index--;
  10626. }
  10627. }
  10628. // Children
  10629. var objects = this.getDescendants(true);
  10630. for (index = 0; index < objects.length; index++) {
  10631. objects[index].dispose();
  10632. }
  10633. }
  10634. else {
  10635. var childMeshes = this.getChildMeshes(true);
  10636. for (index = 0; index < childMeshes.length; index++) {
  10637. var child = childMeshes[index];
  10638. child.parent = null;
  10639. child.computeWorldMatrix(true);
  10640. }
  10641. }
  10642. _super.prototype.dispose.call(this);
  10643. this.onAfterWorldMatrixUpdateObservable.clear();
  10644. this.onCollideObservable.clear();
  10645. this.onCollisionPositionChangeObservable.clear();
  10646. this._isDisposed = true;
  10647. // Callback
  10648. this.onDisposeObservable.notifyObservers(this);
  10649. this.onDisposeObservable.clear();
  10650. };
  10651. // Statics
  10652. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10653. AbstractMesh._BILLBOARDMODE_X = 1;
  10654. AbstractMesh._BILLBOARDMODE_Y = 2;
  10655. AbstractMesh._BILLBOARDMODE_Z = 4;
  10656. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10657. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  10658. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  10659. return AbstractMesh;
  10660. })(BABYLON.Node);
  10661. BABYLON.AbstractMesh = AbstractMesh;
  10662. })(BABYLON || (BABYLON = {}));
  10663. var BABYLON;
  10664. (function (BABYLON) {
  10665. var Light = (function (_super) {
  10666. __extends(Light, _super);
  10667. function Light(name, scene) {
  10668. _super.call(this, name, scene);
  10669. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  10670. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  10671. this.intensity = 1.0;
  10672. this.range = Number.MAX_VALUE;
  10673. this.includeOnlyWithLayerMask = 0;
  10674. this.includedOnlyMeshes = new Array();
  10675. this.excludedMeshes = new Array();
  10676. this.excludeWithLayerMask = 0;
  10677. // PBR Properties.
  10678. this.radius = 0.00001;
  10679. this._excludedMeshesIds = new Array();
  10680. this._includedOnlyMeshesIds = new Array();
  10681. scene.addLight(this);
  10682. }
  10683. /**
  10684. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10685. */
  10686. Light.prototype.toString = function (fullDetails) {
  10687. var ret = "Name: " + this.name;
  10688. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  10689. if (this.animations) {
  10690. for (var i = 0; i < this.animations.length; i++) {
  10691. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  10692. }
  10693. }
  10694. if (fullDetails) {
  10695. }
  10696. return ret;
  10697. };
  10698. Light.prototype.getShadowGenerator = function () {
  10699. return this._shadowGenerator;
  10700. };
  10701. Light.prototype.getAbsolutePosition = function () {
  10702. return BABYLON.Vector3.Zero();
  10703. };
  10704. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  10705. };
  10706. Light.prototype._getWorldMatrix = function () {
  10707. return BABYLON.Matrix.Identity();
  10708. };
  10709. Light.prototype.canAffectMesh = function (mesh) {
  10710. if (!mesh) {
  10711. return true;
  10712. }
  10713. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  10714. return false;
  10715. }
  10716. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  10717. return false;
  10718. }
  10719. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  10720. return false;
  10721. }
  10722. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  10723. return false;
  10724. }
  10725. return true;
  10726. };
  10727. Light.prototype.getWorldMatrix = function () {
  10728. this._currentRenderId = this.getScene().getRenderId();
  10729. var worldMatrix = this._getWorldMatrix();
  10730. if (this.parent && this.parent.getWorldMatrix) {
  10731. if (!this._parentedWorldMatrix) {
  10732. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  10733. }
  10734. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  10735. this._markSyncedWithParent();
  10736. return this._parentedWorldMatrix;
  10737. }
  10738. return worldMatrix;
  10739. };
  10740. Light.prototype.dispose = function () {
  10741. if (this._shadowGenerator) {
  10742. this._shadowGenerator.dispose();
  10743. this._shadowGenerator = null;
  10744. }
  10745. // Animations
  10746. this.getScene().stopAnimation(this);
  10747. // Remove from scene
  10748. this.getScene().removeLight(this);
  10749. _super.prototype.dispose.call(this);
  10750. };
  10751. Light.prototype.getTypeID = function () {
  10752. return 0;
  10753. };
  10754. Light.prototype.clone = function (name) {
  10755. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  10756. };
  10757. Light.prototype.serialize = function () {
  10758. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  10759. // Type
  10760. serializationObject.type = this.getTypeID();
  10761. // Parent
  10762. if (this.parent) {
  10763. serializationObject.parentId = this.parent.id;
  10764. }
  10765. // Inclusion / exclusions
  10766. if (this.excludedMeshes.length > 0) {
  10767. serializationObject.excludedMeshesIds = [];
  10768. this.excludedMeshes.forEach(function (mesh) {
  10769. serializationObject.excludedMeshesIds.push(mesh.id);
  10770. });
  10771. }
  10772. if (this.includedOnlyMeshes.length > 0) {
  10773. serializationObject.includedOnlyMeshesIds = [];
  10774. this.includedOnlyMeshes.forEach(function (mesh) {
  10775. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  10776. });
  10777. }
  10778. // Animations
  10779. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10780. serializationObject.ranges = this.serializeAnimationRanges();
  10781. return serializationObject;
  10782. };
  10783. Light.GetConstructorFromName = function (type, name, scene) {
  10784. switch (type) {
  10785. case 0:
  10786. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  10787. case 1:
  10788. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  10789. case 2:
  10790. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  10791. case 3:
  10792. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  10793. }
  10794. };
  10795. Light.Parse = function (parsedLight, scene) {
  10796. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  10797. // Inclusion / exclusions
  10798. if (parsedLight.excludedMeshesIds) {
  10799. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  10800. }
  10801. if (parsedLight.includedOnlyMeshesIds) {
  10802. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  10803. }
  10804. // Parent
  10805. if (parsedLight.parentId) {
  10806. light._waitingParentId = parsedLight.parentId;
  10807. }
  10808. // Animations
  10809. if (parsedLight.animations) {
  10810. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  10811. var parsedAnimation = parsedLight.animations[animationIndex];
  10812. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10813. }
  10814. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  10815. }
  10816. if (parsedLight.autoAnimate) {
  10817. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  10818. }
  10819. return light;
  10820. };
  10821. __decorate([
  10822. BABYLON.serializeAsColor3()
  10823. ], Light.prototype, "diffuse", void 0);
  10824. __decorate([
  10825. BABYLON.serializeAsColor3()
  10826. ], Light.prototype, "specular", void 0);
  10827. __decorate([
  10828. BABYLON.serialize()
  10829. ], Light.prototype, "intensity", void 0);
  10830. __decorate([
  10831. BABYLON.serialize()
  10832. ], Light.prototype, "range", void 0);
  10833. __decorate([
  10834. BABYLON.serialize()
  10835. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  10836. __decorate([
  10837. BABYLON.serialize()
  10838. ], Light.prototype, "excludeWithLayerMask", void 0);
  10839. __decorate([
  10840. BABYLON.serialize()
  10841. ], Light.prototype, "radius", void 0);
  10842. return Light;
  10843. })(BABYLON.Node);
  10844. BABYLON.Light = Light;
  10845. })(BABYLON || (BABYLON = {}));
  10846. var BABYLON;
  10847. (function (BABYLON) {
  10848. var PointLight = (function (_super) {
  10849. __extends(PointLight, _super);
  10850. function PointLight(name, position, scene) {
  10851. _super.call(this, name, scene);
  10852. this.position = position;
  10853. }
  10854. PointLight.prototype.getAbsolutePosition = function () {
  10855. return this.transformedPosition ? this.transformedPosition : this.position;
  10856. };
  10857. PointLight.prototype.computeTransformedPosition = function () {
  10858. if (this.parent && this.parent.getWorldMatrix) {
  10859. if (!this.transformedPosition) {
  10860. this.transformedPosition = BABYLON.Vector3.Zero();
  10861. }
  10862. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10863. return true;
  10864. }
  10865. return false;
  10866. };
  10867. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  10868. if (this.parent && this.parent.getWorldMatrix) {
  10869. this.computeTransformedPosition();
  10870. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  10871. return;
  10872. }
  10873. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  10874. };
  10875. PointLight.prototype.needCube = function () {
  10876. return true;
  10877. };
  10878. PointLight.prototype.supportsVSM = function () {
  10879. return false;
  10880. };
  10881. PointLight.prototype.needRefreshPerFrame = function () {
  10882. return false;
  10883. };
  10884. PointLight.prototype.getShadowDirection = function (faceIndex) {
  10885. switch (faceIndex) {
  10886. case 0:
  10887. return new BABYLON.Vector3(1, 0, 0);
  10888. case 1:
  10889. return new BABYLON.Vector3(-1, 0, 0);
  10890. case 2:
  10891. return new BABYLON.Vector3(0, -1, 0);
  10892. case 3:
  10893. return new BABYLON.Vector3(0, 1, 0);
  10894. case 4:
  10895. return new BABYLON.Vector3(0, 0, 1);
  10896. case 5:
  10897. return new BABYLON.Vector3(0, 0, -1);
  10898. }
  10899. return BABYLON.Vector3.Zero();
  10900. };
  10901. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10902. var activeCamera = this.getScene().activeCamera;
  10903. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  10904. };
  10905. PointLight.prototype._getWorldMatrix = function () {
  10906. if (!this._worldMatrix) {
  10907. this._worldMatrix = BABYLON.Matrix.Identity();
  10908. }
  10909. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10910. return this._worldMatrix;
  10911. };
  10912. PointLight.prototype.getTypeID = function () {
  10913. return 0;
  10914. };
  10915. __decorate([
  10916. BABYLON.serializeAsVector3()
  10917. ], PointLight.prototype, "position", void 0);
  10918. return PointLight;
  10919. })(BABYLON.Light);
  10920. BABYLON.PointLight = PointLight;
  10921. })(BABYLON || (BABYLON = {}));
  10922. var BABYLON;
  10923. (function (BABYLON) {
  10924. var SpotLight = (function (_super) {
  10925. __extends(SpotLight, _super);
  10926. function SpotLight(name, position, direction, angle, exponent, scene) {
  10927. _super.call(this, name, scene);
  10928. this.position = position;
  10929. this.direction = direction;
  10930. this.angle = angle;
  10931. this.exponent = exponent;
  10932. }
  10933. SpotLight.prototype.getAbsolutePosition = function () {
  10934. return this.transformedPosition ? this.transformedPosition : this.position;
  10935. };
  10936. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10937. var activeCamera = this.getScene().activeCamera;
  10938. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  10939. };
  10940. SpotLight.prototype.needCube = function () {
  10941. return false;
  10942. };
  10943. SpotLight.prototype.supportsVSM = function () {
  10944. return true;
  10945. };
  10946. SpotLight.prototype.needRefreshPerFrame = function () {
  10947. return false;
  10948. };
  10949. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  10950. return this.direction;
  10951. };
  10952. SpotLight.prototype.setDirectionToTarget = function (target) {
  10953. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  10954. return this.direction;
  10955. };
  10956. SpotLight.prototype.computeTransformedPosition = function () {
  10957. if (this.parent && this.parent.getWorldMatrix) {
  10958. if (!this.transformedPosition) {
  10959. this.transformedPosition = BABYLON.Vector3.Zero();
  10960. }
  10961. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10962. return true;
  10963. }
  10964. return false;
  10965. };
  10966. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  10967. var normalizeDirection;
  10968. if (this.parent && this.parent.getWorldMatrix) {
  10969. if (!this._transformedDirection) {
  10970. this._transformedDirection = BABYLON.Vector3.Zero();
  10971. }
  10972. this.computeTransformedPosition();
  10973. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  10974. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  10975. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  10976. }
  10977. else {
  10978. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  10979. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  10980. }
  10981. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  10982. };
  10983. SpotLight.prototype._getWorldMatrix = function () {
  10984. if (!this._worldMatrix) {
  10985. this._worldMatrix = BABYLON.Matrix.Identity();
  10986. }
  10987. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10988. return this._worldMatrix;
  10989. };
  10990. SpotLight.prototype.getTypeID = function () {
  10991. return 2;
  10992. };
  10993. __decorate([
  10994. BABYLON.serializeAsVector3()
  10995. ], SpotLight.prototype, "position", void 0);
  10996. __decorate([
  10997. BABYLON.serializeAsVector3()
  10998. ], SpotLight.prototype, "direction", void 0);
  10999. __decorate([
  11000. BABYLON.serialize()
  11001. ], SpotLight.prototype, "angle", void 0);
  11002. __decorate([
  11003. BABYLON.serialize()
  11004. ], SpotLight.prototype, "exponent", void 0);
  11005. return SpotLight;
  11006. })(BABYLON.Light);
  11007. BABYLON.SpotLight = SpotLight;
  11008. })(BABYLON || (BABYLON = {}));
  11009. var BABYLON;
  11010. (function (BABYLON) {
  11011. var HemisphericLight = (function (_super) {
  11012. __extends(HemisphericLight, _super);
  11013. function HemisphericLight(name, direction, scene) {
  11014. _super.call(this, name, scene);
  11015. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  11016. this.direction = direction;
  11017. }
  11018. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  11019. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  11020. return this.direction;
  11021. };
  11022. HemisphericLight.prototype.getShadowGenerator = function () {
  11023. return null;
  11024. };
  11025. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  11026. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11027. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  11028. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  11029. };
  11030. HemisphericLight.prototype._getWorldMatrix = function () {
  11031. if (!this._worldMatrix) {
  11032. this._worldMatrix = BABYLON.Matrix.Identity();
  11033. }
  11034. return this._worldMatrix;
  11035. };
  11036. HemisphericLight.prototype.getTypeID = function () {
  11037. return 3;
  11038. };
  11039. __decorate([
  11040. BABYLON.serializeAsColor3()
  11041. ], HemisphericLight.prototype, "groundColor", void 0);
  11042. __decorate([
  11043. BABYLON.serializeAsVector3()
  11044. ], HemisphericLight.prototype, "direction", void 0);
  11045. return HemisphericLight;
  11046. })(BABYLON.Light);
  11047. BABYLON.HemisphericLight = HemisphericLight;
  11048. })(BABYLON || (BABYLON = {}));
  11049. var BABYLON;
  11050. (function (BABYLON) {
  11051. var DirectionalLight = (function (_super) {
  11052. __extends(DirectionalLight, _super);
  11053. function DirectionalLight(name, direction, scene) {
  11054. _super.call(this, name, scene);
  11055. this.shadowOrthoScale = 0.5;
  11056. this.autoUpdateExtends = true;
  11057. // Cache
  11058. this._orthoLeft = Number.MAX_VALUE;
  11059. this._orthoRight = Number.MIN_VALUE;
  11060. this._orthoTop = Number.MIN_VALUE;
  11061. this._orthoBottom = Number.MAX_VALUE;
  11062. this.position = direction.scale(-1);
  11063. this.direction = direction;
  11064. }
  11065. DirectionalLight.prototype.getAbsolutePosition = function () {
  11066. return this.transformedPosition ? this.transformedPosition : this.position;
  11067. };
  11068. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  11069. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11070. return this.direction;
  11071. };
  11072. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11073. var activeCamera = this.getScene().activeCamera;
  11074. // Check extends
  11075. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  11076. var tempVector3 = BABYLON.Vector3.Zero();
  11077. this._orthoLeft = Number.MAX_VALUE;
  11078. this._orthoRight = Number.MIN_VALUE;
  11079. this._orthoTop = Number.MIN_VALUE;
  11080. this._orthoBottom = Number.MAX_VALUE;
  11081. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  11082. var mesh = renderList[meshIndex];
  11083. if (!mesh) {
  11084. continue;
  11085. }
  11086. var boundingInfo = mesh.getBoundingInfo();
  11087. if (!boundingInfo) {
  11088. continue;
  11089. }
  11090. var boundingBox = boundingInfo.boundingBox;
  11091. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  11092. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  11093. if (tempVector3.x < this._orthoLeft)
  11094. this._orthoLeft = tempVector3.x;
  11095. if (tempVector3.y < this._orthoBottom)
  11096. this._orthoBottom = tempVector3.y;
  11097. if (tempVector3.x > this._orthoRight)
  11098. this._orthoRight = tempVector3.x;
  11099. if (tempVector3.y > this._orthoTop)
  11100. this._orthoTop = tempVector3.y;
  11101. }
  11102. }
  11103. }
  11104. var xOffset = this._orthoRight - this._orthoLeft;
  11105. var yOffset = this._orthoTop - this._orthoBottom;
  11106. 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);
  11107. };
  11108. DirectionalLight.prototype.supportsVSM = function () {
  11109. return true;
  11110. };
  11111. DirectionalLight.prototype.needRefreshPerFrame = function () {
  11112. return true;
  11113. };
  11114. DirectionalLight.prototype.needCube = function () {
  11115. return false;
  11116. };
  11117. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  11118. return this.direction;
  11119. };
  11120. DirectionalLight.prototype.computeTransformedPosition = function () {
  11121. if (this.parent && this.parent.getWorldMatrix) {
  11122. if (!this.transformedPosition) {
  11123. this.transformedPosition = BABYLON.Vector3.Zero();
  11124. }
  11125. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11126. return true;
  11127. }
  11128. return false;
  11129. };
  11130. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  11131. if (this.parent && this.parent.getWorldMatrix) {
  11132. if (!this._transformedDirection) {
  11133. this._transformedDirection = BABYLON.Vector3.Zero();
  11134. }
  11135. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11136. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  11137. return;
  11138. }
  11139. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  11140. };
  11141. DirectionalLight.prototype._getWorldMatrix = function () {
  11142. if (!this._worldMatrix) {
  11143. this._worldMatrix = BABYLON.Matrix.Identity();
  11144. }
  11145. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11146. return this._worldMatrix;
  11147. };
  11148. DirectionalLight.prototype.getTypeID = function () {
  11149. return 1;
  11150. };
  11151. __decorate([
  11152. BABYLON.serializeAsVector3()
  11153. ], DirectionalLight.prototype, "position", void 0);
  11154. __decorate([
  11155. BABYLON.serializeAsVector3()
  11156. ], DirectionalLight.prototype, "direction", void 0);
  11157. __decorate([
  11158. BABYLON.serialize()
  11159. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  11160. __decorate([
  11161. BABYLON.serialize()
  11162. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  11163. return DirectionalLight;
  11164. })(BABYLON.Light);
  11165. BABYLON.DirectionalLight = DirectionalLight;
  11166. })(BABYLON || (BABYLON = {}));
  11167. var BABYLON;
  11168. (function (BABYLON) {
  11169. var ShadowGenerator = (function () {
  11170. function ShadowGenerator(mapSize, light) {
  11171. var _this = this;
  11172. // Members
  11173. this._filter = ShadowGenerator.FILTER_NONE;
  11174. this.blurScale = 2;
  11175. this._blurBoxOffset = 0;
  11176. this._bias = 0.00005;
  11177. this._lightDirection = BABYLON.Vector3.Zero();
  11178. this.forceBackFacesOnly = false;
  11179. this._darkness = 0;
  11180. this._transparencyShadow = false;
  11181. this._viewMatrix = BABYLON.Matrix.Zero();
  11182. this._projectionMatrix = BABYLON.Matrix.Zero();
  11183. this._transformMatrix = BABYLON.Matrix.Zero();
  11184. this._worldViewProjection = BABYLON.Matrix.Zero();
  11185. this._currentFaceIndex = 0;
  11186. this._currentFaceIndexCache = 0;
  11187. this._useFullFloat = true;
  11188. this._light = light;
  11189. this._scene = light.getScene();
  11190. this._mapSize = mapSize;
  11191. light._shadowGenerator = this;
  11192. // Texture type fallback from float to int if not supported.
  11193. var textureType;
  11194. var caps = this._scene.getEngine().getCaps();
  11195. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  11196. this._useFullFloat = true;
  11197. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  11198. }
  11199. else {
  11200. this._useFullFloat = false;
  11201. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  11202. }
  11203. // Render target
  11204. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  11205. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11206. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11207. this._shadowMap.anisotropicFilteringLevel = 1;
  11208. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11209. this._shadowMap.renderParticles = false;
  11210. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  11211. _this._currentFaceIndex = faceIndex;
  11212. });
  11213. this._shadowMap.onAfterUnbindObservable.add(function () {
  11214. if (!_this.useBlurVarianceShadowMap) {
  11215. return;
  11216. }
  11217. if (!_this._shadowMap2) {
  11218. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  11219. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11220. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11221. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  11222. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  11223. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  11224. effect.setTexture("textureSampler", _this._shadowMap);
  11225. });
  11226. _this.blurBoxOffset = 1;
  11227. }
  11228. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  11229. });
  11230. // Custom render function
  11231. var renderSubMesh = function (subMesh) {
  11232. var mesh = subMesh.getRenderingMesh();
  11233. var scene = _this._scene;
  11234. var engine = scene.getEngine();
  11235. // Culling
  11236. engine.setState(subMesh.getMaterial().backFaceCulling);
  11237. // Managing instances
  11238. var batch = mesh._getInstancesRenderList(subMesh._id);
  11239. if (batch.mustReturn) {
  11240. return;
  11241. }
  11242. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11243. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  11244. engine.enableEffect(_this._effect);
  11245. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  11246. var material = subMesh.getMaterial();
  11247. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  11248. _this._effect.setVector3("lightPosition", _this.getLight().position);
  11249. if (_this.getLight().needCube()) {
  11250. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  11251. }
  11252. // Alpha test
  11253. if (material && material.needAlphaTesting()) {
  11254. var alphaTexture = material.getAlphaTestTexture();
  11255. _this._effect.setTexture("diffuseSampler", alphaTexture);
  11256. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  11257. }
  11258. // Bones
  11259. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11260. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  11261. }
  11262. if (_this.forceBackFacesOnly) {
  11263. engine.setState(true, 0, false, true);
  11264. }
  11265. // Draw
  11266. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  11267. if (_this.forceBackFacesOnly) {
  11268. engine.setState(true, 0, false, false);
  11269. }
  11270. }
  11271. else {
  11272. // Need to reset refresh rate of the shadowMap
  11273. _this._shadowMap.resetRefreshCounter();
  11274. }
  11275. };
  11276. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  11277. var index;
  11278. for (index = 0; index < opaqueSubMeshes.length; index++) {
  11279. renderSubMesh(opaqueSubMeshes.data[index]);
  11280. }
  11281. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  11282. renderSubMesh(alphaTestSubMeshes.data[index]);
  11283. }
  11284. if (_this._transparencyShadow) {
  11285. for (index = 0; index < transparentSubMeshes.length; index++) {
  11286. renderSubMesh(transparentSubMeshes.data[index]);
  11287. }
  11288. }
  11289. };
  11290. this._shadowMap.onClearObservable.add(function (engine) {
  11291. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  11292. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  11293. }
  11294. else {
  11295. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  11296. }
  11297. });
  11298. }
  11299. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  11300. // Static
  11301. get: function () {
  11302. return ShadowGenerator._FILTER_NONE;
  11303. },
  11304. enumerable: true,
  11305. configurable: true
  11306. });
  11307. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  11308. get: function () {
  11309. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  11310. },
  11311. enumerable: true,
  11312. configurable: true
  11313. });
  11314. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  11315. get: function () {
  11316. return ShadowGenerator._FILTER_POISSONSAMPLING;
  11317. },
  11318. enumerable: true,
  11319. configurable: true
  11320. });
  11321. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  11322. get: function () {
  11323. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  11324. },
  11325. enumerable: true,
  11326. configurable: true
  11327. });
  11328. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  11329. get: function () {
  11330. return this._bias;
  11331. },
  11332. set: function (bias) {
  11333. this._bias = bias;
  11334. },
  11335. enumerable: true,
  11336. configurable: true
  11337. });
  11338. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  11339. get: function () {
  11340. return this._blurBoxOffset;
  11341. },
  11342. set: function (value) {
  11343. var _this = this;
  11344. if (this._blurBoxOffset === value) {
  11345. return;
  11346. }
  11347. this._blurBoxOffset = value;
  11348. if (this._boxBlurPostprocess) {
  11349. this._boxBlurPostprocess.dispose();
  11350. }
  11351. 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);
  11352. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  11353. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  11354. });
  11355. },
  11356. enumerable: true,
  11357. configurable: true
  11358. });
  11359. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  11360. get: function () {
  11361. return this._filter;
  11362. },
  11363. set: function (value) {
  11364. if (this._filter === value) {
  11365. return;
  11366. }
  11367. this._filter = value;
  11368. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  11369. this._shadowMap.anisotropicFilteringLevel = 16;
  11370. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  11371. }
  11372. else {
  11373. this._shadowMap.anisotropicFilteringLevel = 1;
  11374. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11375. }
  11376. },
  11377. enumerable: true,
  11378. configurable: true
  11379. });
  11380. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  11381. get: function () {
  11382. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  11383. },
  11384. set: function (value) {
  11385. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11386. },
  11387. enumerable: true,
  11388. configurable: true
  11389. });
  11390. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  11391. get: function () {
  11392. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  11393. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  11394. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  11395. },
  11396. set: function (value) {
  11397. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  11398. },
  11399. enumerable: true,
  11400. configurable: true
  11401. });
  11402. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  11403. get: function () {
  11404. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  11405. },
  11406. set: function (value) {
  11407. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11408. },
  11409. enumerable: true,
  11410. configurable: true
  11411. });
  11412. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  11413. var defines = [];
  11414. if (this._useFullFloat) {
  11415. defines.push("#define FULLFLOAT");
  11416. }
  11417. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  11418. defines.push("#define VSM");
  11419. }
  11420. if (this.getLight().needCube()) {
  11421. defines.push("#define CUBEMAP");
  11422. }
  11423. var attribs = [BABYLON.VertexBuffer.PositionKind];
  11424. var mesh = subMesh.getMesh();
  11425. var material = subMesh.getMaterial();
  11426. // Alpha test
  11427. if (material && material.needAlphaTesting()) {
  11428. defines.push("#define ALPHATEST");
  11429. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11430. attribs.push(BABYLON.VertexBuffer.UVKind);
  11431. defines.push("#define UV1");
  11432. }
  11433. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  11434. var alphaTexture = material.getAlphaTestTexture();
  11435. if (alphaTexture.coordinatesIndex === 1) {
  11436. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  11437. defines.push("#define UV2");
  11438. }
  11439. }
  11440. }
  11441. // Bones
  11442. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11443. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  11444. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  11445. if (mesh.numBoneInfluencers > 4) {
  11446. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  11447. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  11448. }
  11449. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  11450. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  11451. }
  11452. else {
  11453. defines.push("#define NUM_BONE_INFLUENCERS 0");
  11454. }
  11455. // Instances
  11456. if (useInstances) {
  11457. defines.push("#define INSTANCES");
  11458. attribs.push("world0");
  11459. attribs.push("world1");
  11460. attribs.push("world2");
  11461. attribs.push("world3");
  11462. }
  11463. // Get correct effect
  11464. var join = defines.join("\n");
  11465. if (this._cachedDefines !== join) {
  11466. this._cachedDefines = join;
  11467. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  11468. }
  11469. return this._effect.isReady();
  11470. };
  11471. ShadowGenerator.prototype.getShadowMap = function () {
  11472. return this._shadowMap;
  11473. };
  11474. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  11475. if (this._shadowMap2) {
  11476. return this._shadowMap2;
  11477. }
  11478. return this._shadowMap;
  11479. };
  11480. ShadowGenerator.prototype.getLight = function () {
  11481. return this._light;
  11482. };
  11483. // Methods
  11484. ShadowGenerator.prototype.getTransformMatrix = function () {
  11485. var scene = this._scene;
  11486. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  11487. return this._transformMatrix;
  11488. }
  11489. this._currentRenderID = scene.getRenderId();
  11490. this._currentFaceIndexCache = this._currentFaceIndex;
  11491. var lightPosition = this._light.position;
  11492. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  11493. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  11494. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  11495. }
  11496. if (this._light.computeTransformedPosition()) {
  11497. lightPosition = this._light.transformedPosition;
  11498. }
  11499. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  11500. this._cachedPosition = lightPosition.clone();
  11501. this._cachedDirection = this._lightDirection.clone();
  11502. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  11503. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  11504. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  11505. }
  11506. return this._transformMatrix;
  11507. };
  11508. ShadowGenerator.prototype.getDarkness = function () {
  11509. return this._darkness;
  11510. };
  11511. ShadowGenerator.prototype.setDarkness = function (darkness) {
  11512. if (darkness >= 1.0)
  11513. this._darkness = 1.0;
  11514. else if (darkness <= 0.0)
  11515. this._darkness = 0.0;
  11516. else
  11517. this._darkness = darkness;
  11518. };
  11519. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  11520. this._transparencyShadow = hasShadow;
  11521. };
  11522. ShadowGenerator.prototype._packHalf = function (depth) {
  11523. var scale = depth * 255.0;
  11524. var fract = scale - Math.floor(scale);
  11525. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  11526. };
  11527. ShadowGenerator.prototype.dispose = function () {
  11528. this._shadowMap.dispose();
  11529. if (this._shadowMap2) {
  11530. this._shadowMap2.dispose();
  11531. }
  11532. if (this._downSamplePostprocess) {
  11533. this._downSamplePostprocess.dispose();
  11534. }
  11535. if (this._boxBlurPostprocess) {
  11536. this._boxBlurPostprocess.dispose();
  11537. }
  11538. };
  11539. ShadowGenerator.prototype.serialize = function () {
  11540. var serializationObject = {};
  11541. serializationObject.lightId = this._light.id;
  11542. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  11543. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  11544. serializationObject.usePoissonSampling = this.usePoissonSampling;
  11545. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  11546. serializationObject.renderList = [];
  11547. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  11548. var mesh = this.getShadowMap().renderList[meshIndex];
  11549. serializationObject.renderList.push(mesh.id);
  11550. }
  11551. return serializationObject;
  11552. };
  11553. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  11554. //casting to point light, as light is missing the position attr and typescript complains.
  11555. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  11556. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  11557. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  11558. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  11559. meshes.forEach(function (mesh) {
  11560. shadowGenerator.getShadowMap().renderList.push(mesh);
  11561. });
  11562. }
  11563. if (parsedShadowGenerator.usePoissonSampling) {
  11564. shadowGenerator.usePoissonSampling = true;
  11565. }
  11566. else if (parsedShadowGenerator.useVarianceShadowMap) {
  11567. shadowGenerator.useVarianceShadowMap = true;
  11568. }
  11569. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  11570. shadowGenerator.useBlurVarianceShadowMap = true;
  11571. if (parsedShadowGenerator.blurScale) {
  11572. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  11573. }
  11574. if (parsedShadowGenerator.blurBoxOffset) {
  11575. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  11576. }
  11577. }
  11578. if (parsedShadowGenerator.bias !== undefined) {
  11579. shadowGenerator.bias = parsedShadowGenerator.bias;
  11580. }
  11581. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  11582. return shadowGenerator;
  11583. };
  11584. ShadowGenerator._FILTER_NONE = 0;
  11585. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  11586. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  11587. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  11588. return ShadowGenerator;
  11589. })();
  11590. BABYLON.ShadowGenerator = ShadowGenerator;
  11591. })(BABYLON || (BABYLON = {}));
  11592. var BABYLON;
  11593. (function (BABYLON) {
  11594. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  11595. if (boxMin.x > sphereCenter.x + sphereRadius)
  11596. return false;
  11597. if (sphereCenter.x - sphereRadius > boxMax.x)
  11598. return false;
  11599. if (boxMin.y > sphereCenter.y + sphereRadius)
  11600. return false;
  11601. if (sphereCenter.y - sphereRadius > boxMax.y)
  11602. return false;
  11603. if (boxMin.z > sphereCenter.z + sphereRadius)
  11604. return false;
  11605. if (sphereCenter.z - sphereRadius > boxMax.z)
  11606. return false;
  11607. return true;
  11608. };
  11609. var getLowestRoot = (function () {
  11610. var result = { root: 0, found: false };
  11611. return function (a, b, c, maxR) {
  11612. result.root = 0;
  11613. result.found = false;
  11614. var determinant = b * b - 4.0 * a * c;
  11615. if (determinant < 0)
  11616. return result;
  11617. var sqrtD = Math.sqrt(determinant);
  11618. var r1 = (-b - sqrtD) / (2.0 * a);
  11619. var r2 = (-b + sqrtD) / (2.0 * a);
  11620. if (r1 > r2) {
  11621. var temp = r2;
  11622. r2 = r1;
  11623. r1 = temp;
  11624. }
  11625. if (r1 > 0 && r1 < maxR) {
  11626. result.root = r1;
  11627. result.found = true;
  11628. return result;
  11629. }
  11630. if (r2 > 0 && r2 < maxR) {
  11631. result.root = r2;
  11632. result.found = true;
  11633. return result;
  11634. }
  11635. return result;
  11636. };
  11637. })();
  11638. var Collider = (function () {
  11639. function Collider() {
  11640. this.radius = new BABYLON.Vector3(1, 1, 1);
  11641. this.retry = 0;
  11642. this.basePointWorld = BABYLON.Vector3.Zero();
  11643. this.velocityWorld = BABYLON.Vector3.Zero();
  11644. this.normalizedVelocity = BABYLON.Vector3.Zero();
  11645. this._collisionPoint = BABYLON.Vector3.Zero();
  11646. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  11647. this._tempVector = BABYLON.Vector3.Zero();
  11648. this._tempVector2 = BABYLON.Vector3.Zero();
  11649. this._tempVector3 = BABYLON.Vector3.Zero();
  11650. this._tempVector4 = BABYLON.Vector3.Zero();
  11651. this._edge = BABYLON.Vector3.Zero();
  11652. this._baseToVertex = BABYLON.Vector3.Zero();
  11653. this._destinationPoint = BABYLON.Vector3.Zero();
  11654. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  11655. this._displacementVector = BABYLON.Vector3.Zero();
  11656. }
  11657. // Methods
  11658. Collider.prototype._initialize = function (source, dir, e) {
  11659. this.velocity = dir;
  11660. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  11661. this.basePoint = source;
  11662. source.multiplyToRef(this.radius, this.basePointWorld);
  11663. dir.multiplyToRef(this.radius, this.velocityWorld);
  11664. this.velocityWorldLength = this.velocityWorld.length();
  11665. this.epsilon = e;
  11666. this.collisionFound = false;
  11667. };
  11668. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  11669. pa.subtractToRef(point, this._tempVector);
  11670. pb.subtractToRef(point, this._tempVector2);
  11671. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  11672. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11673. if (d < 0)
  11674. return false;
  11675. pc.subtractToRef(point, this._tempVector3);
  11676. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  11677. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11678. if (d < 0)
  11679. return false;
  11680. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  11681. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11682. return d >= 0;
  11683. };
  11684. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  11685. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  11686. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  11687. if (distance > this.velocityWorldLength + max + sphereRadius) {
  11688. return false;
  11689. }
  11690. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  11691. return false;
  11692. return true;
  11693. };
  11694. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  11695. var t0;
  11696. var embeddedInPlane = false;
  11697. //defensive programming, actually not needed.
  11698. if (!trianglePlaneArray) {
  11699. trianglePlaneArray = [];
  11700. }
  11701. if (!trianglePlaneArray[faceIndex]) {
  11702. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  11703. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  11704. }
  11705. var trianglePlane = trianglePlaneArray[faceIndex];
  11706. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  11707. return;
  11708. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  11709. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  11710. if (normalDotVelocity == 0) {
  11711. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  11712. return;
  11713. embeddedInPlane = true;
  11714. t0 = 0;
  11715. }
  11716. else {
  11717. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  11718. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  11719. if (t0 > t1) {
  11720. var temp = t1;
  11721. t1 = t0;
  11722. t0 = temp;
  11723. }
  11724. if (t0 > 1.0 || t1 < 0.0)
  11725. return;
  11726. if (t0 < 0)
  11727. t0 = 0;
  11728. if (t0 > 1.0)
  11729. t0 = 1.0;
  11730. }
  11731. this._collisionPoint.copyFromFloats(0, 0, 0);
  11732. var found = false;
  11733. var t = 1.0;
  11734. if (!embeddedInPlane) {
  11735. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  11736. this.velocity.scaleToRef(t0, this._tempVector);
  11737. this._planeIntersectionPoint.addInPlace(this._tempVector);
  11738. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  11739. found = true;
  11740. t = t0;
  11741. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  11742. }
  11743. }
  11744. if (!found) {
  11745. var velocitySquaredLength = this.velocity.lengthSquared();
  11746. var a = velocitySquaredLength;
  11747. this.basePoint.subtractToRef(p1, this._tempVector);
  11748. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11749. var c = this._tempVector.lengthSquared() - 1.0;
  11750. var lowestRoot = getLowestRoot(a, b, c, t);
  11751. if (lowestRoot.found) {
  11752. t = lowestRoot.root;
  11753. found = true;
  11754. this._collisionPoint.copyFrom(p1);
  11755. }
  11756. this.basePoint.subtractToRef(p2, this._tempVector);
  11757. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11758. c = this._tempVector.lengthSquared() - 1.0;
  11759. lowestRoot = getLowestRoot(a, b, c, t);
  11760. if (lowestRoot.found) {
  11761. t = lowestRoot.root;
  11762. found = true;
  11763. this._collisionPoint.copyFrom(p2);
  11764. }
  11765. this.basePoint.subtractToRef(p3, this._tempVector);
  11766. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11767. c = this._tempVector.lengthSquared() - 1.0;
  11768. lowestRoot = getLowestRoot(a, b, c, t);
  11769. if (lowestRoot.found) {
  11770. t = lowestRoot.root;
  11771. found = true;
  11772. this._collisionPoint.copyFrom(p3);
  11773. }
  11774. p2.subtractToRef(p1, this._edge);
  11775. p1.subtractToRef(this.basePoint, this._baseToVertex);
  11776. var edgeSquaredLength = this._edge.lengthSquared();
  11777. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11778. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11779. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11780. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11781. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11782. lowestRoot = getLowestRoot(a, b, c, t);
  11783. if (lowestRoot.found) {
  11784. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11785. if (f >= 0.0 && f <= 1.0) {
  11786. t = lowestRoot.root;
  11787. found = true;
  11788. this._edge.scaleInPlace(f);
  11789. p1.addToRef(this._edge, this._collisionPoint);
  11790. }
  11791. }
  11792. p3.subtractToRef(p2, this._edge);
  11793. p2.subtractToRef(this.basePoint, this._baseToVertex);
  11794. edgeSquaredLength = this._edge.lengthSquared();
  11795. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11796. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11797. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11798. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11799. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11800. lowestRoot = getLowestRoot(a, b, c, t);
  11801. if (lowestRoot.found) {
  11802. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11803. if (f >= 0.0 && f <= 1.0) {
  11804. t = lowestRoot.root;
  11805. found = true;
  11806. this._edge.scaleInPlace(f);
  11807. p2.addToRef(this._edge, this._collisionPoint);
  11808. }
  11809. }
  11810. p1.subtractToRef(p3, this._edge);
  11811. p3.subtractToRef(this.basePoint, this._baseToVertex);
  11812. edgeSquaredLength = this._edge.lengthSquared();
  11813. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11814. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11815. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11816. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11817. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11818. lowestRoot = getLowestRoot(a, b, c, t);
  11819. if (lowestRoot.found) {
  11820. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11821. if (f >= 0.0 && f <= 1.0) {
  11822. t = lowestRoot.root;
  11823. found = true;
  11824. this._edge.scaleInPlace(f);
  11825. p3.addToRef(this._edge, this._collisionPoint);
  11826. }
  11827. }
  11828. }
  11829. if (found) {
  11830. var distToCollision = t * this.velocity.length();
  11831. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  11832. if (!this.intersectionPoint) {
  11833. this.intersectionPoint = this._collisionPoint.clone();
  11834. }
  11835. else {
  11836. this.intersectionPoint.copyFrom(this._collisionPoint);
  11837. }
  11838. this.nearestDistance = distToCollision;
  11839. this.collisionFound = true;
  11840. }
  11841. }
  11842. };
  11843. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  11844. for (var i = indexStart; i < indexEnd; i += 3) {
  11845. var p1 = pts[indices[i] - decal];
  11846. var p2 = pts[indices[i + 1] - decal];
  11847. var p3 = pts[indices[i + 2] - decal];
  11848. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  11849. }
  11850. };
  11851. Collider.prototype._getResponse = function (pos, vel) {
  11852. pos.addToRef(vel, this._destinationPoint);
  11853. vel.scaleInPlace((this.nearestDistance / vel.length()));
  11854. this.basePoint.addToRef(vel, pos);
  11855. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  11856. this._slidePlaneNormal.normalize();
  11857. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  11858. pos.addInPlace(this._displacementVector);
  11859. this.intersectionPoint.addInPlace(this._displacementVector);
  11860. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  11861. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  11862. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  11863. };
  11864. return Collider;
  11865. })();
  11866. BABYLON.Collider = Collider;
  11867. })(BABYLON || (BABYLON = {}));
  11868. var BABYLON;
  11869. (function (BABYLON) {
  11870. //WebWorker code will be inserted to this variable.
  11871. BABYLON.CollisionWorker = "";
  11872. (function (WorkerTaskType) {
  11873. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  11874. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  11875. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  11876. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  11877. var WorkerTaskType = BABYLON.WorkerTaskType;
  11878. (function (WorkerReplyType) {
  11879. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  11880. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  11881. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  11882. var WorkerReplyType = BABYLON.WorkerReplyType;
  11883. var CollisionCoordinatorWorker = (function () {
  11884. function CollisionCoordinatorWorker() {
  11885. var _this = this;
  11886. this._scaledPosition = BABYLON.Vector3.Zero();
  11887. this._scaledVelocity = BABYLON.Vector3.Zero();
  11888. this.onMeshUpdated = function (mesh) {
  11889. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  11890. };
  11891. this.onGeometryUpdated = function (geometry) {
  11892. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  11893. };
  11894. this._afterRender = function () {
  11895. if (!_this._init)
  11896. return;
  11897. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  11898. return;
  11899. }
  11900. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  11901. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  11902. if (_this._runningUpdated > 4) {
  11903. return;
  11904. }
  11905. ++_this._runningUpdated;
  11906. var payload = {
  11907. updatedMeshes: _this._addUpdateMeshesList,
  11908. updatedGeometries: _this._addUpdateGeometriesList,
  11909. removedGeometries: _this._toRemoveGeometryArray,
  11910. removedMeshes: _this._toRemoveMeshesArray
  11911. };
  11912. var message = {
  11913. payload: payload,
  11914. taskType: WorkerTaskType.UPDATE
  11915. };
  11916. var serializable = [];
  11917. for (var id in payload.updatedGeometries) {
  11918. if (payload.updatedGeometries.hasOwnProperty(id)) {
  11919. //prepare transferables
  11920. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  11921. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  11922. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  11923. }
  11924. }
  11925. _this._worker.postMessage(message, serializable);
  11926. _this._addUpdateMeshesList = {};
  11927. _this._addUpdateGeometriesList = {};
  11928. _this._toRemoveGeometryArray = [];
  11929. _this._toRemoveMeshesArray = [];
  11930. };
  11931. this._onMessageFromWorker = function (e) {
  11932. var returnData = e.data;
  11933. if (returnData.error != WorkerReplyType.SUCCESS) {
  11934. //TODO what errors can be returned from the worker?
  11935. BABYLON.Tools.Warn("error returned from worker!");
  11936. return;
  11937. }
  11938. switch (returnData.taskType) {
  11939. case WorkerTaskType.INIT:
  11940. _this._init = true;
  11941. //Update the worked with ALL of the scene's current state
  11942. _this._scene.meshes.forEach(function (mesh) {
  11943. _this.onMeshAdded(mesh);
  11944. });
  11945. _this._scene.getGeometries().forEach(function (geometry) {
  11946. _this.onGeometryAdded(geometry);
  11947. });
  11948. break;
  11949. case WorkerTaskType.UPDATE:
  11950. _this._runningUpdated--;
  11951. break;
  11952. case WorkerTaskType.COLLIDE:
  11953. _this._runningCollisionTask = false;
  11954. var returnPayload = returnData.payload;
  11955. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  11956. return;
  11957. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  11958. //cleanup
  11959. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  11960. break;
  11961. }
  11962. };
  11963. this._collisionsCallbackArray = [];
  11964. this._init = false;
  11965. this._runningUpdated = 0;
  11966. this._runningCollisionTask = false;
  11967. this._addUpdateMeshesList = {};
  11968. this._addUpdateGeometriesList = {};
  11969. this._toRemoveGeometryArray = [];
  11970. this._toRemoveMeshesArray = [];
  11971. }
  11972. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  11973. if (!this._init)
  11974. return;
  11975. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  11976. return;
  11977. position.divideToRef(collider.radius, this._scaledPosition);
  11978. velocity.divideToRef(collider.radius, this._scaledVelocity);
  11979. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  11980. var payload = {
  11981. collider: {
  11982. position: this._scaledPosition.asArray(),
  11983. velocity: this._scaledVelocity.asArray(),
  11984. radius: collider.radius.asArray()
  11985. },
  11986. collisionId: collisionIndex,
  11987. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  11988. maximumRetry: maximumRetry
  11989. };
  11990. var message = {
  11991. payload: payload,
  11992. taskType: WorkerTaskType.COLLIDE
  11993. };
  11994. this._worker.postMessage(message);
  11995. };
  11996. CollisionCoordinatorWorker.prototype.init = function (scene) {
  11997. this._scene = scene;
  11998. this._scene.registerAfterRender(this._afterRender);
  11999. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  12000. this._worker = new Worker(workerUrl);
  12001. this._worker.onmessage = this._onMessageFromWorker;
  12002. var message = {
  12003. payload: {},
  12004. taskType: WorkerTaskType.INIT
  12005. };
  12006. this._worker.postMessage(message);
  12007. };
  12008. CollisionCoordinatorWorker.prototype.destroy = function () {
  12009. this._scene.unregisterAfterRender(this._afterRender);
  12010. this._worker.terminate();
  12011. };
  12012. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  12013. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  12014. this.onMeshUpdated(mesh);
  12015. };
  12016. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  12017. this._toRemoveMeshesArray.push(mesh.uniqueId);
  12018. };
  12019. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  12020. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  12021. geometry.onGeometryUpdated = this.onGeometryUpdated;
  12022. this.onGeometryUpdated(geometry);
  12023. };
  12024. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  12025. this._toRemoveGeometryArray.push(geometry.id);
  12026. };
  12027. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  12028. var submeshes = [];
  12029. if (mesh.subMeshes) {
  12030. submeshes = mesh.subMeshes.map(function (sm, idx) {
  12031. return {
  12032. position: idx,
  12033. verticesStart: sm.verticesStart,
  12034. verticesCount: sm.verticesCount,
  12035. indexStart: sm.indexStart,
  12036. indexCount: sm.indexCount,
  12037. hasMaterial: !!sm.getMaterial(),
  12038. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12039. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  12040. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12041. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  12042. };
  12043. });
  12044. }
  12045. var geometryId = null;
  12046. if (mesh instanceof BABYLON.Mesh) {
  12047. geometryId = mesh.geometry ? mesh.geometry.id : null;
  12048. }
  12049. else if (mesh instanceof BABYLON.InstancedMesh) {
  12050. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  12051. }
  12052. return {
  12053. uniqueId: mesh.uniqueId,
  12054. id: mesh.id,
  12055. name: mesh.name,
  12056. geometryId: geometryId,
  12057. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12058. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  12059. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12060. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  12061. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  12062. subMeshes: submeshes,
  12063. checkCollisions: mesh.checkCollisions
  12064. };
  12065. };
  12066. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  12067. return {
  12068. id: geometry.id,
  12069. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  12070. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  12071. indices: new Int32Array(geometry.getIndices() || []),
  12072. };
  12073. };
  12074. return CollisionCoordinatorWorker;
  12075. })();
  12076. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  12077. var CollisionCoordinatorLegacy = (function () {
  12078. function CollisionCoordinatorLegacy() {
  12079. this._scaledPosition = BABYLON.Vector3.Zero();
  12080. this._scaledVelocity = BABYLON.Vector3.Zero();
  12081. this._finalPosition = BABYLON.Vector3.Zero();
  12082. }
  12083. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12084. position.divideToRef(collider.radius, this._scaledPosition);
  12085. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12086. collider.collidedMesh = null;
  12087. collider.retry = 0;
  12088. collider.initialVelocity = this._scaledVelocity;
  12089. collider.initialPosition = this._scaledPosition;
  12090. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  12091. this._finalPosition.multiplyInPlace(collider.radius);
  12092. //run the callback
  12093. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  12094. };
  12095. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  12096. this._scene = scene;
  12097. };
  12098. CollisionCoordinatorLegacy.prototype.destroy = function () {
  12099. //Legacy need no destruction method.
  12100. };
  12101. //No update in legacy mode
  12102. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  12103. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  12104. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  12105. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  12106. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  12107. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  12108. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  12109. if (excludedMesh === void 0) { excludedMesh = null; }
  12110. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  12111. if (collider.retry >= maximumRetry) {
  12112. finalPosition.copyFrom(position);
  12113. return;
  12114. }
  12115. collider._initialize(position, velocity, closeDistance);
  12116. // Check all meshes
  12117. for (var index = 0; index < this._scene.meshes.length; index++) {
  12118. var mesh = this._scene.meshes[index];
  12119. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  12120. mesh._checkCollision(collider);
  12121. }
  12122. }
  12123. if (!collider.collisionFound) {
  12124. position.addToRef(velocity, finalPosition);
  12125. return;
  12126. }
  12127. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  12128. collider._getResponse(position, velocity);
  12129. }
  12130. if (velocity.length() <= closeDistance) {
  12131. finalPosition.copyFrom(position);
  12132. return;
  12133. }
  12134. collider.retry++;
  12135. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  12136. };
  12137. return CollisionCoordinatorLegacy;
  12138. })();
  12139. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  12140. })(BABYLON || (BABYLON = {}));
  12141. var BABYLON;
  12142. (function (BABYLON) {
  12143. var Camera = (function (_super) {
  12144. __extends(Camera, _super);
  12145. function Camera(name, position, scene) {
  12146. _super.call(this, name, scene);
  12147. this.upVector = BABYLON.Vector3.Up();
  12148. this.orthoLeft = null;
  12149. this.orthoRight = null;
  12150. this.orthoBottom = null;
  12151. this.orthoTop = null;
  12152. this.fov = 0.8;
  12153. this.minZ = 1.0;
  12154. this.maxZ = 10000.0;
  12155. this.inertia = 0.9;
  12156. this.mode = Camera.PERSPECTIVE_CAMERA;
  12157. this.isIntermediate = false;
  12158. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  12159. this.layerMask = 0x0FFFFFFF;
  12160. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  12161. // Camera rig members
  12162. this.cameraRigMode = Camera.RIG_MODE_NONE;
  12163. this._rigCameras = new Array();
  12164. // Cache
  12165. this._computedViewMatrix = BABYLON.Matrix.Identity();
  12166. this._projectionMatrix = new BABYLON.Matrix();
  12167. this._postProcesses = new Array();
  12168. this._transformMatrix = BABYLON.Matrix.Zero();
  12169. this._activeMeshes = new BABYLON.SmartArray(256);
  12170. this._globalPosition = BABYLON.Vector3.Zero();
  12171. this._refreshFrustumPlanes = true;
  12172. scene.addCamera(this);
  12173. if (!scene.activeCamera) {
  12174. scene.activeCamera = this;
  12175. }
  12176. this.position = position;
  12177. }
  12178. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  12179. get: function () {
  12180. return Camera._PERSPECTIVE_CAMERA;
  12181. },
  12182. enumerable: true,
  12183. configurable: true
  12184. });
  12185. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  12186. get: function () {
  12187. return Camera._ORTHOGRAPHIC_CAMERA;
  12188. },
  12189. enumerable: true,
  12190. configurable: true
  12191. });
  12192. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  12193. get: function () {
  12194. return Camera._FOVMODE_VERTICAL_FIXED;
  12195. },
  12196. enumerable: true,
  12197. configurable: true
  12198. });
  12199. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  12200. get: function () {
  12201. return Camera._FOVMODE_HORIZONTAL_FIXED;
  12202. },
  12203. enumerable: true,
  12204. configurable: true
  12205. });
  12206. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  12207. get: function () {
  12208. return Camera._RIG_MODE_NONE;
  12209. },
  12210. enumerable: true,
  12211. configurable: true
  12212. });
  12213. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  12214. get: function () {
  12215. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  12216. },
  12217. enumerable: true,
  12218. configurable: true
  12219. });
  12220. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  12221. get: function () {
  12222. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  12223. },
  12224. enumerable: true,
  12225. configurable: true
  12226. });
  12227. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  12228. get: function () {
  12229. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12230. },
  12231. enumerable: true,
  12232. configurable: true
  12233. });
  12234. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  12235. get: function () {
  12236. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  12237. },
  12238. enumerable: true,
  12239. configurable: true
  12240. });
  12241. Object.defineProperty(Camera, "RIG_MODE_VR", {
  12242. get: function () {
  12243. return Camera._RIG_MODE_VR;
  12244. },
  12245. enumerable: true,
  12246. configurable: true
  12247. });
  12248. /**
  12249. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12250. */
  12251. Camera.prototype.toString = function (fullDetails) {
  12252. var ret = "Name: " + this.name;
  12253. ret += ", type: " + this.getTypeName();
  12254. if (this.animations) {
  12255. for (var i = 0; i < this.animations.length; i++) {
  12256. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12257. }
  12258. }
  12259. if (fullDetails) {
  12260. }
  12261. return ret;
  12262. };
  12263. Object.defineProperty(Camera.prototype, "globalPosition", {
  12264. get: function () {
  12265. return this._globalPosition;
  12266. },
  12267. enumerable: true,
  12268. configurable: true
  12269. });
  12270. Camera.prototype.getActiveMeshes = function () {
  12271. return this._activeMeshes;
  12272. };
  12273. Camera.prototype.isActiveMesh = function (mesh) {
  12274. return (this._activeMeshes.indexOf(mesh) !== -1);
  12275. };
  12276. //Cache
  12277. Camera.prototype._initCache = function () {
  12278. _super.prototype._initCache.call(this);
  12279. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12280. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12281. this._cache.mode = undefined;
  12282. this._cache.minZ = undefined;
  12283. this._cache.maxZ = undefined;
  12284. this._cache.fov = undefined;
  12285. this._cache.aspectRatio = undefined;
  12286. this._cache.orthoLeft = undefined;
  12287. this._cache.orthoRight = undefined;
  12288. this._cache.orthoBottom = undefined;
  12289. this._cache.orthoTop = undefined;
  12290. this._cache.renderWidth = undefined;
  12291. this._cache.renderHeight = undefined;
  12292. };
  12293. Camera.prototype._updateCache = function (ignoreParentClass) {
  12294. if (!ignoreParentClass) {
  12295. _super.prototype._updateCache.call(this);
  12296. }
  12297. var engine = this.getEngine();
  12298. this._cache.position.copyFrom(this.position);
  12299. this._cache.upVector.copyFrom(this.upVector);
  12300. this._cache.mode = this.mode;
  12301. this._cache.minZ = this.minZ;
  12302. this._cache.maxZ = this.maxZ;
  12303. this._cache.fov = this.fov;
  12304. this._cache.aspectRatio = engine.getAspectRatio(this);
  12305. this._cache.orthoLeft = this.orthoLeft;
  12306. this._cache.orthoRight = this.orthoRight;
  12307. this._cache.orthoBottom = this.orthoBottom;
  12308. this._cache.orthoTop = this.orthoTop;
  12309. this._cache.renderWidth = engine.getRenderWidth();
  12310. this._cache.renderHeight = engine.getRenderHeight();
  12311. };
  12312. Camera.prototype._updateFromScene = function () {
  12313. this.updateCache();
  12314. this.update();
  12315. };
  12316. // Synchronized
  12317. Camera.prototype._isSynchronized = function () {
  12318. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  12319. };
  12320. Camera.prototype._isSynchronizedViewMatrix = function () {
  12321. if (!_super.prototype._isSynchronized.call(this))
  12322. return false;
  12323. return this._cache.position.equals(this.position)
  12324. && this._cache.upVector.equals(this.upVector)
  12325. && this.isSynchronizedWithParent();
  12326. };
  12327. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  12328. var check = this._cache.mode === this.mode
  12329. && this._cache.minZ === this.minZ
  12330. && this._cache.maxZ === this.maxZ;
  12331. if (!check) {
  12332. return false;
  12333. }
  12334. var engine = this.getEngine();
  12335. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12336. check = this._cache.fov === this.fov
  12337. && this._cache.aspectRatio === engine.getAspectRatio(this);
  12338. }
  12339. else {
  12340. check = this._cache.orthoLeft === this.orthoLeft
  12341. && this._cache.orthoRight === this.orthoRight
  12342. && this._cache.orthoBottom === this.orthoBottom
  12343. && this._cache.orthoTop === this.orthoTop
  12344. && this._cache.renderWidth === engine.getRenderWidth()
  12345. && this._cache.renderHeight === engine.getRenderHeight();
  12346. }
  12347. return check;
  12348. };
  12349. // Controls
  12350. Camera.prototype.attachControl = function (element, noPreventDefault) {
  12351. };
  12352. Camera.prototype.detachControl = function (element) {
  12353. };
  12354. Camera.prototype.update = function () {
  12355. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12356. this._updateRigCameras();
  12357. }
  12358. this._checkInputs();
  12359. };
  12360. Camera.prototype._checkInputs = function () {
  12361. };
  12362. Camera.prototype._cascadePostProcessesToRigCams = function () {
  12363. // invalidate framebuffer
  12364. if (this._postProcesses.length > 0) {
  12365. this._postProcesses[0].markTextureDirty();
  12366. }
  12367. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  12368. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  12369. var cam = this._rigCameras[i];
  12370. var rigPostProcess = cam._rigPostProcess;
  12371. // for VR rig, there does not have to be a post process
  12372. if (rigPostProcess) {
  12373. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  12374. if (isPass) {
  12375. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  12376. cam.isIntermediate = this._postProcesses.length === 0;
  12377. }
  12378. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  12379. rigPostProcess.markTextureDirty();
  12380. }
  12381. else {
  12382. cam._postProcesses = this._postProcesses.slice(0);
  12383. }
  12384. }
  12385. };
  12386. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  12387. if (insertAt === void 0) { insertAt = null; }
  12388. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  12389. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  12390. return 0;
  12391. }
  12392. if (insertAt == null || insertAt < 0) {
  12393. this._postProcesses.push(postProcess);
  12394. }
  12395. else {
  12396. this._postProcesses.splice(insertAt, 0, postProcess);
  12397. }
  12398. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12399. return this._postProcesses.indexOf(postProcess);
  12400. };
  12401. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  12402. if (atIndices === void 0) { atIndices = null; }
  12403. var result = [];
  12404. var i;
  12405. var index;
  12406. if (!atIndices) {
  12407. var idx = this._postProcesses.indexOf(postProcess);
  12408. if (idx !== -1) {
  12409. this._postProcesses.splice(idx, 1);
  12410. }
  12411. }
  12412. else {
  12413. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  12414. // iterate descending, so can just splice as we go
  12415. for (i = atIndices.length - 1; i >= 0; i--) {
  12416. if (this._postProcesses[atIndices[i]] !== postProcess) {
  12417. result.push(i);
  12418. continue;
  12419. }
  12420. this._postProcesses.splice(index, 1);
  12421. }
  12422. }
  12423. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12424. return result;
  12425. };
  12426. Camera.prototype.getWorldMatrix = function () {
  12427. if (!this._worldMatrix) {
  12428. this._worldMatrix = BABYLON.Matrix.Identity();
  12429. }
  12430. var viewMatrix = this.getViewMatrix();
  12431. viewMatrix.invertToRef(this._worldMatrix);
  12432. return this._worldMatrix;
  12433. };
  12434. Camera.prototype._getViewMatrix = function () {
  12435. return BABYLON.Matrix.Identity();
  12436. };
  12437. Camera.prototype.getViewMatrix = function (force) {
  12438. this._computedViewMatrix = this._computeViewMatrix(force);
  12439. if (!force && this._isSynchronizedViewMatrix()) {
  12440. return this._computedViewMatrix;
  12441. }
  12442. this._refreshFrustumPlanes = true;
  12443. if (!this.parent || !this.parent.getWorldMatrix) {
  12444. this._globalPosition.copyFrom(this.position);
  12445. }
  12446. else {
  12447. if (!this._worldMatrix) {
  12448. this._worldMatrix = BABYLON.Matrix.Identity();
  12449. }
  12450. this._computedViewMatrix.invertToRef(this._worldMatrix);
  12451. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  12452. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  12453. this._computedViewMatrix.invert();
  12454. this._markSyncedWithParent();
  12455. }
  12456. this._currentRenderId = this.getScene().getRenderId();
  12457. return this._computedViewMatrix;
  12458. };
  12459. Camera.prototype._computeViewMatrix = function (force) {
  12460. if (!force && this._isSynchronizedViewMatrix()) {
  12461. return this._computedViewMatrix;
  12462. }
  12463. this._computedViewMatrix = this._getViewMatrix();
  12464. this._currentRenderId = this.getScene().getRenderId();
  12465. return this._computedViewMatrix;
  12466. };
  12467. Camera.prototype.getProjectionMatrix = function (force) {
  12468. if (!force && this._isSynchronizedProjectionMatrix()) {
  12469. return this._projectionMatrix;
  12470. }
  12471. this._refreshFrustumPlanes = true;
  12472. var engine = this.getEngine();
  12473. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12474. if (this.minZ <= 0) {
  12475. this.minZ = 0.1;
  12476. }
  12477. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  12478. return this._projectionMatrix;
  12479. }
  12480. var halfWidth = engine.getRenderWidth() / 2.0;
  12481. var halfHeight = engine.getRenderHeight() / 2.0;
  12482. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  12483. return this._projectionMatrix;
  12484. };
  12485. Camera.prototype.getTranformationMatrix = function () {
  12486. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12487. return this._transformMatrix;
  12488. };
  12489. Camera.prototype.updateFrustumPlanes = function () {
  12490. if (!this._refreshFrustumPlanes) {
  12491. return;
  12492. }
  12493. this.getTranformationMatrix();
  12494. if (!this._frustumPlanes) {
  12495. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12496. }
  12497. else {
  12498. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12499. }
  12500. this._refreshFrustumPlanes = false;
  12501. };
  12502. Camera.prototype.isInFrustum = function (target) {
  12503. this.updateFrustumPlanes();
  12504. return target.isInFrustum(this._frustumPlanes);
  12505. };
  12506. Camera.prototype.isCompletelyInFrustum = function (target) {
  12507. this.updateFrustumPlanes();
  12508. return target.isCompletelyInFrustum(this._frustumPlanes);
  12509. };
  12510. Camera.prototype.dispose = function () {
  12511. // Animations
  12512. this.getScene().stopAnimation(this);
  12513. // Remove from scene
  12514. this.getScene().removeCamera(this);
  12515. while (this._rigCameras.length > 0) {
  12516. this._rigCameras.pop().dispose();
  12517. }
  12518. // Postprocesses
  12519. for (var i = 0; i < this._postProcesses.length; ++i) {
  12520. this._postProcesses[i].dispose(this);
  12521. }
  12522. _super.prototype.dispose.call(this);
  12523. };
  12524. // ---- Camera rigs section ----
  12525. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  12526. while (this._rigCameras.length > 0) {
  12527. this._rigCameras.pop().dispose();
  12528. }
  12529. this.cameraRigMode = mode;
  12530. this._cameraRigParams = {};
  12531. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  12532. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  12533. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  12534. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  12535. // create the rig cameras, unless none
  12536. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12537. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  12538. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  12539. }
  12540. switch (this.cameraRigMode) {
  12541. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12542. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12543. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  12544. break;
  12545. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12546. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12547. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12548. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12549. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12550. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  12551. break;
  12552. case Camera.RIG_MODE_VR:
  12553. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  12554. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  12555. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  12556. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12557. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  12558. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  12559. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  12560. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  12561. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  12562. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12563. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  12564. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  12565. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  12566. if (metrics.compensateDistortion) {
  12567. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  12568. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  12569. }
  12570. break;
  12571. }
  12572. this._cascadePostProcessesToRigCams();
  12573. this.
  12574. update();
  12575. };
  12576. Camera.prototype._getVRProjectionMatrix = function () {
  12577. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  12578. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  12579. return this._projectionMatrix;
  12580. };
  12581. Camera.prototype.setCameraRigParameter = function (name, value) {
  12582. if (!this._cameraRigParams) {
  12583. this._cameraRigParams = {};
  12584. }
  12585. this._cameraRigParams[name] = value;
  12586. //provisionnally:
  12587. if (name === "interaxialDistance") {
  12588. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  12589. }
  12590. };
  12591. /**
  12592. * needs to be overridden by children so sub has required properties to be copied
  12593. */
  12594. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  12595. return null;
  12596. };
  12597. /**
  12598. * May need to be overridden by children
  12599. */
  12600. Camera.prototype._updateRigCameras = function () {
  12601. for (var i = 0; i < this._rigCameras.length; i++) {
  12602. this._rigCameras[i].minZ = this.minZ;
  12603. this._rigCameras[i].maxZ = this.maxZ;
  12604. this._rigCameras[i].fov = this.fov;
  12605. }
  12606. // only update viewport when ANAGLYPH
  12607. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  12608. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  12609. }
  12610. };
  12611. Camera.prototype._setupInputs = function () {
  12612. };
  12613. Camera.prototype.serialize = function () {
  12614. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  12615. // Type
  12616. serializationObject.type = this.getTypeName();
  12617. // Parent
  12618. if (this.parent) {
  12619. serializationObject.parentId = this.parent.id;
  12620. }
  12621. if (this.inputs) {
  12622. this.inputs.serialize(serializationObject);
  12623. }
  12624. // Animations
  12625. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  12626. serializationObject.ranges = this.serializeAnimationRanges();
  12627. return serializationObject;
  12628. };
  12629. Camera.prototype.getTypeName = function () {
  12630. return "Camera";
  12631. };
  12632. Camera.prototype.clone = function (name) {
  12633. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  12634. };
  12635. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  12636. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  12637. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  12638. switch (type) {
  12639. case "ArcRotateCamera":
  12640. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  12641. case "DeviceOrientationCamera":
  12642. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  12643. case "FollowCamera":
  12644. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  12645. case "ArcFollowCamera":
  12646. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  12647. case "GamepadCamera":
  12648. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  12649. case "TouchCamera":
  12650. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  12651. case "VirtualJoysticksCamera":
  12652. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  12653. case "WebVRFreeCamera":
  12654. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  12655. case "VRDeviceOrientationFreeCamera":
  12656. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  12657. case "AnaglyphArcRotateCamera":
  12658. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12659. case "AnaglyphFreeCamera":
  12660. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12661. case "AnaglyphGamepadCamera":
  12662. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12663. case "AnaglyphUniversalCamera":
  12664. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12665. case "StereoscopicArcRotateCamera":
  12666. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12667. case "StereoscopicFreeCamera":
  12668. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12669. case "StereoscopicGamepadCamera":
  12670. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12671. case "StereoscopicUniversalCamera":
  12672. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12673. case "FreeCamera":
  12674. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  12675. default:
  12676. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  12677. }
  12678. };
  12679. Camera.Parse = function (parsedCamera, scene) {
  12680. var type = parsedCamera.type;
  12681. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  12682. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  12683. // Parent
  12684. if (parsedCamera.parentId) {
  12685. camera._waitingParentId = parsedCamera.parentId;
  12686. }
  12687. //If camera has an input manager, let it parse inputs settings
  12688. if (camera.inputs) {
  12689. camera.inputs.parse(parsedCamera);
  12690. camera._setupInputs();
  12691. }
  12692. // Target
  12693. if (parsedCamera.target) {
  12694. if (camera.setTarget) {
  12695. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  12696. }
  12697. }
  12698. // Apply 3d rig, when found
  12699. if (parsedCamera.cameraRigMode) {
  12700. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  12701. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  12702. }
  12703. // Animations
  12704. if (parsedCamera.animations) {
  12705. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  12706. var parsedAnimation = parsedCamera.animations[animationIndex];
  12707. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  12708. }
  12709. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  12710. }
  12711. if (parsedCamera.autoAnimate) {
  12712. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  12713. }
  12714. return camera;
  12715. };
  12716. // Statics
  12717. Camera._PERSPECTIVE_CAMERA = 0;
  12718. Camera._ORTHOGRAPHIC_CAMERA = 1;
  12719. Camera._FOVMODE_VERTICAL_FIXED = 0;
  12720. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  12721. Camera._RIG_MODE_NONE = 0;
  12722. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  12723. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  12724. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  12725. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  12726. Camera._RIG_MODE_VR = 20;
  12727. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  12728. __decorate([
  12729. BABYLON.serializeAsVector3()
  12730. ], Camera.prototype, "position", void 0);
  12731. __decorate([
  12732. BABYLON.serializeAsVector3()
  12733. ], Camera.prototype, "upVector", void 0);
  12734. __decorate([
  12735. BABYLON.serialize()
  12736. ], Camera.prototype, "orthoLeft", void 0);
  12737. __decorate([
  12738. BABYLON.serialize()
  12739. ], Camera.prototype, "orthoRight", void 0);
  12740. __decorate([
  12741. BABYLON.serialize()
  12742. ], Camera.prototype, "orthoBottom", void 0);
  12743. __decorate([
  12744. BABYLON.serialize()
  12745. ], Camera.prototype, "orthoTop", void 0);
  12746. __decorate([
  12747. BABYLON.serialize()
  12748. ], Camera.prototype, "fov", void 0);
  12749. __decorate([
  12750. BABYLON.serialize()
  12751. ], Camera.prototype, "minZ", void 0);
  12752. __decorate([
  12753. BABYLON.serialize()
  12754. ], Camera.prototype, "maxZ", void 0);
  12755. __decorate([
  12756. BABYLON.serialize()
  12757. ], Camera.prototype, "inertia", void 0);
  12758. __decorate([
  12759. BABYLON.serialize()
  12760. ], Camera.prototype, "mode", void 0);
  12761. __decorate([
  12762. BABYLON.serialize()
  12763. ], Camera.prototype, "layerMask", void 0);
  12764. __decorate([
  12765. BABYLON.serialize()
  12766. ], Camera.prototype, "fovMode", void 0);
  12767. __decorate([
  12768. BABYLON.serialize()
  12769. ], Camera.prototype, "cameraRigMode", void 0);
  12770. __decorate([
  12771. BABYLON.serialize()
  12772. ], Camera.prototype, "interaxialDistance", void 0);
  12773. __decorate([
  12774. BABYLON.serialize()
  12775. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  12776. return Camera;
  12777. })(BABYLON.Node);
  12778. BABYLON.Camera = Camera;
  12779. })(BABYLON || (BABYLON = {}));
  12780. var BABYLON;
  12781. (function (BABYLON) {
  12782. BABYLON.CameraInputTypes = {};
  12783. var CameraInputsManager = (function () {
  12784. function CameraInputsManager(camera) {
  12785. this.attached = {};
  12786. this.camera = camera;
  12787. this.checkInputs = function () { };
  12788. }
  12789. CameraInputsManager.prototype.add = function (input) {
  12790. var type = input.getSimpleName();
  12791. if (this.attached[type]) {
  12792. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  12793. return;
  12794. }
  12795. this.attached[type] = input;
  12796. input.camera = this.camera;
  12797. //for checkInputs, we are dynamically creating a function
  12798. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  12799. if (input.checkInputs) {
  12800. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12801. }
  12802. if (this.attachedElement) {
  12803. input.attachControl(this.attachedElement);
  12804. }
  12805. };
  12806. CameraInputsManager.prototype.remove = function (inputToRemove) {
  12807. for (var cam in this.attached) {
  12808. var input = this.attached[cam];
  12809. if (input === inputToRemove) {
  12810. input.detachControl(this.attachedElement);
  12811. delete this.attached[cam];
  12812. this.rebuildInputCheck();
  12813. }
  12814. }
  12815. };
  12816. CameraInputsManager.prototype.removeByType = function (inputType) {
  12817. for (var cam in this.attached) {
  12818. var input = this.attached[cam];
  12819. if (input.getTypeName() === inputType) {
  12820. input.detachControl(this.attachedElement);
  12821. delete this.attached[cam];
  12822. this.rebuildInputCheck();
  12823. }
  12824. }
  12825. };
  12826. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  12827. var current = this.checkInputs;
  12828. return function () {
  12829. current();
  12830. fn();
  12831. };
  12832. };
  12833. CameraInputsManager.prototype.attachInput = function (input) {
  12834. input.attachControl(this.attachedElement, this.noPreventDefault);
  12835. };
  12836. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  12837. if (this.attachedElement) {
  12838. return;
  12839. }
  12840. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  12841. this.attachedElement = element;
  12842. this.noPreventDefault = noPreventDefault;
  12843. for (var cam in this.attached) {
  12844. var input = this.attached[cam];
  12845. this.attached[cam].attachControl(element, noPreventDefault);
  12846. }
  12847. };
  12848. CameraInputsManager.prototype.detachElement = function (element) {
  12849. if (this.attachedElement !== element) {
  12850. return;
  12851. }
  12852. for (var cam in this.attached) {
  12853. var input = this.attached[cam];
  12854. this.attached[cam].detachControl(element);
  12855. }
  12856. this.attachedElement = null;
  12857. };
  12858. CameraInputsManager.prototype.rebuildInputCheck = function () {
  12859. this.checkInputs = function () { };
  12860. for (var cam in this.attached) {
  12861. var input = this.attached[cam];
  12862. if (input.checkInputs) {
  12863. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12864. }
  12865. }
  12866. };
  12867. CameraInputsManager.prototype.clear = function () {
  12868. if (this.attachedElement) {
  12869. this.detachElement(this.attachedElement);
  12870. }
  12871. this.attached = {};
  12872. this.attachedElement = null;
  12873. this.checkInputs = function () { };
  12874. };
  12875. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  12876. var inputs = {};
  12877. for (var cam in this.attached) {
  12878. var input = this.attached[cam];
  12879. var res = BABYLON.SerializationHelper.Serialize(input);
  12880. inputs[input.getTypeName()] = res;
  12881. }
  12882. serializedCamera.inputsmgr = inputs;
  12883. };
  12884. CameraInputsManager.prototype.parse = function (parsedCamera) {
  12885. var parsedInputs = parsedCamera.inputsmgr;
  12886. if (parsedInputs) {
  12887. this.clear();
  12888. for (var n in parsedInputs) {
  12889. var construct = BABYLON.CameraInputTypes[n];
  12890. if (construct) {
  12891. var parsedinput = parsedInputs[n];
  12892. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  12893. this.add(input);
  12894. }
  12895. }
  12896. }
  12897. else {
  12898. //2016-03-08 this part is for managing backward compatibility
  12899. for (var n in this.attached) {
  12900. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  12901. if (construct) {
  12902. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  12903. this.remove(this.attached[n]);
  12904. this.add(input);
  12905. }
  12906. }
  12907. }
  12908. };
  12909. return CameraInputsManager;
  12910. })();
  12911. BABYLON.CameraInputsManager = CameraInputsManager;
  12912. })(BABYLON || (BABYLON = {}));
  12913. var BABYLON;
  12914. (function (BABYLON) {
  12915. var FreeCameraMouseInput = (function () {
  12916. function FreeCameraMouseInput(touchEnabled) {
  12917. if (touchEnabled === void 0) { touchEnabled = true; }
  12918. this.touchEnabled = touchEnabled;
  12919. this.angularSensibility = 2000.0;
  12920. }
  12921. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  12922. var _this = this;
  12923. if (!this._pointerInput) {
  12924. var camera = this.camera;
  12925. var engine = this.camera.getEngine();
  12926. this._pointerInput = function (p, s) {
  12927. var evt = p.event;
  12928. if (!_this.touchEnabled && evt.pointerType === "touch") {
  12929. return;
  12930. }
  12931. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12932. try {
  12933. evt.srcElement.setPointerCapture(evt.pointerId);
  12934. }
  12935. catch (e) {
  12936. }
  12937. _this.previousPosition = {
  12938. x: evt.clientX,
  12939. y: evt.clientY
  12940. };
  12941. if (!noPreventDefault) {
  12942. evt.preventDefault();
  12943. element.focus();
  12944. }
  12945. }
  12946. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12947. try {
  12948. evt.srcElement.releasePointerCapture(evt.pointerId);
  12949. }
  12950. catch (e) {
  12951. }
  12952. _this.previousPosition = null;
  12953. if (!noPreventDefault) {
  12954. evt.preventDefault();
  12955. }
  12956. }
  12957. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12958. if (!_this.previousPosition && !engine.isPointerLock) {
  12959. return;
  12960. }
  12961. var offsetX;
  12962. var offsetY;
  12963. if (!engine.isPointerLock) {
  12964. offsetX = evt.clientX - _this.previousPosition.x;
  12965. offsetY = evt.clientY - _this.previousPosition.y;
  12966. }
  12967. else {
  12968. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12969. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12970. }
  12971. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  12972. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  12973. _this.previousPosition = {
  12974. x: evt.clientX,
  12975. y: evt.clientY
  12976. };
  12977. if (!noPreventDefault) {
  12978. evt.preventDefault();
  12979. }
  12980. }
  12981. };
  12982. }
  12983. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12984. };
  12985. FreeCameraMouseInput.prototype.detachControl = function (element) {
  12986. if (this._observer && element) {
  12987. this.camera.getScene().onPointerObservable.remove(this._observer);
  12988. this._observer = null;
  12989. this.previousPosition = null;
  12990. }
  12991. };
  12992. FreeCameraMouseInput.prototype.getTypeName = function () {
  12993. return "FreeCameraMouseInput";
  12994. };
  12995. FreeCameraMouseInput.prototype.getSimpleName = function () {
  12996. return "mouse";
  12997. };
  12998. __decorate([
  12999. BABYLON.serialize()
  13000. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  13001. return FreeCameraMouseInput;
  13002. })();
  13003. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  13004. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  13005. })(BABYLON || (BABYLON = {}));
  13006. var BABYLON;
  13007. (function (BABYLON) {
  13008. var FreeCameraKeyboardMoveInput = (function () {
  13009. function FreeCameraKeyboardMoveInput() {
  13010. this._keys = [];
  13011. this.keysUp = [38];
  13012. this.keysDown = [40];
  13013. this.keysLeft = [37];
  13014. this.keysRight = [39];
  13015. }
  13016. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13017. var _this = this;
  13018. if (!this._onKeyDown) {
  13019. element.tabIndex = 1;
  13020. this._onKeyDown = function (evt) {
  13021. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13022. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13023. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13024. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13025. var index = _this._keys.indexOf(evt.keyCode);
  13026. if (index === -1) {
  13027. _this._keys.push(evt.keyCode);
  13028. }
  13029. if (!noPreventDefault) {
  13030. evt.preventDefault();
  13031. }
  13032. }
  13033. };
  13034. this._onKeyUp = function (evt) {
  13035. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13036. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13037. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13038. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13039. var index = _this._keys.indexOf(evt.keyCode);
  13040. if (index >= 0) {
  13041. _this._keys.splice(index, 1);
  13042. }
  13043. if (!noPreventDefault) {
  13044. evt.preventDefault();
  13045. }
  13046. }
  13047. };
  13048. element.addEventListener("keydown", this._onKeyDown, false);
  13049. element.addEventListener("keyup", this._onKeyUp, false);
  13050. BABYLON.Tools.RegisterTopRootEvents([
  13051. { name: "blur", handler: this._onLostFocus }
  13052. ]);
  13053. }
  13054. };
  13055. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13056. if (this._onKeyDown) {
  13057. element.removeEventListener("keydown", this._onKeyDown);
  13058. element.removeEventListener("keyup", this._onKeyUp);
  13059. BABYLON.Tools.UnregisterTopRootEvents([
  13060. { name: "blur", handler: this._onLostFocus }
  13061. ]);
  13062. this._keys = [];
  13063. this._onKeyDown = null;
  13064. this._onKeyUp = null;
  13065. }
  13066. };
  13067. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13068. if (this._onKeyDown) {
  13069. var camera = this.camera;
  13070. // Keyboard
  13071. for (var index = 0; index < this._keys.length; index++) {
  13072. var keyCode = this._keys[index];
  13073. var speed = camera._computeLocalCameraSpeed();
  13074. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13075. camera._localDirection.copyFromFloats(-speed, 0, 0);
  13076. }
  13077. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13078. camera._localDirection.copyFromFloats(0, 0, speed);
  13079. }
  13080. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13081. camera._localDirection.copyFromFloats(speed, 0, 0);
  13082. }
  13083. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13084. camera._localDirection.copyFromFloats(0, 0, -speed);
  13085. }
  13086. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  13087. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  13088. camera.cameraDirection.addInPlace(camera._transformedDirection);
  13089. }
  13090. }
  13091. };
  13092. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13093. return "FreeCameraKeyboardMoveInput";
  13094. };
  13095. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  13096. this._keys = [];
  13097. };
  13098. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13099. return "keyboard";
  13100. };
  13101. __decorate([
  13102. BABYLON.serialize()
  13103. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13104. __decorate([
  13105. BABYLON.serialize()
  13106. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13107. __decorate([
  13108. BABYLON.serialize()
  13109. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13110. __decorate([
  13111. BABYLON.serialize()
  13112. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13113. return FreeCameraKeyboardMoveInput;
  13114. })();
  13115. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  13116. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  13117. })(BABYLON || (BABYLON = {}));
  13118. var BABYLON;
  13119. (function (BABYLON) {
  13120. var FreeCameraTouchInput = (function () {
  13121. function FreeCameraTouchInput() {
  13122. this._offsetX = null;
  13123. this._offsetY = null;
  13124. this._pointerCount = 0;
  13125. this._pointerPressed = [];
  13126. this.touchAngularSensibility = 200000.0;
  13127. this.touchMoveSensibility = 250.0;
  13128. }
  13129. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  13130. var _this = this;
  13131. var previousPosition;
  13132. if (this._pointerInput === undefined) {
  13133. this._onLostFocus = function (evt) {
  13134. _this._offsetX = null;
  13135. _this._offsetY = null;
  13136. };
  13137. this._pointerInput = function (p, s) {
  13138. var evt = p.event;
  13139. if (evt.pointerType === "mouse") {
  13140. return;
  13141. }
  13142. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13143. if (!noPreventDefault) {
  13144. evt.preventDefault();
  13145. }
  13146. _this._pointerPressed.push(evt.pointerId);
  13147. if (_this._pointerPressed.length !== 1) {
  13148. return;
  13149. }
  13150. previousPosition = {
  13151. x: evt.clientX,
  13152. y: evt.clientY
  13153. };
  13154. }
  13155. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13156. if (!noPreventDefault) {
  13157. evt.preventDefault();
  13158. }
  13159. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13160. if (index === -1) {
  13161. return;
  13162. }
  13163. _this._pointerPressed.splice(index, 1);
  13164. if (index != 0) {
  13165. return;
  13166. }
  13167. previousPosition = null;
  13168. _this._offsetX = null;
  13169. _this._offsetY = null;
  13170. }
  13171. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13172. if (!noPreventDefault) {
  13173. evt.preventDefault();
  13174. }
  13175. if (!previousPosition) {
  13176. return;
  13177. }
  13178. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13179. if (index != 0) {
  13180. return;
  13181. }
  13182. _this._offsetX = evt.clientX - previousPosition.x;
  13183. _this._offsetY = -(evt.clientY - previousPosition.y);
  13184. }
  13185. };
  13186. }
  13187. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13188. element.addEventListener("blur", this._onLostFocus);
  13189. };
  13190. FreeCameraTouchInput.prototype.detachControl = function (element) {
  13191. if (this._pointerInput && element) {
  13192. this.camera.getScene().onPointerObservable.remove(this._observer);
  13193. this._observer = null;
  13194. element.removeEventListener("blur", this._onLostFocus);
  13195. this._onLostFocus = null;
  13196. this._pointerPressed = [];
  13197. this._offsetX = null;
  13198. this._offsetY = null;
  13199. this._pointerCount = 0;
  13200. }
  13201. };
  13202. FreeCameraTouchInput.prototype.checkInputs = function () {
  13203. if (this._offsetX) {
  13204. var camera = this.camera;
  13205. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  13206. if (this._pointerPressed.length > 1) {
  13207. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  13208. }
  13209. else {
  13210. var speed = camera._computeLocalCameraSpeed();
  13211. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  13212. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  13213. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  13214. }
  13215. }
  13216. };
  13217. FreeCameraTouchInput.prototype.getTypeName = function () {
  13218. return "FreeCameraTouchInput";
  13219. };
  13220. FreeCameraTouchInput.prototype.getSimpleName = function () {
  13221. return "touch";
  13222. };
  13223. __decorate([
  13224. BABYLON.serialize()
  13225. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  13226. __decorate([
  13227. BABYLON.serialize()
  13228. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  13229. return FreeCameraTouchInput;
  13230. })();
  13231. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  13232. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  13233. })(BABYLON || (BABYLON = {}));
  13234. var BABYLON;
  13235. (function (BABYLON) {
  13236. var FreeCameraDeviceOrientationInput = (function () {
  13237. function FreeCameraDeviceOrientationInput() {
  13238. var _this = this;
  13239. this._screenOrientationAngle = 0;
  13240. this._screenQuaternion = new BABYLON.Quaternion();
  13241. this._alpha = 0;
  13242. this._beta = 0;
  13243. this._gamma = 0;
  13244. this._orientationChanged = function () {
  13245. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  13246. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  13247. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  13248. };
  13249. this._deviceOrientation = function (evt) {
  13250. _this._alpha = evt.alpha;
  13251. _this._beta = evt.beta;
  13252. _this._gamma = evt.gamma;
  13253. };
  13254. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  13255. this._orientationChanged();
  13256. }
  13257. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  13258. get: function () {
  13259. return this._camera;
  13260. },
  13261. set: function (camera) {
  13262. this._camera = camera;
  13263. if (!this._camera.rotationQuaternion)
  13264. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  13265. },
  13266. enumerable: true,
  13267. configurable: true
  13268. });
  13269. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13270. window.addEventListener("orientationchange", this._orientationChanged);
  13271. window.addEventListener("deviceorientation", this._deviceOrientation);
  13272. };
  13273. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  13274. window.removeEventListener("orientationchange", this._orientationChanged);
  13275. window.removeEventListener("deviceorientation", this._deviceOrientation);
  13276. };
  13277. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  13278. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  13279. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  13280. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  13281. //Mirror on XY Plane
  13282. this._camera.rotationQuaternion.z *= -1;
  13283. this._camera.rotationQuaternion.w *= -1;
  13284. };
  13285. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  13286. return "FreeCameraDeviceOrientationInput";
  13287. };
  13288. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  13289. return "deviceOrientation";
  13290. };
  13291. return FreeCameraDeviceOrientationInput;
  13292. })();
  13293. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  13294. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  13295. })(BABYLON || (BABYLON = {}));
  13296. var BABYLON;
  13297. (function (BABYLON) {
  13298. var FreeCameraGamepadInput = (function () {
  13299. function FreeCameraGamepadInput() {
  13300. this.gamepadAngularSensibility = 200;
  13301. this.gamepadMoveSensibility = 40;
  13302. }
  13303. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13304. var _this = this;
  13305. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13306. };
  13307. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  13308. if (this._gamepads) {
  13309. this._gamepads.dispose();
  13310. }
  13311. this.gamepad = null;
  13312. };
  13313. FreeCameraGamepadInput.prototype.checkInputs = function () {
  13314. if (this.gamepad) {
  13315. var camera = this.camera;
  13316. var LSValues = this.gamepad.leftStick;
  13317. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  13318. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13319. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  13320. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  13321. var RSValues = this.gamepad.rightStick;
  13322. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  13323. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  13324. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  13325. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  13326. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  13327. var speed = camera._computeLocalCameraSpeed() * 50.0;
  13328. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  13329. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  13330. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  13331. }
  13332. };
  13333. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13334. // Only the first gamepad can control the camera
  13335. if (gamepad.index === 0) {
  13336. this.gamepad = gamepad;
  13337. }
  13338. };
  13339. FreeCameraGamepadInput.prototype.getTypeName = function () {
  13340. return "FreeCameraGamepadInput";
  13341. };
  13342. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  13343. return "gamepad";
  13344. };
  13345. __decorate([
  13346. BABYLON.serialize()
  13347. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  13348. __decorate([
  13349. BABYLON.serialize()
  13350. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13351. return FreeCameraGamepadInput;
  13352. })();
  13353. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  13354. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  13355. })(BABYLON || (BABYLON = {}));
  13356. var BABYLON;
  13357. (function (BABYLON) {
  13358. var ArcRotateCameraKeyboardMoveInput = (function () {
  13359. function ArcRotateCameraKeyboardMoveInput() {
  13360. this._keys = [];
  13361. this.keysUp = [38];
  13362. this.keysDown = [40];
  13363. this.keysLeft = [37];
  13364. this.keysRight = [39];
  13365. }
  13366. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13367. var _this = this;
  13368. element.tabIndex = 1;
  13369. this._onKeyDown = function (evt) {
  13370. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13371. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13372. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13373. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13374. var index = _this._keys.indexOf(evt.keyCode);
  13375. if (index === -1) {
  13376. _this._keys.push(evt.keyCode);
  13377. }
  13378. if (evt.preventDefault) {
  13379. if (!noPreventDefault) {
  13380. evt.preventDefault();
  13381. }
  13382. }
  13383. }
  13384. };
  13385. this._onKeyUp = function (evt) {
  13386. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13387. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13388. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13389. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13390. var index = _this._keys.indexOf(evt.keyCode);
  13391. if (index >= 0) {
  13392. _this._keys.splice(index, 1);
  13393. }
  13394. if (evt.preventDefault) {
  13395. if (!noPreventDefault) {
  13396. evt.preventDefault();
  13397. }
  13398. }
  13399. }
  13400. };
  13401. this._onLostFocus = function () {
  13402. _this._keys = [];
  13403. };
  13404. element.addEventListener("keydown", this._onKeyDown, false);
  13405. element.addEventListener("keyup", this._onKeyUp, false);
  13406. BABYLON.Tools.RegisterTopRootEvents([
  13407. { name: "blur", handler: this._onLostFocus }
  13408. ]);
  13409. };
  13410. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13411. if (element) {
  13412. element.removeEventListener("keydown", this._onKeyDown);
  13413. element.removeEventListener("keyup", this._onKeyUp);
  13414. }
  13415. BABYLON.Tools.UnregisterTopRootEvents([
  13416. { name: "blur", handler: this._onLostFocus }
  13417. ]);
  13418. this._keys = [];
  13419. this._onKeyDown = null;
  13420. this._onKeyUp = null;
  13421. this._onLostFocus = null;
  13422. };
  13423. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13424. if (this._onKeyDown) {
  13425. var camera = this.camera;
  13426. for (var index = 0; index < this._keys.length; index++) {
  13427. var keyCode = this._keys[index];
  13428. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13429. camera.inertialAlphaOffset -= 0.01;
  13430. }
  13431. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13432. camera.inertialBetaOffset -= 0.01;
  13433. }
  13434. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13435. camera.inertialAlphaOffset += 0.01;
  13436. }
  13437. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13438. camera.inertialBetaOffset += 0.01;
  13439. }
  13440. }
  13441. }
  13442. };
  13443. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13444. return "ArcRotateCameraKeyboardMoveInput";
  13445. };
  13446. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13447. return "keyboard";
  13448. };
  13449. __decorate([
  13450. BABYLON.serialize()
  13451. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13452. __decorate([
  13453. BABYLON.serialize()
  13454. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13455. __decorate([
  13456. BABYLON.serialize()
  13457. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13458. __decorate([
  13459. BABYLON.serialize()
  13460. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13461. return ArcRotateCameraKeyboardMoveInput;
  13462. })();
  13463. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  13464. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  13465. })(BABYLON || (BABYLON = {}));
  13466. var BABYLON;
  13467. (function (BABYLON) {
  13468. var ArcRotateCameraMouseWheelInput = (function () {
  13469. function ArcRotateCameraMouseWheelInput() {
  13470. this.wheelPrecision = 3.0;
  13471. }
  13472. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  13473. var _this = this;
  13474. this._wheel = function (p, s) {
  13475. //sanity check - this should be a PointerWheel event.
  13476. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  13477. return;
  13478. var event = p.event;
  13479. var delta = 0;
  13480. if (event.wheelDelta) {
  13481. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  13482. }
  13483. else if (event.detail) {
  13484. delta = -event.detail / _this.wheelPrecision;
  13485. }
  13486. if (delta)
  13487. _this.camera.inertialRadiusOffset += delta;
  13488. if (event.preventDefault) {
  13489. if (!noPreventDefault) {
  13490. event.preventDefault();
  13491. }
  13492. }
  13493. };
  13494. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  13495. };
  13496. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  13497. if (this._observer && element) {
  13498. this.camera.getScene().onPointerObservable.remove(this._observer);
  13499. this._observer = null;
  13500. this._wheel = null;
  13501. }
  13502. };
  13503. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  13504. return "ArcRotateCameraMouseWheelInput";
  13505. };
  13506. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  13507. return "mousewheel";
  13508. };
  13509. __decorate([
  13510. BABYLON.serialize()
  13511. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  13512. return ArcRotateCameraMouseWheelInput;
  13513. })();
  13514. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  13515. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  13516. })(BABYLON || (BABYLON = {}));
  13517. var BABYLON;
  13518. (function (BABYLON) {
  13519. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13520. var ArcRotateCameraPointersInput = (function () {
  13521. function ArcRotateCameraPointersInput() {
  13522. this.angularSensibilityX = 1000.0;
  13523. this.angularSensibilityY = 1000.0;
  13524. this.pinchPrecision = 6.0;
  13525. this.panningSensibility = 50.0;
  13526. this._isPanClick = false;
  13527. this.pinchInwards = true;
  13528. }
  13529. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  13530. var _this = this;
  13531. var engine = this.camera.getEngine();
  13532. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  13533. var pointA, pointB;
  13534. var previousPinchDistance = 0;
  13535. this._pointerInput = function (p, s) {
  13536. var evt = p.event;
  13537. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13538. try {
  13539. evt.srcElement.setPointerCapture(evt.pointerId);
  13540. }
  13541. catch (e) {
  13542. }
  13543. // Manage panning with pan button click
  13544. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  13545. // manage pointers
  13546. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  13547. if (pointA === undefined) {
  13548. pointA = cacheSoloPointer;
  13549. }
  13550. else if (pointB === undefined) {
  13551. pointB = cacheSoloPointer;
  13552. }
  13553. if (!noPreventDefault) {
  13554. evt.preventDefault();
  13555. element.focus();
  13556. }
  13557. }
  13558. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13559. try {
  13560. evt.srcElement.releasePointerCapture(evt.pointerId);
  13561. }
  13562. catch (e) {
  13563. }
  13564. cacheSoloPointer = null;
  13565. previousPinchDistance = 0;
  13566. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  13567. //but emptying completly pointers collection is required to fix a bug on iPhone :
  13568. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  13569. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  13570. pointA = pointB = undefined;
  13571. if (!noPreventDefault) {
  13572. evt.preventDefault();
  13573. }
  13574. }
  13575. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13576. if (!noPreventDefault) {
  13577. evt.preventDefault();
  13578. }
  13579. // One button down
  13580. if (pointA && pointB === undefined) {
  13581. if (_this.panningSensibility !== 0 &&
  13582. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  13583. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  13584. _this.camera
  13585. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  13586. _this.camera
  13587. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  13588. }
  13589. else {
  13590. var offsetX = evt.clientX - cacheSoloPointer.x;
  13591. var offsetY = evt.clientY - cacheSoloPointer.y;
  13592. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  13593. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  13594. }
  13595. cacheSoloPointer.x = evt.clientX;
  13596. cacheSoloPointer.y = evt.clientY;
  13597. }
  13598. else if (pointA && pointB) {
  13599. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  13600. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  13601. ed.x = evt.clientX;
  13602. ed.y = evt.clientY;
  13603. var direction = _this.pinchInwards ? 1 : -1;
  13604. var distX = pointA.x - pointB.x;
  13605. var distY = pointA.y - pointB.y;
  13606. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  13607. if (previousPinchDistance === 0) {
  13608. previousPinchDistance = pinchSquaredDistance;
  13609. return;
  13610. }
  13611. if (pinchSquaredDistance !== previousPinchDistance) {
  13612. _this.camera
  13613. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  13614. (_this.pinchPrecision *
  13615. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  13616. direction);
  13617. previousPinchDistance = pinchSquaredDistance;
  13618. }
  13619. }
  13620. }
  13621. };
  13622. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13623. this._onContextMenu = function (evt) {
  13624. evt.preventDefault();
  13625. };
  13626. if (!this.camera._useCtrlForPanning) {
  13627. element.addEventListener("contextmenu", this._onContextMenu, false);
  13628. }
  13629. this._onLostFocus = function () {
  13630. //this._keys = [];
  13631. pointA = pointB = undefined;
  13632. previousPinchDistance = 0;
  13633. cacheSoloPointer = null;
  13634. };
  13635. this._onMouseMove = function (evt) {
  13636. if (!engine.isPointerLock) {
  13637. return;
  13638. }
  13639. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13640. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13641. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  13642. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  13643. if (!noPreventDefault) {
  13644. evt.preventDefault();
  13645. }
  13646. };
  13647. this._onGestureStart = function (e) {
  13648. if (window.MSGesture === undefined) {
  13649. return;
  13650. }
  13651. if (!_this._MSGestureHandler) {
  13652. _this._MSGestureHandler = new MSGesture();
  13653. _this._MSGestureHandler.target = element;
  13654. }
  13655. _this._MSGestureHandler.addPointer(e.pointerId);
  13656. };
  13657. this._onGesture = function (e) {
  13658. _this.camera.radius *= e.scale;
  13659. if (e.preventDefault) {
  13660. if (!noPreventDefault) {
  13661. e.stopPropagation();
  13662. e.preventDefault();
  13663. }
  13664. }
  13665. };
  13666. element.addEventListener("mousemove", this._onMouseMove, false);
  13667. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  13668. element.addEventListener("MSGestureChange", this._onGesture, false);
  13669. element.addEventListener("keydown", this._onKeyDown, false);
  13670. element.addEventListener("keyup", this._onKeyUp, false);
  13671. BABYLON.Tools.RegisterTopRootEvents([
  13672. { name: "blur", handler: this._onLostFocus }
  13673. ]);
  13674. };
  13675. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  13676. if (element && this._observer) {
  13677. this.camera.getScene().onPointerObservable.remove(this._observer);
  13678. this._observer = null;
  13679. element.removeEventListener("contextmenu", this._onContextMenu);
  13680. element.removeEventListener("mousemove", this._onMouseMove);
  13681. element.removeEventListener("MSPointerDown", this._onGestureStart);
  13682. element.removeEventListener("MSGestureChange", this._onGesture);
  13683. element.removeEventListener("keydown", this._onKeyDown);
  13684. element.removeEventListener("keyup", this._onKeyUp);
  13685. this._isPanClick = false;
  13686. this.pinchInwards = true;
  13687. this._onKeyDown = null;
  13688. this._onKeyUp = null;
  13689. this._onMouseMove = null;
  13690. this._onGestureStart = null;
  13691. this._onGesture = null;
  13692. this._MSGestureHandler = null;
  13693. this._onLostFocus = null;
  13694. this._onContextMenu = null;
  13695. }
  13696. BABYLON.Tools.UnregisterTopRootEvents([
  13697. { name: "blur", handler: this._onLostFocus }
  13698. ]);
  13699. };
  13700. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  13701. return "ArcRotateCameraPointersInput";
  13702. };
  13703. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  13704. return "pointers";
  13705. };
  13706. __decorate([
  13707. BABYLON.serialize()
  13708. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  13709. __decorate([
  13710. BABYLON.serialize()
  13711. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  13712. __decorate([
  13713. BABYLON.serialize()
  13714. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  13715. __decorate([
  13716. BABYLON.serialize()
  13717. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  13718. return ArcRotateCameraPointersInput;
  13719. })();
  13720. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  13721. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  13722. })(BABYLON || (BABYLON = {}));
  13723. var BABYLON;
  13724. (function (BABYLON) {
  13725. var ArcRotateCameraGamepadInput = (function () {
  13726. function ArcRotateCameraGamepadInput() {
  13727. this.gamepadRotationSensibility = 80;
  13728. this.gamepadMoveSensibility = 40;
  13729. }
  13730. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13731. var _this = this;
  13732. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13733. };
  13734. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  13735. if (this._gamepads) {
  13736. this._gamepads.dispose();
  13737. }
  13738. this.gamepad = null;
  13739. };
  13740. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  13741. if (this.gamepad) {
  13742. var camera = this.camera;
  13743. var RSValues = this.gamepad.rightStick;
  13744. if (RSValues.x != 0) {
  13745. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  13746. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  13747. camera.inertialAlphaOffset += normalizedRX;
  13748. }
  13749. }
  13750. if (RSValues.y != 0) {
  13751. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  13752. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  13753. camera.inertialBetaOffset += normalizedRY;
  13754. }
  13755. }
  13756. var LSValues = this.gamepad.leftStick;
  13757. if (LSValues.y != 0) {
  13758. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13759. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  13760. this.camera.inertialRadiusOffset -= normalizedLY;
  13761. }
  13762. }
  13763. }
  13764. };
  13765. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13766. // Only the first gamepad can control the camera
  13767. if (gamepad.index === 0) {
  13768. this.gamepad = gamepad;
  13769. }
  13770. };
  13771. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  13772. return "ArcRotateCameraGamepadInput";
  13773. };
  13774. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  13775. return "gamepad";
  13776. };
  13777. __decorate([
  13778. BABYLON.serialize()
  13779. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  13780. __decorate([
  13781. BABYLON.serialize()
  13782. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13783. return ArcRotateCameraGamepadInput;
  13784. })();
  13785. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  13786. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  13787. })(BABYLON || (BABYLON = {}));
  13788. var BABYLON;
  13789. (function (BABYLON) {
  13790. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  13791. function ArcRotateCameraVRDeviceOrientationInput() {
  13792. this.alphaCorrection = 1;
  13793. this.betaCorrection = 1;
  13794. this.gammaCorrection = 1;
  13795. this._alpha = 0;
  13796. this._beta = 0;
  13797. this._gamma = 0;
  13798. this._dirty = false;
  13799. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  13800. }
  13801. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13802. this.camera.attachControl(element, noPreventDefault);
  13803. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  13804. };
  13805. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  13806. var camera = this.camera;
  13807. this._alpha = +evt.alpha | 0;
  13808. this._beta = +evt.beta | 0;
  13809. this._gamma = +evt.gamma | 0;
  13810. this._dirty = true;
  13811. };
  13812. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  13813. if (this._dirty) {
  13814. this._dirty = false;
  13815. if (this._gamma < 0) {
  13816. this._gamma = 180 + this._gamma;
  13817. }
  13818. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  13819. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  13820. }
  13821. };
  13822. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  13823. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  13824. };
  13825. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  13826. return "ArcRotateCameraVRDeviceOrientationInput";
  13827. };
  13828. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  13829. return "VRDeviceOrientation";
  13830. };
  13831. return ArcRotateCameraVRDeviceOrientationInput;
  13832. })();
  13833. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  13834. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  13835. })(BABYLON || (BABYLON = {}));
  13836. var BABYLON;
  13837. (function (BABYLON) {
  13838. var TargetCamera = (function (_super) {
  13839. __extends(TargetCamera, _super);
  13840. function TargetCamera(name, position, scene) {
  13841. _super.call(this, name, position, scene);
  13842. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13843. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13844. this.rotation = new BABYLON.Vector3(0, 0, 0);
  13845. this.speed = 2.0;
  13846. this.noRotationConstraint = false;
  13847. this.lockedTarget = null;
  13848. this._currentTarget = BABYLON.Vector3.Zero();
  13849. this._viewMatrix = BABYLON.Matrix.Zero();
  13850. this._camMatrix = BABYLON.Matrix.Zero();
  13851. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  13852. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  13853. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  13854. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  13855. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  13856. this._lookAtTemp = BABYLON.Matrix.Zero();
  13857. this._tempMatrix = BABYLON.Matrix.Zero();
  13858. }
  13859. TargetCamera.prototype.getFrontPosition = function (distance) {
  13860. var direction = this.getTarget().subtract(this.position);
  13861. direction.normalize();
  13862. direction.scaleInPlace(distance);
  13863. return this.globalPosition.add(direction);
  13864. };
  13865. TargetCamera.prototype._getLockedTargetPosition = function () {
  13866. if (!this.lockedTarget) {
  13867. return null;
  13868. }
  13869. return this.lockedTarget.position || this.lockedTarget;
  13870. };
  13871. // Cache
  13872. TargetCamera.prototype._initCache = function () {
  13873. _super.prototype._initCache.call(this);
  13874. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13875. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13876. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13877. };
  13878. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  13879. if (!ignoreParentClass) {
  13880. _super.prototype._updateCache.call(this);
  13881. }
  13882. var lockedTargetPosition = this._getLockedTargetPosition();
  13883. if (!lockedTargetPosition) {
  13884. this._cache.lockedTarget = null;
  13885. }
  13886. else {
  13887. if (!this._cache.lockedTarget) {
  13888. this._cache.lockedTarget = lockedTargetPosition.clone();
  13889. }
  13890. else {
  13891. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  13892. }
  13893. }
  13894. this._cache.rotation.copyFrom(this.rotation);
  13895. if (this.rotationQuaternion)
  13896. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13897. };
  13898. // Synchronized
  13899. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  13900. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  13901. return false;
  13902. }
  13903. var lockedTargetPosition = this._getLockedTargetPosition();
  13904. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  13905. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  13906. };
  13907. // Methods
  13908. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  13909. var engine = this.getEngine();
  13910. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  13911. };
  13912. // Target
  13913. TargetCamera.prototype.setTarget = function (target) {
  13914. this.upVector.normalize();
  13915. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  13916. this._camMatrix.invert();
  13917. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  13918. var vDir = target.subtract(this.position);
  13919. if (vDir.x >= 0.0) {
  13920. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  13921. }
  13922. else {
  13923. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  13924. }
  13925. this.rotation.z = 0;
  13926. if (isNaN(this.rotation.x)) {
  13927. this.rotation.x = 0;
  13928. }
  13929. if (isNaN(this.rotation.y)) {
  13930. this.rotation.y = 0;
  13931. }
  13932. if (isNaN(this.rotation.z)) {
  13933. this.rotation.z = 0;
  13934. }
  13935. if (this.rotationQuaternion) {
  13936. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  13937. }
  13938. };
  13939. TargetCamera.prototype.getTarget = function () {
  13940. return this._currentTarget;
  13941. };
  13942. TargetCamera.prototype._decideIfNeedsToMove = function () {
  13943. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13944. };
  13945. TargetCamera.prototype._updatePosition = function () {
  13946. this.position.addInPlace(this.cameraDirection);
  13947. };
  13948. TargetCamera.prototype._checkInputs = function () {
  13949. var needToMove = this._decideIfNeedsToMove();
  13950. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  13951. // Move
  13952. if (needToMove) {
  13953. this._updatePosition();
  13954. }
  13955. // Rotate
  13956. if (needToRotate) {
  13957. this.rotation.x += this.cameraRotation.x;
  13958. this.rotation.y += this.cameraRotation.y;
  13959. if (!this.noRotationConstraint) {
  13960. var limit = (Math.PI / 2) * 0.95;
  13961. if (this.rotation.x > limit)
  13962. this.rotation.x = limit;
  13963. if (this.rotation.x < -limit)
  13964. this.rotation.x = -limit;
  13965. }
  13966. }
  13967. // Inertia
  13968. if (needToMove) {
  13969. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  13970. this.cameraDirection.x = 0;
  13971. }
  13972. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  13973. this.cameraDirection.y = 0;
  13974. }
  13975. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  13976. this.cameraDirection.z = 0;
  13977. }
  13978. this.cameraDirection.scaleInPlace(this.inertia);
  13979. }
  13980. if (needToRotate) {
  13981. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  13982. this.cameraRotation.x = 0;
  13983. }
  13984. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  13985. this.cameraRotation.y = 0;
  13986. }
  13987. this.cameraRotation.scaleInPlace(this.inertia);
  13988. }
  13989. _super.prototype._checkInputs.call(this);
  13990. };
  13991. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  13992. if (this.rotationQuaternion) {
  13993. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  13994. //update the up vector!
  13995. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  13996. }
  13997. else {
  13998. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  13999. }
  14000. };
  14001. TargetCamera.prototype._getViewMatrix = function () {
  14002. if (!this.lockedTarget) {
  14003. // Compute
  14004. this._updateCameraRotationMatrix();
  14005. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  14006. // Computing target and final matrix
  14007. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  14008. }
  14009. else {
  14010. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  14011. }
  14012. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14013. return this._viewMatrix;
  14014. };
  14015. /**
  14016. * @override
  14017. * Override Camera.createRigCamera
  14018. */
  14019. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14020. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  14021. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  14022. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  14023. if (!this.rotationQuaternion) {
  14024. this.rotationQuaternion = new BABYLON.Quaternion();
  14025. }
  14026. rigCamera._cameraRigParams = {};
  14027. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  14028. }
  14029. return rigCamera;
  14030. }
  14031. return null;
  14032. };
  14033. /**
  14034. * @override
  14035. * Override Camera._updateRigCameras
  14036. */
  14037. TargetCamera.prototype._updateRigCameras = function () {
  14038. var camLeft = this._rigCameras[0];
  14039. var camRight = this._rigCameras[1];
  14040. switch (this.cameraRigMode) {
  14041. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14042. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14043. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14044. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14045. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  14046. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  14047. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  14048. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  14049. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  14050. camLeft.setTarget(this.getTarget());
  14051. camRight.setTarget(this.getTarget());
  14052. break;
  14053. case BABYLON.Camera.RIG_MODE_VR:
  14054. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14055. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14056. camLeft.position.copyFrom(this.position);
  14057. camRight.position.copyFrom(this.position);
  14058. break;
  14059. }
  14060. _super.prototype._updateRigCameras.call(this);
  14061. };
  14062. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  14063. if (!this._rigCamTransformMatrix) {
  14064. this._rigCamTransformMatrix = new BABYLON.Matrix();
  14065. }
  14066. var target = this.getTarget();
  14067. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  14068. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  14069. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  14070. };
  14071. TargetCamera.prototype.getTypeName = function () {
  14072. return "TargetCamera";
  14073. };
  14074. __decorate([
  14075. BABYLON.serializeAsVector3()
  14076. ], TargetCamera.prototype, "rotation", void 0);
  14077. __decorate([
  14078. BABYLON.serialize()
  14079. ], TargetCamera.prototype, "speed", void 0);
  14080. __decorate([
  14081. BABYLON.serializeAsMeshReference("lockedTargetId")
  14082. ], TargetCamera.prototype, "lockedTarget", void 0);
  14083. return TargetCamera;
  14084. })(BABYLON.Camera);
  14085. BABYLON.TargetCamera = TargetCamera;
  14086. })(BABYLON || (BABYLON = {}));
  14087. var BABYLON;
  14088. (function (BABYLON) {
  14089. var FreeCamera = (function (_super) {
  14090. __extends(FreeCamera, _super);
  14091. function FreeCamera(name, position, scene) {
  14092. var _this = this;
  14093. _super.call(this, name, position, scene);
  14094. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  14095. this.checkCollisions = false;
  14096. this.applyGravity = false;
  14097. this._collider = new BABYLON.Collider();
  14098. this._needMoveForGravity = false;
  14099. this._oldPosition = BABYLON.Vector3.Zero();
  14100. this._diffPosition = BABYLON.Vector3.Zero();
  14101. this._newPosition = BABYLON.Vector3.Zero();
  14102. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14103. if (collidedMesh === void 0) { collidedMesh = null; }
  14104. //TODO move this to the collision coordinator!
  14105. if (_this.getScene().workerCollisions)
  14106. newPosition.multiplyInPlace(_this._collider.radius);
  14107. var updatePosition = function (newPos) {
  14108. _this._newPosition.copyFrom(newPos);
  14109. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  14110. var oldPosition = _this.position.clone();
  14111. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  14112. _this.position.addInPlace(_this._diffPosition);
  14113. if (_this.onCollide && collidedMesh) {
  14114. _this.onCollide(collidedMesh);
  14115. }
  14116. }
  14117. };
  14118. updatePosition(newPosition);
  14119. };
  14120. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  14121. this.inputs.addKeyboard().addMouse();
  14122. }
  14123. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  14124. //-- begin properties for backward compatibility for inputs
  14125. get: function () {
  14126. var mouse = this.inputs.attached["mouse"];
  14127. if (mouse)
  14128. return mouse.angularSensibility;
  14129. },
  14130. set: function (value) {
  14131. var mouse = this.inputs.attached["mouse"];
  14132. if (mouse)
  14133. mouse.angularSensibility = value;
  14134. },
  14135. enumerable: true,
  14136. configurable: true
  14137. });
  14138. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  14139. get: function () {
  14140. var keyboard = this.inputs.attached["keyboard"];
  14141. if (keyboard)
  14142. return keyboard.keysUp;
  14143. },
  14144. set: function (value) {
  14145. var keyboard = this.inputs.attached["keyboard"];
  14146. if (keyboard)
  14147. keyboard.keysUp = value;
  14148. },
  14149. enumerable: true,
  14150. configurable: true
  14151. });
  14152. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  14153. get: function () {
  14154. var keyboard = this.inputs.attached["keyboard"];
  14155. if (keyboard)
  14156. return keyboard.keysDown;
  14157. },
  14158. set: function (value) {
  14159. var keyboard = this.inputs.attached["keyboard"];
  14160. if (keyboard)
  14161. keyboard.keysDown = value;
  14162. },
  14163. enumerable: true,
  14164. configurable: true
  14165. });
  14166. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  14167. get: function () {
  14168. var keyboard = this.inputs.attached["keyboard"];
  14169. if (keyboard)
  14170. return keyboard.keysLeft;
  14171. },
  14172. set: function (value) {
  14173. var keyboard = this.inputs.attached["keyboard"];
  14174. if (keyboard)
  14175. keyboard.keysLeft = value;
  14176. },
  14177. enumerable: true,
  14178. configurable: true
  14179. });
  14180. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  14181. get: function () {
  14182. var keyboard = this.inputs.attached["keyboard"];
  14183. if (keyboard)
  14184. return keyboard.keysRight;
  14185. },
  14186. set: function (value) {
  14187. var keyboard = this.inputs.attached["keyboard"];
  14188. if (keyboard)
  14189. keyboard.keysRight = value;
  14190. },
  14191. enumerable: true,
  14192. configurable: true
  14193. });
  14194. // Controls
  14195. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  14196. this.inputs.attachElement(element, noPreventDefault);
  14197. };
  14198. FreeCamera.prototype.detachControl = function (element) {
  14199. this.inputs.detachElement(element);
  14200. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14201. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14202. };
  14203. FreeCamera.prototype._collideWithWorld = function (velocity) {
  14204. var globalPosition;
  14205. if (this.parent) {
  14206. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  14207. }
  14208. else {
  14209. globalPosition = this.position;
  14210. }
  14211. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  14212. this._collider.radius = this.ellipsoid;
  14213. //no need for clone, as long as gravity is not on.
  14214. var actualVelocity = velocity;
  14215. //add gravity to the velocity to prevent the dual-collision checking
  14216. if (this.applyGravity) {
  14217. //this prevents mending with cameraDirection, a global variable of the free camera class.
  14218. actualVelocity = velocity.add(this.getScene().gravity);
  14219. }
  14220. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14221. };
  14222. FreeCamera.prototype._checkInputs = function () {
  14223. if (!this._localDirection) {
  14224. this._localDirection = BABYLON.Vector3.Zero();
  14225. this._transformedDirection = BABYLON.Vector3.Zero();
  14226. }
  14227. this.inputs.checkInputs();
  14228. _super.prototype._checkInputs.call(this);
  14229. };
  14230. FreeCamera.prototype._decideIfNeedsToMove = function () {
  14231. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14232. };
  14233. FreeCamera.prototype._updatePosition = function () {
  14234. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  14235. this._collideWithWorld(this.cameraDirection);
  14236. }
  14237. else {
  14238. this.position.addInPlace(this.cameraDirection);
  14239. }
  14240. };
  14241. FreeCamera.prototype.dispose = function () {
  14242. this.inputs.clear();
  14243. _super.prototype.dispose.call(this);
  14244. };
  14245. FreeCamera.prototype.getTypeName = function () {
  14246. return "FreeCamera";
  14247. };
  14248. __decorate([
  14249. BABYLON.serializeAsVector3()
  14250. ], FreeCamera.prototype, "ellipsoid", void 0);
  14251. __decorate([
  14252. BABYLON.serialize()
  14253. ], FreeCamera.prototype, "checkCollisions", void 0);
  14254. __decorate([
  14255. BABYLON.serialize()
  14256. ], FreeCamera.prototype, "applyGravity", void 0);
  14257. return FreeCamera;
  14258. })(BABYLON.TargetCamera);
  14259. BABYLON.FreeCamera = FreeCamera;
  14260. })(BABYLON || (BABYLON = {}));
  14261. var BABYLON;
  14262. (function (BABYLON) {
  14263. var FreeCameraInputsManager = (function (_super) {
  14264. __extends(FreeCameraInputsManager, _super);
  14265. function FreeCameraInputsManager(camera) {
  14266. _super.call(this, camera);
  14267. }
  14268. FreeCameraInputsManager.prototype.addKeyboard = function () {
  14269. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  14270. return this;
  14271. };
  14272. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  14273. if (touchEnabled === void 0) { touchEnabled = true; }
  14274. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  14275. return this;
  14276. };
  14277. FreeCameraInputsManager.prototype.addGamepad = function () {
  14278. this.add(new BABYLON.FreeCameraGamepadInput());
  14279. return this;
  14280. };
  14281. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  14282. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  14283. return this;
  14284. };
  14285. FreeCameraInputsManager.prototype.addTouch = function () {
  14286. this.add(new BABYLON.FreeCameraTouchInput());
  14287. return this;
  14288. };
  14289. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  14290. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  14291. return this;
  14292. };
  14293. return FreeCameraInputsManager;
  14294. })(BABYLON.CameraInputsManager);
  14295. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  14296. })(BABYLON || (BABYLON = {}));
  14297. var BABYLON;
  14298. (function (BABYLON) {
  14299. var FollowCamera = (function (_super) {
  14300. __extends(FollowCamera, _super);
  14301. function FollowCamera(name, position, scene, target) {
  14302. _super.call(this, name, position, scene);
  14303. this.radius = 12;
  14304. this.rotationOffset = 0;
  14305. this.heightOffset = 4;
  14306. this.cameraAcceleration = 0.05;
  14307. this.maxCameraSpeed = 20;
  14308. this.target = target;
  14309. }
  14310. FollowCamera.prototype.getRadians = function (degrees) {
  14311. return degrees * Math.PI / 180;
  14312. };
  14313. FollowCamera.prototype.follow = function (cameraTarget) {
  14314. if (!cameraTarget)
  14315. return;
  14316. var yRotation;
  14317. if (cameraTarget.rotationQuaternion) {
  14318. var rotMatrix = new BABYLON.Matrix();
  14319. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  14320. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  14321. }
  14322. else {
  14323. yRotation = cameraTarget.rotation.y;
  14324. }
  14325. var radians = this.getRadians(this.rotationOffset) + yRotation;
  14326. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  14327. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  14328. var dx = targetX - this.position.x;
  14329. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  14330. var dz = (targetZ) - this.position.z;
  14331. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  14332. var vy = dy * this.cameraAcceleration;
  14333. var vz = dz * this.cameraAcceleration * 2;
  14334. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  14335. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14336. }
  14337. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  14338. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14339. }
  14340. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  14341. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14342. }
  14343. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  14344. this.setTarget(cameraTarget.position);
  14345. };
  14346. FollowCamera.prototype._checkInputs = function () {
  14347. _super.prototype._checkInputs.call(this);
  14348. this.follow(this.target);
  14349. };
  14350. FollowCamera.prototype.getTypeName = function () {
  14351. return "FollowCamera";
  14352. };
  14353. __decorate([
  14354. BABYLON.serialize()
  14355. ], FollowCamera.prototype, "radius", void 0);
  14356. __decorate([
  14357. BABYLON.serialize()
  14358. ], FollowCamera.prototype, "rotationOffset", void 0);
  14359. __decorate([
  14360. BABYLON.serialize()
  14361. ], FollowCamera.prototype, "heightOffset", void 0);
  14362. __decorate([
  14363. BABYLON.serialize()
  14364. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  14365. __decorate([
  14366. BABYLON.serialize()
  14367. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  14368. __decorate([
  14369. BABYLON.serializeAsMeshReference("lockedTargetId")
  14370. ], FollowCamera.prototype, "target", void 0);
  14371. return FollowCamera;
  14372. })(BABYLON.TargetCamera);
  14373. BABYLON.FollowCamera = FollowCamera;
  14374. var ArcFollowCamera = (function (_super) {
  14375. __extends(ArcFollowCamera, _super);
  14376. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  14377. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14378. this.alpha = alpha;
  14379. this.beta = beta;
  14380. this.radius = radius;
  14381. this.target = target;
  14382. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  14383. this.follow();
  14384. }
  14385. ArcFollowCamera.prototype.follow = function () {
  14386. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  14387. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  14388. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  14389. this.position = this.target.position.add(this._cartesianCoordinates);
  14390. this.setTarget(this.target.position);
  14391. };
  14392. ArcFollowCamera.prototype._checkInputs = function () {
  14393. _super.prototype._checkInputs.call(this);
  14394. this.follow();
  14395. };
  14396. ArcFollowCamera.prototype.getTypeName = function () {
  14397. return "ArcFollowCamera";
  14398. };
  14399. return ArcFollowCamera;
  14400. })(BABYLON.TargetCamera);
  14401. BABYLON.ArcFollowCamera = ArcFollowCamera;
  14402. })(BABYLON || (BABYLON = {}));
  14403. var BABYLON;
  14404. (function (BABYLON) {
  14405. // We're mainly based on the logic defined into the FreeCamera code
  14406. var TouchCamera = (function (_super) {
  14407. __extends(TouchCamera, _super);
  14408. //-- end properties for backward compatibility for inputs
  14409. function TouchCamera(name, position, scene) {
  14410. _super.call(this, name, position, scene);
  14411. this.inputs.addTouch();
  14412. this._setupInputs();
  14413. }
  14414. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  14415. //-- Begin properties for backward compatibility for inputs
  14416. get: function () {
  14417. var touch = this.inputs.attached["touch"];
  14418. if (touch)
  14419. return touch.touchAngularSensibility;
  14420. },
  14421. set: function (value) {
  14422. var touch = this.inputs.attached["touch"];
  14423. if (touch)
  14424. touch.touchAngularSensibility = value;
  14425. },
  14426. enumerable: true,
  14427. configurable: true
  14428. });
  14429. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  14430. get: function () {
  14431. var touch = this.inputs.attached["touch"];
  14432. if (touch)
  14433. return touch.touchMoveSensibility;
  14434. },
  14435. set: function (value) {
  14436. var touch = this.inputs.attached["touch"];
  14437. if (touch)
  14438. touch.touchMoveSensibility = value;
  14439. },
  14440. enumerable: true,
  14441. configurable: true
  14442. });
  14443. TouchCamera.prototype.getTypeName = function () {
  14444. return "TouchCamera";
  14445. };
  14446. TouchCamera.prototype._setupInputs = function () {
  14447. var mouse = this.inputs.attached["mouse"];
  14448. if (mouse) {
  14449. mouse.touchEnabled = false;
  14450. }
  14451. };
  14452. return TouchCamera;
  14453. })(BABYLON.FreeCamera);
  14454. BABYLON.TouchCamera = TouchCamera;
  14455. })(BABYLON || (BABYLON = {}));
  14456. var BABYLON;
  14457. (function (BABYLON) {
  14458. var ArcRotateCamera = (function (_super) {
  14459. __extends(ArcRotateCamera, _super);
  14460. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  14461. var _this = this;
  14462. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14463. this.inertialAlphaOffset = 0;
  14464. this.inertialBetaOffset = 0;
  14465. this.inertialRadiusOffset = 0;
  14466. this.lowerAlphaLimit = null;
  14467. this.upperAlphaLimit = null;
  14468. this.lowerBetaLimit = 0.01;
  14469. this.upperBetaLimit = Math.PI;
  14470. this.lowerRadiusLimit = null;
  14471. this.upperRadiusLimit = null;
  14472. this.inertialPanningX = 0;
  14473. this.inertialPanningY = 0;
  14474. //-- end properties for backward compatibility for inputs
  14475. this.zoomOnFactor = 1;
  14476. this.targetScreenOffset = BABYLON.Vector2.Zero();
  14477. this.allowUpsideDown = true;
  14478. this._viewMatrix = new BABYLON.Matrix();
  14479. // Panning
  14480. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  14481. this.checkCollisions = false;
  14482. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14483. this._collider = new BABYLON.Collider();
  14484. this._previousPosition = BABYLON.Vector3.Zero();
  14485. this._collisionVelocity = BABYLON.Vector3.Zero();
  14486. this._newPosition = BABYLON.Vector3.Zero();
  14487. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14488. if (collidedMesh === void 0) { collidedMesh = null; }
  14489. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  14490. newPosition.multiplyInPlace(_this._collider.radius);
  14491. }
  14492. if (!collidedMesh) {
  14493. _this._previousPosition.copyFrom(_this.position);
  14494. }
  14495. else {
  14496. _this.setPosition(newPosition);
  14497. if (_this.onCollide) {
  14498. _this.onCollide(collidedMesh);
  14499. }
  14500. }
  14501. // Recompute because of constraints
  14502. var cosa = Math.cos(_this.alpha);
  14503. var sina = Math.sin(_this.alpha);
  14504. var cosb = Math.cos(_this.beta);
  14505. var sinb = Math.sin(_this.beta);
  14506. if (sinb === 0) {
  14507. sinb = 0.0001;
  14508. }
  14509. var target = _this._getTargetPosition();
  14510. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  14511. _this.position.copyFrom(_this._newPosition);
  14512. var up = _this.upVector;
  14513. if (_this.allowUpsideDown && _this.beta < 0) {
  14514. up = up.clone();
  14515. up = up.negate();
  14516. }
  14517. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  14518. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  14519. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  14520. _this._collisionTriggered = false;
  14521. };
  14522. if (!target) {
  14523. this.target = BABYLON.Vector3.Zero();
  14524. }
  14525. else {
  14526. this.target = target;
  14527. }
  14528. this.alpha = alpha;
  14529. this.beta = beta;
  14530. this.radius = radius;
  14531. this.getViewMatrix();
  14532. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  14533. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  14534. }
  14535. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  14536. //-- begin properties for backward compatibility for inputs
  14537. get: function () {
  14538. var pointers = this.inputs.attached["pointers"];
  14539. if (pointers)
  14540. return pointers.angularSensibilityX;
  14541. },
  14542. set: function (value) {
  14543. var pointers = this.inputs.attached["pointers"];
  14544. if (pointers) {
  14545. pointers.angularSensibilityX = value;
  14546. }
  14547. },
  14548. enumerable: true,
  14549. configurable: true
  14550. });
  14551. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  14552. get: function () {
  14553. var pointers = this.inputs.attached["pointers"];
  14554. if (pointers)
  14555. return pointers.angularSensibilityY;
  14556. },
  14557. set: function (value) {
  14558. var pointers = this.inputs.attached["pointers"];
  14559. if (pointers) {
  14560. pointers.angularSensibilityY = value;
  14561. }
  14562. },
  14563. enumerable: true,
  14564. configurable: true
  14565. });
  14566. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  14567. get: function () {
  14568. var pointers = this.inputs.attached["pointers"];
  14569. if (pointers)
  14570. return pointers.pinchPrecision;
  14571. },
  14572. set: function (value) {
  14573. var pointers = this.inputs.attached["pointers"];
  14574. if (pointers) {
  14575. pointers.pinchPrecision = value;
  14576. }
  14577. },
  14578. enumerable: true,
  14579. configurable: true
  14580. });
  14581. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  14582. get: function () {
  14583. var pointers = this.inputs.attached["pointers"];
  14584. if (pointers)
  14585. return pointers.panningSensibility;
  14586. },
  14587. set: function (value) {
  14588. var pointers = this.inputs.attached["pointers"];
  14589. if (pointers) {
  14590. pointers.panningSensibility = value;
  14591. }
  14592. },
  14593. enumerable: true,
  14594. configurable: true
  14595. });
  14596. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  14597. get: function () {
  14598. var keyboard = this.inputs.attached["keyboard"];
  14599. if (keyboard)
  14600. return keyboard.keysUp;
  14601. },
  14602. set: function (value) {
  14603. var keyboard = this.inputs.attached["keyboard"];
  14604. if (keyboard)
  14605. keyboard.keysUp = value;
  14606. },
  14607. enumerable: true,
  14608. configurable: true
  14609. });
  14610. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  14611. get: function () {
  14612. var keyboard = this.inputs.attached["keyboard"];
  14613. if (keyboard)
  14614. return keyboard.keysDown;
  14615. },
  14616. set: function (value) {
  14617. var keyboard = this.inputs.attached["keyboard"];
  14618. if (keyboard)
  14619. keyboard.keysDown = value;
  14620. },
  14621. enumerable: true,
  14622. configurable: true
  14623. });
  14624. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  14625. get: function () {
  14626. var keyboard = this.inputs.attached["keyboard"];
  14627. if (keyboard)
  14628. return keyboard.keysLeft;
  14629. },
  14630. set: function (value) {
  14631. var keyboard = this.inputs.attached["keyboard"];
  14632. if (keyboard)
  14633. keyboard.keysLeft = value;
  14634. },
  14635. enumerable: true,
  14636. configurable: true
  14637. });
  14638. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  14639. get: function () {
  14640. var keyboard = this.inputs.attached["keyboard"];
  14641. if (keyboard)
  14642. return keyboard.keysRight;
  14643. },
  14644. set: function (value) {
  14645. var keyboard = this.inputs.attached["keyboard"];
  14646. if (keyboard)
  14647. keyboard.keysRight = value;
  14648. },
  14649. enumerable: true,
  14650. configurable: true
  14651. });
  14652. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  14653. get: function () {
  14654. var mousewheel = this.inputs.attached["mousewheel"];
  14655. if (mousewheel)
  14656. return mousewheel.wheelPrecision;
  14657. },
  14658. set: function (value) {
  14659. var mousewheel = this.inputs.attached["mousewheel"];
  14660. if (mousewheel)
  14661. mousewheel.wheelPrecision = value;
  14662. },
  14663. enumerable: true,
  14664. configurable: true
  14665. });
  14666. // Cache
  14667. ArcRotateCamera.prototype._initCache = function () {
  14668. _super.prototype._initCache.call(this);
  14669. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14670. this._cache.alpha = undefined;
  14671. this._cache.beta = undefined;
  14672. this._cache.radius = undefined;
  14673. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  14674. };
  14675. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  14676. if (!ignoreParentClass) {
  14677. _super.prototype._updateCache.call(this);
  14678. }
  14679. this._cache.target.copyFrom(this._getTargetPosition());
  14680. this._cache.alpha = this.alpha;
  14681. this._cache.beta = this.beta;
  14682. this._cache.radius = this.radius;
  14683. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  14684. };
  14685. ArcRotateCamera.prototype._getTargetPosition = function () {
  14686. if (this.target.getAbsolutePosition) {
  14687. return this.target.getAbsolutePosition();
  14688. }
  14689. return this.target;
  14690. };
  14691. // Synchronized
  14692. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  14693. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  14694. return false;
  14695. return this._cache.target.equals(this.target)
  14696. && this._cache.alpha === this.alpha
  14697. && this._cache.beta === this.beta
  14698. && this._cache.radius === this.radius
  14699. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  14700. };
  14701. // Methods
  14702. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  14703. var _this = this;
  14704. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  14705. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  14706. this._useCtrlForPanning = useCtrlForPanning;
  14707. this._panningMouseButton = panningMouseButton;
  14708. this.inputs.attachElement(element, noPreventDefault);
  14709. this._reset = function () {
  14710. _this.inertialAlphaOffset = 0;
  14711. _this.inertialBetaOffset = 0;
  14712. _this.inertialRadiusOffset = 0;
  14713. };
  14714. };
  14715. ArcRotateCamera.prototype.detachControl = function (element) {
  14716. this.inputs.detachElement(element);
  14717. if (this._reset) {
  14718. this._reset();
  14719. }
  14720. };
  14721. ArcRotateCamera.prototype._checkInputs = function () {
  14722. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  14723. if (this._collisionTriggered) {
  14724. return;
  14725. }
  14726. this.inputs.checkInputs();
  14727. // Inertia
  14728. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  14729. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  14730. this.beta += this.inertialBetaOffset;
  14731. this.radius -= this.inertialRadiusOffset;
  14732. this.inertialAlphaOffset *= this.inertia;
  14733. this.inertialBetaOffset *= this.inertia;
  14734. this.inertialRadiusOffset *= this.inertia;
  14735. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  14736. this.inertialAlphaOffset = 0;
  14737. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  14738. this.inertialBetaOffset = 0;
  14739. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  14740. this.inertialRadiusOffset = 0;
  14741. }
  14742. // Panning inertia
  14743. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  14744. if (!this._localDirection) {
  14745. this._localDirection = BABYLON.Vector3.Zero();
  14746. this._transformedDirection = BABYLON.Vector3.Zero();
  14747. }
  14748. this.inertialPanningX *= this.inertia;
  14749. this.inertialPanningY *= this.inertia;
  14750. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  14751. this.inertialPanningX = 0;
  14752. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  14753. this.inertialPanningY = 0;
  14754. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  14755. this._localDirection.multiplyInPlace(this.panningAxis);
  14756. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  14757. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  14758. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  14759. if (!this.panningAxis.y) {
  14760. this._transformedDirection.y = 0;
  14761. }
  14762. if (!this.target.getAbsolutePosition) {
  14763. this.target.addInPlace(this._transformedDirection);
  14764. }
  14765. }
  14766. // Limits
  14767. this._checkLimits();
  14768. _super.prototype._checkInputs.call(this);
  14769. };
  14770. ArcRotateCamera.prototype._checkLimits = function () {
  14771. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  14772. if (this.allowUpsideDown && this.beta > Math.PI) {
  14773. this.beta = this.beta - (2 * Math.PI);
  14774. }
  14775. }
  14776. else {
  14777. if (this.beta < this.lowerBetaLimit) {
  14778. this.beta = this.lowerBetaLimit;
  14779. }
  14780. }
  14781. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  14782. if (this.allowUpsideDown && this.beta < -Math.PI) {
  14783. this.beta = this.beta + (2 * Math.PI);
  14784. }
  14785. }
  14786. else {
  14787. if (this.beta > this.upperBetaLimit) {
  14788. this.beta = this.upperBetaLimit;
  14789. }
  14790. }
  14791. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  14792. this.alpha = this.lowerAlphaLimit;
  14793. }
  14794. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  14795. this.alpha = this.upperAlphaLimit;
  14796. }
  14797. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  14798. this.radius = this.lowerRadiusLimit;
  14799. }
  14800. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  14801. this.radius = this.upperRadiusLimit;
  14802. }
  14803. };
  14804. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  14805. var radiusv3 = this.position.subtract(this._getTargetPosition());
  14806. this.radius = radiusv3.length();
  14807. // Alpha
  14808. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  14809. if (radiusv3.z < 0) {
  14810. this.alpha = 2 * Math.PI - this.alpha;
  14811. }
  14812. // Beta
  14813. this.beta = Math.acos(radiusv3.y / this.radius);
  14814. this._checkLimits();
  14815. };
  14816. ArcRotateCamera.prototype.setPosition = function (position) {
  14817. if (this.position.equals(position)) {
  14818. return;
  14819. }
  14820. this.position.copyFrom(position);
  14821. this.rebuildAnglesAndRadius();
  14822. };
  14823. ArcRotateCamera.prototype.setTarget = function (target) {
  14824. if (this._getTargetPosition().equals(target)) {
  14825. return;
  14826. }
  14827. this.target = target;
  14828. this.rebuildAnglesAndRadius();
  14829. };
  14830. ArcRotateCamera.prototype._getViewMatrix = function () {
  14831. // Compute
  14832. var cosa = Math.cos(this.alpha);
  14833. var sina = Math.sin(this.alpha);
  14834. var cosb = Math.cos(this.beta);
  14835. var sinb = Math.sin(this.beta);
  14836. if (sinb === 0) {
  14837. sinb = 0.0001;
  14838. }
  14839. var target = this._getTargetPosition();
  14840. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  14841. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  14842. this._collider.radius = this.collisionRadius;
  14843. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  14844. this._collisionTriggered = true;
  14845. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14846. }
  14847. else {
  14848. this.position.copyFrom(this._newPosition);
  14849. var up = this.upVector;
  14850. if (this.allowUpsideDown && this.beta < 0) {
  14851. up = up.clone();
  14852. up = up.negate();
  14853. }
  14854. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  14855. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  14856. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  14857. }
  14858. return this._viewMatrix;
  14859. };
  14860. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  14861. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14862. meshes = meshes || this.getScene().meshes;
  14863. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  14864. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  14865. this.radius = distance * this.zoomOnFactor;
  14866. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  14867. };
  14868. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  14869. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14870. var meshesOrMinMaxVector;
  14871. var distance;
  14872. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  14873. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  14874. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  14875. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  14876. }
  14877. else {
  14878. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  14879. distance = meshesOrMinMaxVectorAndDistance.distance;
  14880. }
  14881. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  14882. if (!doNotUpdateMaxZ) {
  14883. this.maxZ = distance * 2;
  14884. }
  14885. };
  14886. /**
  14887. * @override
  14888. * Override Camera.createRigCamera
  14889. */
  14890. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14891. var alphaShift;
  14892. switch (this.cameraRigMode) {
  14893. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14894. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14895. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14896. case BABYLON.Camera.RIG_MODE_VR:
  14897. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  14898. break;
  14899. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14900. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  14901. break;
  14902. }
  14903. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  14904. rigCam._cameraRigParams = {};
  14905. return rigCam;
  14906. };
  14907. /**
  14908. * @override
  14909. * Override Camera._updateRigCameras
  14910. */
  14911. ArcRotateCamera.prototype._updateRigCameras = function () {
  14912. var camLeft = this._rigCameras[0];
  14913. var camRight = this._rigCameras[1];
  14914. camLeft.beta = camRight.beta = this.beta;
  14915. camLeft.radius = camRight.radius = this.radius;
  14916. switch (this.cameraRigMode) {
  14917. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14918. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14919. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14920. case BABYLON.Camera.RIG_MODE_VR:
  14921. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  14922. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  14923. break;
  14924. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14925. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  14926. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  14927. break;
  14928. }
  14929. _super.prototype._updateRigCameras.call(this);
  14930. };
  14931. ArcRotateCamera.prototype.dispose = function () {
  14932. this.inputs.clear();
  14933. _super.prototype.dispose.call(this);
  14934. };
  14935. ArcRotateCamera.prototype.getTypeName = function () {
  14936. return "ArcRotateCamera";
  14937. };
  14938. __decorate([
  14939. BABYLON.serialize()
  14940. ], ArcRotateCamera.prototype, "alpha", void 0);
  14941. __decorate([
  14942. BABYLON.serialize()
  14943. ], ArcRotateCamera.prototype, "beta", void 0);
  14944. __decorate([
  14945. BABYLON.serialize()
  14946. ], ArcRotateCamera.prototype, "radius", void 0);
  14947. __decorate([
  14948. BABYLON.serializeAsVector3()
  14949. ], ArcRotateCamera.prototype, "target", void 0);
  14950. __decorate([
  14951. BABYLON.serialize()
  14952. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  14953. __decorate([
  14954. BABYLON.serialize()
  14955. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  14956. __decorate([
  14957. BABYLON.serialize()
  14958. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  14959. __decorate([
  14960. BABYLON.serialize()
  14961. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  14962. __decorate([
  14963. BABYLON.serialize()
  14964. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  14965. __decorate([
  14966. BABYLON.serialize()
  14967. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  14968. __decorate([
  14969. BABYLON.serialize()
  14970. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  14971. __decorate([
  14972. BABYLON.serialize()
  14973. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  14974. __decorate([
  14975. BABYLON.serialize()
  14976. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  14977. __decorate([
  14978. BABYLON.serialize()
  14979. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  14980. __decorate([
  14981. BABYLON.serialize()
  14982. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  14983. __decorate([
  14984. BABYLON.serialize()
  14985. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  14986. __decorate([
  14987. BABYLON.serialize()
  14988. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  14989. return ArcRotateCamera;
  14990. })(BABYLON.TargetCamera);
  14991. BABYLON.ArcRotateCamera = ArcRotateCamera;
  14992. })(BABYLON || (BABYLON = {}));
  14993. var BABYLON;
  14994. (function (BABYLON) {
  14995. var ArcRotateCameraInputsManager = (function (_super) {
  14996. __extends(ArcRotateCameraInputsManager, _super);
  14997. function ArcRotateCameraInputsManager(camera) {
  14998. _super.call(this, camera);
  14999. }
  15000. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  15001. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  15002. return this;
  15003. };
  15004. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  15005. this.add(new BABYLON.ArcRotateCameraPointersInput());
  15006. return this;
  15007. };
  15008. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  15009. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  15010. return this;
  15011. };
  15012. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  15013. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  15014. return this;
  15015. };
  15016. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  15017. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  15018. return this;
  15019. };
  15020. return ArcRotateCameraInputsManager;
  15021. })(BABYLON.CameraInputsManager);
  15022. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  15023. })(BABYLON || (BABYLON = {}));
  15024. var BABYLON;
  15025. (function (BABYLON) {
  15026. var RenderingManager = (function () {
  15027. function RenderingManager(scene) {
  15028. this._renderingGroups = new Array();
  15029. this._autoClearDepthStencil = {};
  15030. this._customOpaqueSortCompareFn = {};
  15031. this._customAlphaTestSortCompareFn = {};
  15032. this._customTransparentSortCompareFn = {};
  15033. this._scene = scene;
  15034. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15035. this._autoClearDepthStencil[i] = true;
  15036. }
  15037. }
  15038. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  15039. if (this._scene._activeParticleSystems.length === 0) {
  15040. return;
  15041. }
  15042. // Particles
  15043. var activeCamera = this._scene.activeCamera;
  15044. this._scene._particlesDuration.beginMonitoring();
  15045. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15046. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15047. if (particleSystem.renderingGroupId !== index) {
  15048. continue;
  15049. }
  15050. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15051. continue;
  15052. }
  15053. this._clearDepthStencilBuffer();
  15054. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15055. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15056. }
  15057. }
  15058. this._scene._particlesDuration.endMonitoring(false);
  15059. };
  15060. RenderingManager.prototype._renderSprites = function (index) {
  15061. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  15062. return;
  15063. }
  15064. // Sprites
  15065. var activeCamera = this._scene.activeCamera;
  15066. this._scene._spritesDuration.beginMonitoring();
  15067. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  15068. var spriteManager = this._scene.spriteManagers[id];
  15069. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15070. this._clearDepthStencilBuffer();
  15071. spriteManager.render();
  15072. }
  15073. }
  15074. this._scene._spritesDuration.endMonitoring(false);
  15075. };
  15076. RenderingManager.prototype._clearDepthStencilBuffer = function () {
  15077. if (this._depthStencilBufferAlreadyCleaned) {
  15078. return;
  15079. }
  15080. this._scene.getEngine().clear(0, false, true, true);
  15081. this._depthStencilBufferAlreadyCleaned = true;
  15082. };
  15083. RenderingManager.prototype._renderSpritesAndParticles = function () {
  15084. if (this._currentRenderSprites) {
  15085. this._renderSprites(this._currentIndex);
  15086. }
  15087. if (this._currentRenderParticles) {
  15088. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  15089. }
  15090. };
  15091. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15092. this._currentActiveMeshes = activeMeshes;
  15093. this._currentRenderParticles = renderParticles;
  15094. this._currentRenderSprites = renderSprites;
  15095. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15096. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15097. var renderingGroup = this._renderingGroups[index];
  15098. var needToStepBack = false;
  15099. this._currentIndex = index;
  15100. if (renderingGroup) {
  15101. if (this._autoClearDepthStencil[index]) {
  15102. this._clearDepthStencilBuffer();
  15103. }
  15104. if (!renderingGroup.onBeforeTransparentRendering) {
  15105. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  15106. }
  15107. if (!renderingGroup.render(customRenderFunction)) {
  15108. this._renderingGroups.splice(index, 1);
  15109. needToStepBack = true;
  15110. this._renderSpritesAndParticles();
  15111. }
  15112. }
  15113. else {
  15114. this._renderSpritesAndParticles();
  15115. }
  15116. if (needToStepBack) {
  15117. index--;
  15118. }
  15119. }
  15120. };
  15121. RenderingManager.prototype.reset = function () {
  15122. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15123. var renderingGroup = this._renderingGroups[index];
  15124. if (renderingGroup) {
  15125. renderingGroup.prepare();
  15126. }
  15127. }
  15128. };
  15129. RenderingManager.prototype.dispatch = function (subMesh) {
  15130. var mesh = subMesh.getMesh();
  15131. var renderingGroupId = mesh.renderingGroupId || 0;
  15132. if (!this._renderingGroups[renderingGroupId]) {
  15133. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15134. }
  15135. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15136. };
  15137. /**
  15138. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15139. * This allowed control for front to back rendering or reversly depending of the special needs.
  15140. *
  15141. * @param renderingGroupId The rendering group id corresponding to its index
  15142. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15143. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15144. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15145. */
  15146. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15147. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15148. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15149. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15150. if (this._renderingGroups[renderingGroupId]) {
  15151. var group = this._renderingGroups[renderingGroupId];
  15152. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15153. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15154. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15155. }
  15156. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15157. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15158. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15159. };
  15160. /**
  15161. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15162. *
  15163. * @param renderingGroupId The rendering group id corresponding to its index
  15164. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15165. */
  15166. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  15167. this._autoClearDepthStencil[renderingGroupId] = autoClearDepthStencil;
  15168. };
  15169. /**
  15170. * The max id used for rendering groups (not included)
  15171. */
  15172. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15173. /**
  15174. * The min id used for rendering groups (included)
  15175. */
  15176. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15177. return RenderingManager;
  15178. })();
  15179. BABYLON.RenderingManager = RenderingManager;
  15180. })(BABYLON || (BABYLON = {}));
  15181. var BABYLON;
  15182. (function (BABYLON) {
  15183. var RenderingGroup = (function () {
  15184. /**
  15185. * Creates a new rendering group.
  15186. * @param index The rendering group index
  15187. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15188. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15189. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15190. */
  15191. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15192. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15193. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15194. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15195. this.index = index;
  15196. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15197. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15198. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15199. this._scene = scene;
  15200. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15201. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15202. this.transparentSortCompareFn = transparentSortCompareFn;
  15203. }
  15204. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15205. /**
  15206. * Set the opaque sort comparison function.
  15207. * If null the sub meshes will be render in the order they were created
  15208. */
  15209. set: function (value) {
  15210. this._opaqueSortCompareFn = value;
  15211. if (value) {
  15212. this._renderOpaque = this.renderOpaqueSorted;
  15213. }
  15214. else {
  15215. this._renderOpaque = RenderingGroup.renderUnsorted;
  15216. }
  15217. },
  15218. enumerable: true,
  15219. configurable: true
  15220. });
  15221. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15222. /**
  15223. * Set the alpha test sort comparison function.
  15224. * If null the sub meshes will be render in the order they were created
  15225. */
  15226. set: function (value) {
  15227. this._alphaTestSortCompareFn = value;
  15228. if (value) {
  15229. this._renderAlphaTest = this.renderAlphaTestSorted;
  15230. }
  15231. else {
  15232. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15233. }
  15234. },
  15235. enumerable: true,
  15236. configurable: true
  15237. });
  15238. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15239. /**
  15240. * Set the transparent sort comparison function.
  15241. * If null the sub meshes will be render in the order they were created
  15242. */
  15243. set: function (value) {
  15244. if (value) {
  15245. this._transparentSortCompareFn = value;
  15246. }
  15247. else {
  15248. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15249. }
  15250. this._renderTransparent = this.renderTransparentSorted;
  15251. },
  15252. enumerable: true,
  15253. configurable: true
  15254. });
  15255. /**
  15256. * Render all the sub meshes contained in the group.
  15257. * @param customRenderFunction Used to override the default render behaviour of the group.
  15258. * @returns true if rendered some submeshes.
  15259. */
  15260. RenderingGroup.prototype.render = function (customRenderFunction) {
  15261. if (customRenderFunction) {
  15262. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15263. return true;
  15264. }
  15265. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  15266. if (this.onBeforeTransparentRendering) {
  15267. this.onBeforeTransparentRendering();
  15268. }
  15269. return false;
  15270. }
  15271. var engine = this._scene.getEngine();
  15272. // Opaque
  15273. this._renderOpaque(this._opaqueSubMeshes);
  15274. // Alpha test
  15275. engine.setAlphaTesting(true);
  15276. this._renderAlphaTest(this._alphaTestSubMeshes);
  15277. engine.setAlphaTesting(false);
  15278. if (this.onBeforeTransparentRendering) {
  15279. this.onBeforeTransparentRendering();
  15280. }
  15281. // Transparent
  15282. this._renderTransparent(this._transparentSubMeshes);
  15283. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15284. return true;
  15285. };
  15286. /**
  15287. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15288. * @param subMeshes The submeshes to render
  15289. */
  15290. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15291. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15292. };
  15293. /**
  15294. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15295. * @param subMeshes The submeshes to render
  15296. */
  15297. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15298. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15299. };
  15300. /**
  15301. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15302. * @param subMeshes The submeshes to render
  15303. */
  15304. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15305. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15306. };
  15307. /**
  15308. * Renders the submeshes in a specified order.
  15309. * @param subMeshes The submeshes to sort before render
  15310. * @param sortCompareFn The comparison function use to sort
  15311. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15312. * @param transparent Specifies to activate blending if true
  15313. */
  15314. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15315. var subIndex = 0;
  15316. var subMesh;
  15317. for (; subIndex < subMeshes.length; subIndex++) {
  15318. subMesh = subMeshes.data[subIndex];
  15319. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15320. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15321. }
  15322. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15323. sortedArray.sort(sortCompareFn);
  15324. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15325. subMesh = sortedArray[subIndex];
  15326. subMesh.render(transparent);
  15327. }
  15328. };
  15329. /**
  15330. * Renders the submeshes in the order they were dispatched (no sort applied).
  15331. * @param subMeshes The submeshes to render
  15332. */
  15333. RenderingGroup.renderUnsorted = function (subMeshes) {
  15334. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15335. var submesh = subMeshes.data[subIndex];
  15336. submesh.render(false);
  15337. }
  15338. };
  15339. /**
  15340. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15341. * are rendered back to front if in the same alpha index.
  15342. *
  15343. * @param a The first submesh
  15344. * @param b The second submesh
  15345. * @returns The result of the comparison
  15346. */
  15347. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15348. // Alpha index first
  15349. if (a._alphaIndex > b._alphaIndex) {
  15350. return 1;
  15351. }
  15352. if (a._alphaIndex < b._alphaIndex) {
  15353. return -1;
  15354. }
  15355. // Then distance to camera
  15356. return RenderingGroup.backToFrontSortCompare(a, b);
  15357. };
  15358. /**
  15359. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15360. * are rendered back to front.
  15361. *
  15362. * @param a The first submesh
  15363. * @param b The second submesh
  15364. * @returns The result of the comparison
  15365. */
  15366. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15367. // Then distance to camera
  15368. if (a._distanceToCamera < b._distanceToCamera) {
  15369. return 1;
  15370. }
  15371. if (a._distanceToCamera > b._distanceToCamera) {
  15372. return -1;
  15373. }
  15374. return 0;
  15375. };
  15376. /**
  15377. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15378. * are rendered front to back (prevent overdraw).
  15379. *
  15380. * @param a The first submesh
  15381. * @param b The second submesh
  15382. * @returns The result of the comparison
  15383. */
  15384. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15385. // Then distance to camera
  15386. if (a._distanceToCamera < b._distanceToCamera) {
  15387. return -1;
  15388. }
  15389. if (a._distanceToCamera > b._distanceToCamera) {
  15390. return 1;
  15391. }
  15392. return 0;
  15393. };
  15394. /**
  15395. * Resets the different lists of submeshes to prepare a new frame.
  15396. */
  15397. RenderingGroup.prototype.prepare = function () {
  15398. this._opaqueSubMeshes.reset();
  15399. this._transparentSubMeshes.reset();
  15400. this._alphaTestSubMeshes.reset();
  15401. };
  15402. /**
  15403. * Inserts the submesh in its correct queue depending on its material.
  15404. * @param subMesh The submesh to dispatch
  15405. */
  15406. RenderingGroup.prototype.dispatch = function (subMesh) {
  15407. var material = subMesh.getMaterial();
  15408. var mesh = subMesh.getMesh();
  15409. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15410. this._transparentSubMeshes.push(subMesh);
  15411. }
  15412. else if (material.needAlphaTesting()) {
  15413. this._alphaTestSubMeshes.push(subMesh);
  15414. }
  15415. else {
  15416. this._opaqueSubMeshes.push(subMesh); // Opaque
  15417. }
  15418. };
  15419. return RenderingGroup;
  15420. })();
  15421. BABYLON.RenderingGroup = RenderingGroup;
  15422. })(BABYLON || (BABYLON = {}));
  15423. var BABYLON;
  15424. (function (BABYLON) {
  15425. var PointerEventTypes = (function () {
  15426. function PointerEventTypes() {
  15427. }
  15428. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15429. get: function () {
  15430. return PointerEventTypes._POINTERDOWN;
  15431. },
  15432. enumerable: true,
  15433. configurable: true
  15434. });
  15435. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15436. get: function () {
  15437. return PointerEventTypes._POINTERUP;
  15438. },
  15439. enumerable: true,
  15440. configurable: true
  15441. });
  15442. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15443. get: function () {
  15444. return PointerEventTypes._POINTERMOVE;
  15445. },
  15446. enumerable: true,
  15447. configurable: true
  15448. });
  15449. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15450. get: function () {
  15451. return PointerEventTypes._POINTERWHEEL;
  15452. },
  15453. enumerable: true,
  15454. configurable: true
  15455. });
  15456. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15457. get: function () {
  15458. return PointerEventTypes._POINTERPICK;
  15459. },
  15460. enumerable: true,
  15461. configurable: true
  15462. });
  15463. PointerEventTypes._POINTERDOWN = 0x01;
  15464. PointerEventTypes._POINTERUP = 0x02;
  15465. PointerEventTypes._POINTERMOVE = 0x04;
  15466. PointerEventTypes._POINTERWHEEL = 0x08;
  15467. PointerEventTypes._POINTERPICK = 0x10;
  15468. return PointerEventTypes;
  15469. })();
  15470. BABYLON.PointerEventTypes = PointerEventTypes;
  15471. var PointerInfoBase = (function () {
  15472. function PointerInfoBase(type, event) {
  15473. this.type = type;
  15474. this.event = event;
  15475. }
  15476. return PointerInfoBase;
  15477. })();
  15478. BABYLON.PointerInfoBase = PointerInfoBase;
  15479. /**
  15480. * This class is used to store pointer related info for the onPrePointerObservable event.
  15481. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15482. */
  15483. var PointerInfoPre = (function (_super) {
  15484. __extends(PointerInfoPre, _super);
  15485. function PointerInfoPre(type, event, localX, localY) {
  15486. _super.call(this, type, event);
  15487. this.skipOnPointerObservable = false;
  15488. this.localPosition = new BABYLON.Vector2(localX, localY);
  15489. }
  15490. return PointerInfoPre;
  15491. })(PointerInfoBase);
  15492. BABYLON.PointerInfoPre = PointerInfoPre;
  15493. /**
  15494. * This type contains all the data related to a pointer event in Babylon.js.
  15495. * 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.
  15496. */
  15497. var PointerInfo = (function (_super) {
  15498. __extends(PointerInfo, _super);
  15499. function PointerInfo(type, event, pickInfo) {
  15500. _super.call(this, type, event);
  15501. this.pickInfo = pickInfo;
  15502. }
  15503. return PointerInfo;
  15504. })(PointerInfoBase);
  15505. BABYLON.PointerInfo = PointerInfo;
  15506. /**
  15507. * Represents a scene to be rendered by the engine.
  15508. * @see http://doc.babylonjs.com/page.php?p=21911
  15509. */
  15510. var Scene = (function () {
  15511. /**
  15512. * @constructor
  15513. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15514. */
  15515. function Scene(engine) {
  15516. // Members
  15517. this.autoClear = true;
  15518. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15519. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15520. this.forceWireframe = false;
  15521. this.forcePointsCloud = false;
  15522. this.forceShowBoundingBoxes = false;
  15523. this.animationsEnabled = true;
  15524. this.constantlyUpdateMeshUnderPointer = false;
  15525. this.hoverCursor = "pointer";
  15526. // Events
  15527. /**
  15528. * An event triggered when the scene is disposed.
  15529. * @type {BABYLON.Observable}
  15530. */
  15531. this.onDisposeObservable = new BABYLON.Observable();
  15532. /**
  15533. * An event triggered before rendering the scene
  15534. * @type {BABYLON.Observable}
  15535. */
  15536. this.onBeforeRenderObservable = new BABYLON.Observable();
  15537. /**
  15538. * An event triggered after rendering the scene
  15539. * @type {BABYLON.Observable}
  15540. */
  15541. this.onAfterRenderObservable = new BABYLON.Observable();
  15542. /**
  15543. * An event triggered when the scene is ready
  15544. * @type {BABYLON.Observable}
  15545. */
  15546. this.onReadyObservable = new BABYLON.Observable();
  15547. /**
  15548. * An event triggered before rendering a camera
  15549. * @type {BABYLON.Observable}
  15550. */
  15551. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15552. /**
  15553. * An event triggered after rendering a camera
  15554. * @type {BABYLON.Observable}
  15555. */
  15556. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15557. /**
  15558. * An event triggered when a camera is created
  15559. * @type {BABYLON.Observable}
  15560. */
  15561. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15562. /**
  15563. * An event triggered when a camera is removed
  15564. * @type {BABYLON.Observable}
  15565. */
  15566. this.onCameraRemovedObservable = new BABYLON.Observable();
  15567. /**
  15568. * An event triggered when a light is created
  15569. * @type {BABYLON.Observable}
  15570. */
  15571. this.onNewLightAddedObservable = new BABYLON.Observable();
  15572. /**
  15573. * An event triggered when a light is removed
  15574. * @type {BABYLON.Observable}
  15575. */
  15576. this.onLightRemovedObservable = new BABYLON.Observable();
  15577. /**
  15578. * An event triggered when a geometry is created
  15579. * @type {BABYLON.Observable}
  15580. */
  15581. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15582. /**
  15583. * An event triggered when a geometry is removed
  15584. * @type {BABYLON.Observable}
  15585. */
  15586. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15587. /**
  15588. * An event triggered when a mesh is created
  15589. * @type {BABYLON.Observable}
  15590. */
  15591. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15592. /**
  15593. * An event triggered when a mesh is removed
  15594. * @type {BABYLON.Observable}
  15595. */
  15596. this.onMeshRemovedObservable = new BABYLON.Observable();
  15597. // Animations
  15598. this.animations = [];
  15599. /**
  15600. * 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).
  15601. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15602. */
  15603. this.onPrePointerObservable = new BABYLON.Observable();
  15604. /**
  15605. * Observable event triggered each time an input event is received from the rendering canvas
  15606. */
  15607. this.onPointerObservable = new BABYLON.Observable();
  15608. 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
  15609. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15610. this._startingPointerTime = 0;
  15611. // Fog
  15612. /**
  15613. * is fog enabled on this scene.
  15614. * @type {boolean}
  15615. */
  15616. this.fogEnabled = true;
  15617. this.fogMode = Scene.FOGMODE_NONE;
  15618. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15619. this.fogDensity = 0.1;
  15620. this.fogStart = 0;
  15621. this.fogEnd = 1000.0;
  15622. // Lights
  15623. /**
  15624. * is shadow enabled on this scene.
  15625. * @type {boolean}
  15626. */
  15627. this.shadowsEnabled = true;
  15628. /**
  15629. * is light enabled on this scene.
  15630. * @type {boolean}
  15631. */
  15632. this.lightsEnabled = true;
  15633. /**
  15634. * All of the lights added to this scene.
  15635. * @see BABYLON.Light
  15636. * @type {BABYLON.Light[]}
  15637. */
  15638. this.lights = new Array();
  15639. // Cameras
  15640. /**
  15641. * All of the cameras added to this scene.
  15642. * @see BABYLON.Camera
  15643. * @type {BABYLON.Camera[]}
  15644. */
  15645. this.cameras = new Array();
  15646. this.activeCameras = new Array();
  15647. // Meshes
  15648. /**
  15649. * All of the (abstract) meshes added to this scene.
  15650. * @see BABYLON.AbstractMesh
  15651. * @type {BABYLON.AbstractMesh[]}
  15652. */
  15653. this.meshes = new Array();
  15654. // Geometries
  15655. this._geometries = new Array();
  15656. this.materials = new Array();
  15657. this.multiMaterials = new Array();
  15658. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15659. // Textures
  15660. this.texturesEnabled = true;
  15661. this.textures = new Array();
  15662. // Particles
  15663. this.particlesEnabled = true;
  15664. this.particleSystems = new Array();
  15665. // Sprites
  15666. this.spritesEnabled = true;
  15667. this.spriteManagers = new Array();
  15668. // Layers
  15669. this.layers = new Array();
  15670. // Skeletons
  15671. this.skeletonsEnabled = true;
  15672. this.skeletons = new Array();
  15673. // Lens flares
  15674. this.lensFlaresEnabled = true;
  15675. this.lensFlareSystems = new Array();
  15676. // Collisions
  15677. this.collisionsEnabled = true;
  15678. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15679. // Postprocesses
  15680. this.postProcessesEnabled = true;
  15681. // Customs render targets
  15682. this.renderTargetsEnabled = true;
  15683. this.dumpNextRenderTargets = false;
  15684. this.customRenderTargets = new Array();
  15685. // Imported meshes
  15686. this.importedMeshesFiles = new Array();
  15687. // Probes
  15688. this.probesEnabled = true;
  15689. this.reflectionProbes = new Array();
  15690. this._actionManagers = new Array();
  15691. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15692. // Procedural textures
  15693. this.proceduralTexturesEnabled = true;
  15694. this._proceduralTextures = new Array();
  15695. this.soundTracks = new Array();
  15696. this._audioEnabled = true;
  15697. this._headphone = false;
  15698. // Performance counters
  15699. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15700. this._totalLightsCounter = new BABYLON.PerfCounter();
  15701. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15702. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15703. this._totalVertices = new BABYLON.PerfCounter();
  15704. this._activeIndices = new BABYLON.PerfCounter();
  15705. this._activeParticles = new BABYLON.PerfCounter();
  15706. this._lastFrameDuration = new BABYLON.PerfCounter();
  15707. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15708. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15709. this._particlesDuration = new BABYLON.PerfCounter();
  15710. this._renderDuration = new BABYLON.PerfCounter();
  15711. this._spritesDuration = new BABYLON.PerfCounter();
  15712. this._activeBones = new BABYLON.PerfCounter();
  15713. this._renderId = 0;
  15714. this._executeWhenReadyTimeoutId = -1;
  15715. this._intermediateRendering = false;
  15716. this._toBeDisposed = new BABYLON.SmartArray(256);
  15717. this._pendingData = []; //ANY
  15718. this._activeMeshes = new BABYLON.SmartArray(256);
  15719. this._processedMaterials = new BABYLON.SmartArray(256);
  15720. this._renderTargets = new BABYLON.SmartArray(256);
  15721. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15722. this._activeSkeletons = new BABYLON.SmartArray(32);
  15723. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15724. this._activeAnimatables = new Array();
  15725. this._transformMatrix = BABYLON.Matrix.Zero();
  15726. this._edgesRenderers = new BABYLON.SmartArray(16);
  15727. this._uniqueIdCounter = 0;
  15728. this._engine = engine;
  15729. engine.scenes.push(this);
  15730. this._renderingManager = new BABYLON.RenderingManager(this);
  15731. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15732. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15733. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  15734. if (BABYLON.OutlineRenderer) {
  15735. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15736. }
  15737. this.attachControl();
  15738. if (BABYLON.SoundTrack) {
  15739. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15740. }
  15741. //simplification queue
  15742. if (BABYLON.SimplificationQueue) {
  15743. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15744. }
  15745. //collision coordinator initialization. For now legacy per default.
  15746. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15747. }
  15748. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15749. get: function () {
  15750. return Scene._FOGMODE_NONE;
  15751. },
  15752. enumerable: true,
  15753. configurable: true
  15754. });
  15755. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15756. get: function () {
  15757. return Scene._FOGMODE_EXP;
  15758. },
  15759. enumerable: true,
  15760. configurable: true
  15761. });
  15762. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15763. get: function () {
  15764. return Scene._FOGMODE_EXP2;
  15765. },
  15766. enumerable: true,
  15767. configurable: true
  15768. });
  15769. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15770. get: function () {
  15771. return Scene._FOGMODE_LINEAR;
  15772. },
  15773. enumerable: true,
  15774. configurable: true
  15775. });
  15776. Object.defineProperty(Scene.prototype, "onDispose", {
  15777. set: function (callback) {
  15778. if (this._onDisposeObserver) {
  15779. this.onDisposeObservable.remove(this._onDisposeObserver);
  15780. }
  15781. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15782. },
  15783. enumerable: true,
  15784. configurable: true
  15785. });
  15786. Object.defineProperty(Scene.prototype, "beforeRender", {
  15787. set: function (callback) {
  15788. if (this._onBeforeRenderObserver) {
  15789. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15790. }
  15791. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15792. },
  15793. enumerable: true,
  15794. configurable: true
  15795. });
  15796. Object.defineProperty(Scene.prototype, "afterRender", {
  15797. set: function (callback) {
  15798. if (this._onAfterRenderObserver) {
  15799. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15800. }
  15801. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15802. },
  15803. enumerable: true,
  15804. configurable: true
  15805. });
  15806. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15807. set: function (callback) {
  15808. if (this._onBeforeCameraRenderObserver) {
  15809. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15810. }
  15811. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15812. },
  15813. enumerable: true,
  15814. configurable: true
  15815. });
  15816. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15817. set: function (callback) {
  15818. if (this._onAfterCameraRenderObserver) {
  15819. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15820. }
  15821. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15822. },
  15823. enumerable: true,
  15824. configurable: true
  15825. });
  15826. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15827. get: function () {
  15828. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15829. },
  15830. enumerable: true,
  15831. configurable: true
  15832. });
  15833. Object.defineProperty(Scene.prototype, "debugLayer", {
  15834. // Properties
  15835. get: function () {
  15836. if (!this._debugLayer) {
  15837. this._debugLayer = new BABYLON.DebugLayer(this);
  15838. }
  15839. return this._debugLayer;
  15840. },
  15841. enumerable: true,
  15842. configurable: true
  15843. });
  15844. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15845. get: function () {
  15846. return this._workerCollisions;
  15847. },
  15848. set: function (enabled) {
  15849. enabled = (enabled && !!Worker);
  15850. this._workerCollisions = enabled;
  15851. if (this.collisionCoordinator) {
  15852. this.collisionCoordinator.destroy();
  15853. }
  15854. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15855. this.collisionCoordinator.init(this);
  15856. },
  15857. enumerable: true,
  15858. configurable: true
  15859. });
  15860. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  15861. get: function () {
  15862. return this._selectionOctree;
  15863. },
  15864. enumerable: true,
  15865. configurable: true
  15866. });
  15867. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15868. /**
  15869. * The mesh that is currently under the pointer.
  15870. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15871. */
  15872. get: function () {
  15873. return this._pointerOverMesh;
  15874. },
  15875. enumerable: true,
  15876. configurable: true
  15877. });
  15878. Object.defineProperty(Scene.prototype, "pointerX", {
  15879. /**
  15880. * Current on-screen X position of the pointer
  15881. * @return {number} X position of the pointer
  15882. */
  15883. get: function () {
  15884. return this._pointerX;
  15885. },
  15886. enumerable: true,
  15887. configurable: true
  15888. });
  15889. Object.defineProperty(Scene.prototype, "pointerY", {
  15890. /**
  15891. * Current on-screen Y position of the pointer
  15892. * @return {number} Y position of the pointer
  15893. */
  15894. get: function () {
  15895. return this._pointerY;
  15896. },
  15897. enumerable: true,
  15898. configurable: true
  15899. });
  15900. Scene.prototype.getCachedMaterial = function () {
  15901. return this._cachedMaterial;
  15902. };
  15903. Scene.prototype.getBoundingBoxRenderer = function () {
  15904. return this._boundingBoxRenderer;
  15905. };
  15906. Scene.prototype.getOutlineRenderer = function () {
  15907. return this._outlineRenderer;
  15908. };
  15909. Scene.prototype.getEngine = function () {
  15910. return this._engine;
  15911. };
  15912. Scene.prototype.getTotalVertices = function () {
  15913. return this._totalVertices.current;
  15914. };
  15915. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  15916. get: function () {
  15917. return this._totalVertices;
  15918. },
  15919. enumerable: true,
  15920. configurable: true
  15921. });
  15922. Scene.prototype.getActiveIndices = function () {
  15923. return this._activeIndices.current;
  15924. };
  15925. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  15926. get: function () {
  15927. return this._activeIndices;
  15928. },
  15929. enumerable: true,
  15930. configurable: true
  15931. });
  15932. Scene.prototype.getActiveParticles = function () {
  15933. return this._activeParticles.current;
  15934. };
  15935. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  15936. get: function () {
  15937. return this._activeParticles;
  15938. },
  15939. enumerable: true,
  15940. configurable: true
  15941. });
  15942. Scene.prototype.getActiveBones = function () {
  15943. return this._activeBones.current;
  15944. };
  15945. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  15946. get: function () {
  15947. return this._activeBones;
  15948. },
  15949. enumerable: true,
  15950. configurable: true
  15951. });
  15952. // Stats
  15953. Scene.prototype.getLastFrameDuration = function () {
  15954. return this._lastFrameDuration.current;
  15955. };
  15956. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  15957. get: function () {
  15958. return this._lastFrameDuration;
  15959. },
  15960. enumerable: true,
  15961. configurable: true
  15962. });
  15963. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15964. return this._evaluateActiveMeshesDuration.current;
  15965. };
  15966. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  15967. get: function () {
  15968. return this._evaluateActiveMeshesDuration;
  15969. },
  15970. enumerable: true,
  15971. configurable: true
  15972. });
  15973. Scene.prototype.getActiveMeshes = function () {
  15974. return this._activeMeshes;
  15975. };
  15976. Scene.prototype.getRenderTargetsDuration = function () {
  15977. return this._renderTargetsDuration.current;
  15978. };
  15979. Scene.prototype.getRenderDuration = function () {
  15980. return this._renderDuration.current;
  15981. };
  15982. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  15983. get: function () {
  15984. return this._renderDuration;
  15985. },
  15986. enumerable: true,
  15987. configurable: true
  15988. });
  15989. Scene.prototype.getParticlesDuration = function () {
  15990. return this._particlesDuration.current;
  15991. };
  15992. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  15993. get: function () {
  15994. return this._particlesDuration;
  15995. },
  15996. enumerable: true,
  15997. configurable: true
  15998. });
  15999. Scene.prototype.getSpritesDuration = function () {
  16000. return this._spritesDuration.current;
  16001. };
  16002. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16003. get: function () {
  16004. return this._spritesDuration;
  16005. },
  16006. enumerable: true,
  16007. configurable: true
  16008. });
  16009. Scene.prototype.getAnimationRatio = function () {
  16010. return this._animationRatio;
  16011. };
  16012. Scene.prototype.getRenderId = function () {
  16013. return this._renderId;
  16014. };
  16015. Scene.prototype.incrementRenderId = function () {
  16016. this._renderId++;
  16017. };
  16018. Scene.prototype._updatePointerPosition = function (evt) {
  16019. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16020. this._pointerX = evt.clientX - canvasRect.left;
  16021. this._pointerY = evt.clientY - canvasRect.top;
  16022. this._unTranslatedPointerX = this._pointerX;
  16023. this._unTranslatedPointerY = this._pointerY;
  16024. if (this.cameraToUseForPointers) {
  16025. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16026. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16027. }
  16028. };
  16029. // Pointers handling
  16030. /**
  16031. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16032. * @param attachUp defines if you want to attach events to pointerup
  16033. * @param attachDown defines if you want to attach events to pointerdown
  16034. * @param attachMove defines if you want to attach events to pointermove
  16035. */
  16036. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16037. var _this = this;
  16038. if (attachUp === void 0) { attachUp = true; }
  16039. if (attachDown === void 0) { attachDown = true; }
  16040. if (attachMove === void 0) { attachMove = true; }
  16041. var spritePredicate = function (sprite) {
  16042. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16043. };
  16044. this._onPointerMove = function (evt) {
  16045. _this._updatePointerPosition(evt);
  16046. // PreObservable support
  16047. if (_this.onPrePointerObservable.hasObservers()) {
  16048. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16049. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16050. _this.onPrePointerObservable.notifyObservers(pi, type);
  16051. if (pi.skipOnPointerObservable) {
  16052. return;
  16053. }
  16054. }
  16055. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16056. return;
  16057. }
  16058. var canvas = _this._engine.getRenderingCanvas();
  16059. if (!_this.pointerMovePredicate) {
  16060. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  16061. }
  16062. // Meshes
  16063. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16064. if (pickResult.hit && pickResult.pickedMesh) {
  16065. _this.setPointerOverSprite(null);
  16066. _this.setPointerOverMesh(pickResult.pickedMesh);
  16067. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16068. canvas.style.cursor = _this.hoverCursor;
  16069. }
  16070. else {
  16071. canvas.style.cursor = "";
  16072. }
  16073. }
  16074. else {
  16075. _this.setPointerOverMesh(null);
  16076. // Sprites
  16077. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16078. if (pickResult.hit && pickResult.pickedSprite) {
  16079. canvas.style.cursor = _this.hoverCursor;
  16080. _this.setPointerOverSprite(pickResult.pickedSprite);
  16081. }
  16082. else {
  16083. _this.setPointerOverSprite(null);
  16084. // Restore pointer
  16085. canvas.style.cursor = "";
  16086. }
  16087. }
  16088. if (_this.onPointerMove) {
  16089. _this.onPointerMove(evt, pickResult);
  16090. }
  16091. if (_this.onPointerObservable.hasObservers()) {
  16092. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16093. var pi = new PointerInfo(type, evt, pickResult);
  16094. _this.onPointerObservable.notifyObservers(pi, type);
  16095. }
  16096. };
  16097. this._onPointerDown = function (evt) {
  16098. _this._updatePointerPosition(evt);
  16099. // PreObservable support
  16100. if (_this.onPrePointerObservable.hasObservers()) {
  16101. var type = PointerEventTypes.POINTERDOWN;
  16102. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16103. _this.onPrePointerObservable.notifyObservers(pi, type);
  16104. if (pi.skipOnPointerObservable) {
  16105. return;
  16106. }
  16107. }
  16108. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16109. return;
  16110. }
  16111. _this._startingPointerPosition.x = _this._pointerX;
  16112. _this._startingPointerPosition.y = _this._pointerY;
  16113. _this._startingPointerTime = new Date().getTime();
  16114. if (!_this.pointerDownPredicate) {
  16115. _this.pointerDownPredicate = function (mesh) {
  16116. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  16117. };
  16118. }
  16119. // Meshes
  16120. _this._pickedDownMesh = null;
  16121. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16122. if (pickResult.hit && pickResult.pickedMesh) {
  16123. if (pickResult.pickedMesh.actionManager) {
  16124. _this._pickedDownMesh = pickResult.pickedMesh;
  16125. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  16126. switch (evt.button) {
  16127. case 0:
  16128. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16129. break;
  16130. case 1:
  16131. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16132. break;
  16133. case 2:
  16134. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16135. break;
  16136. }
  16137. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16138. }
  16139. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16140. var that = _this;
  16141. window.setTimeout(function () {
  16142. 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);
  16143. if (pickResult.hit && pickResult.pickedMesh) {
  16144. if (pickResult.pickedMesh.actionManager) {
  16145. 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)) {
  16146. that._startingPointerTime = 0;
  16147. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16148. }
  16149. }
  16150. }
  16151. }, BABYLON.ActionManager.LongPressDelay);
  16152. }
  16153. }
  16154. }
  16155. if (_this.onPointerDown) {
  16156. _this.onPointerDown(evt, pickResult);
  16157. }
  16158. if (_this.onPointerObservable.hasObservers()) {
  16159. var type = PointerEventTypes.POINTERDOWN;
  16160. var pi = new PointerInfo(type, evt, pickResult);
  16161. _this.onPointerObservable.notifyObservers(pi, type);
  16162. }
  16163. // Sprites
  16164. _this._pickedDownSprite = null;
  16165. if (_this.spriteManagers.length > 0) {
  16166. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16167. if (pickResult.hit && pickResult.pickedSprite) {
  16168. if (pickResult.pickedSprite.actionManager) {
  16169. _this._pickedDownSprite = pickResult.pickedSprite;
  16170. switch (evt.button) {
  16171. case 0:
  16172. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16173. break;
  16174. case 1:
  16175. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16176. break;
  16177. case 2:
  16178. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16179. break;
  16180. }
  16181. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16182. }
  16183. }
  16184. }
  16185. };
  16186. this._onPointerUp = function (evt) {
  16187. _this._updatePointerPosition(evt);
  16188. // PreObservable support
  16189. if (_this.onPrePointerObservable.hasObservers()) {
  16190. var type = PointerEventTypes.POINTERUP;
  16191. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16192. _this.onPrePointerObservable.notifyObservers(pi, type);
  16193. if (pi.skipOnPointerObservable) {
  16194. return;
  16195. }
  16196. }
  16197. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16198. return;
  16199. }
  16200. if (!_this.pointerUpPredicate) {
  16201. _this.pointerUpPredicate = function (mesh) {
  16202. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  16203. };
  16204. }
  16205. // Meshes
  16206. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  16207. if (pickResult.hit && pickResult.pickedMesh) {
  16208. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  16209. if (_this.onPointerPick) {
  16210. _this.onPointerPick(evt, pickResult);
  16211. }
  16212. if (_this.onPointerObservable.hasObservers()) {
  16213. var type = PointerEventTypes.POINTERPICK;
  16214. var pi = new PointerInfo(type, evt, pickResult);
  16215. _this.onPointerObservable.notifyObservers(pi, type);
  16216. }
  16217. }
  16218. if (pickResult.pickedMesh.actionManager) {
  16219. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16220. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16221. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16222. }
  16223. }
  16224. }
  16225. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  16226. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  16227. }
  16228. if (_this.onPointerUp) {
  16229. _this.onPointerUp(evt, pickResult);
  16230. }
  16231. if (_this.onPointerObservable.hasObservers()) {
  16232. var type = PointerEventTypes.POINTERUP;
  16233. var pi = new PointerInfo(type, evt, pickResult);
  16234. _this.onPointerObservable.notifyObservers(pi, type);
  16235. }
  16236. _this._startingPointerTime = 0;
  16237. // Sprites
  16238. if (_this.spriteManagers.length > 0) {
  16239. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16240. if (pickResult.hit && pickResult.pickedSprite) {
  16241. if (pickResult.pickedSprite.actionManager) {
  16242. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16243. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16244. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16245. }
  16246. }
  16247. }
  16248. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  16249. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  16250. }
  16251. }
  16252. };
  16253. this._onKeyDown = function (evt) {
  16254. if (_this.actionManager) {
  16255. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16256. }
  16257. };
  16258. this._onKeyUp = function (evt) {
  16259. if (_this.actionManager) {
  16260. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16261. }
  16262. };
  16263. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16264. var canvas = this._engine.getRenderingCanvas();
  16265. if (attachMove) {
  16266. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16267. // Wheel
  16268. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16269. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16270. }
  16271. if (attachDown) {
  16272. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16273. }
  16274. if (attachUp) {
  16275. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16276. }
  16277. canvas.tabIndex = 1;
  16278. canvas.addEventListener("keydown", this._onKeyDown, false);
  16279. canvas.addEventListener("keyup", this._onKeyUp, false);
  16280. };
  16281. Scene.prototype.detachControl = function () {
  16282. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16283. var canvas = this._engine.getRenderingCanvas();
  16284. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16285. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16286. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16287. // Wheel
  16288. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16289. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16290. canvas.removeEventListener("keydown", this._onKeyDown);
  16291. canvas.removeEventListener("keyup", this._onKeyUp);
  16292. };
  16293. // Ready
  16294. Scene.prototype.isReady = function () {
  16295. if (this._pendingData.length > 0) {
  16296. return false;
  16297. }
  16298. var index;
  16299. for (index = 0; index < this._geometries.length; index++) {
  16300. var geometry = this._geometries[index];
  16301. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16302. return false;
  16303. }
  16304. }
  16305. for (index = 0; index < this.meshes.length; index++) {
  16306. var mesh = this.meshes[index];
  16307. if (!mesh.isReady()) {
  16308. return false;
  16309. }
  16310. var mat = mesh.material;
  16311. if (mat) {
  16312. if (!mat.isReady(mesh)) {
  16313. return false;
  16314. }
  16315. }
  16316. }
  16317. return true;
  16318. };
  16319. Scene.prototype.resetCachedMaterial = function () {
  16320. this._cachedMaterial = null;
  16321. };
  16322. Scene.prototype.registerBeforeRender = function (func) {
  16323. this.onBeforeRenderObservable.add(func);
  16324. };
  16325. Scene.prototype.unregisterBeforeRender = function (func) {
  16326. this.onBeforeRenderObservable.removeCallback(func);
  16327. };
  16328. Scene.prototype.registerAfterRender = function (func) {
  16329. this.onAfterRenderObservable.add(func);
  16330. };
  16331. Scene.prototype.unregisterAfterRender = function (func) {
  16332. this.onAfterRenderObservable.removeCallback(func);
  16333. };
  16334. Scene.prototype._addPendingData = function (data) {
  16335. this._pendingData.push(data);
  16336. };
  16337. Scene.prototype._removePendingData = function (data) {
  16338. var index = this._pendingData.indexOf(data);
  16339. if (index !== -1) {
  16340. this._pendingData.splice(index, 1);
  16341. }
  16342. };
  16343. Scene.prototype.getWaitingItemsCount = function () {
  16344. return this._pendingData.length;
  16345. };
  16346. /**
  16347. * Registers a function to be executed when the scene is ready.
  16348. * @param {Function} func - the function to be executed.
  16349. */
  16350. Scene.prototype.executeWhenReady = function (func) {
  16351. var _this = this;
  16352. this.onReadyObservable.add(func);
  16353. if (this._executeWhenReadyTimeoutId !== -1) {
  16354. return;
  16355. }
  16356. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16357. _this._checkIsReady();
  16358. }, 150);
  16359. };
  16360. Scene.prototype._checkIsReady = function () {
  16361. var _this = this;
  16362. if (this.isReady()) {
  16363. this.onReadyObservable.notifyObservers(this);
  16364. this.onReadyObservable.clear();
  16365. this._executeWhenReadyTimeoutId = -1;
  16366. return;
  16367. }
  16368. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16369. _this._checkIsReady();
  16370. }, 150);
  16371. };
  16372. // Animations
  16373. /**
  16374. * Will start the animation sequence of a given target
  16375. * @param target - the target
  16376. * @param {number} from - from which frame should animation start
  16377. * @param {number} to - till which frame should animation run.
  16378. * @param {boolean} [loop] - should the animation loop
  16379. * @param {number} [speedRatio] - the speed in which to run the animation
  16380. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16381. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16382. * @return {BABYLON.Animatable} the animatable object created for this animation
  16383. * @see BABYLON.Animatable
  16384. * @see http://doc.babylonjs.com/page.php?p=22081
  16385. */
  16386. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16387. if (speedRatio === void 0) { speedRatio = 1.0; }
  16388. this.stopAnimation(target);
  16389. if (!animatable) {
  16390. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16391. }
  16392. // Local animations
  16393. if (target.animations) {
  16394. animatable.appendAnimations(target, target.animations);
  16395. }
  16396. // Children animations
  16397. if (target.getAnimatables) {
  16398. var animatables = target.getAnimatables();
  16399. for (var index = 0; index < animatables.length; index++) {
  16400. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16401. }
  16402. }
  16403. animatable.reset();
  16404. return animatable;
  16405. };
  16406. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16407. if (speedRatio === undefined) {
  16408. speedRatio = 1.0;
  16409. }
  16410. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16411. return animatable;
  16412. };
  16413. Scene.prototype.getAnimatableByTarget = function (target) {
  16414. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16415. if (this._activeAnimatables[index].target === target) {
  16416. return this._activeAnimatables[index];
  16417. }
  16418. }
  16419. return null;
  16420. };
  16421. Object.defineProperty(Scene.prototype, "Animatables", {
  16422. get: function () {
  16423. return this._activeAnimatables;
  16424. },
  16425. enumerable: true,
  16426. configurable: true
  16427. });
  16428. /**
  16429. * Will stop the animation of the given target
  16430. * @param target - the target
  16431. * @see beginAnimation
  16432. */
  16433. Scene.prototype.stopAnimation = function (target) {
  16434. var animatable = this.getAnimatableByTarget(target);
  16435. if (animatable) {
  16436. animatable.stop();
  16437. }
  16438. };
  16439. Scene.prototype._animate = function () {
  16440. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16441. return;
  16442. }
  16443. if (!this._animationStartDate) {
  16444. if (this._pendingData.length > 0) {
  16445. return;
  16446. }
  16447. this._animationStartDate = BABYLON.Tools.Now;
  16448. }
  16449. // Getting time
  16450. var now = BABYLON.Tools.Now;
  16451. var delay = now - this._animationStartDate;
  16452. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16453. this._activeAnimatables[index]._animate(delay);
  16454. }
  16455. };
  16456. // Matrix
  16457. Scene.prototype.getViewMatrix = function () {
  16458. return this._viewMatrix;
  16459. };
  16460. Scene.prototype.getProjectionMatrix = function () {
  16461. return this._projectionMatrix;
  16462. };
  16463. Scene.prototype.getTransformMatrix = function () {
  16464. return this._transformMatrix;
  16465. };
  16466. Scene.prototype.setTransformMatrix = function (view, projection) {
  16467. this._viewMatrix = view;
  16468. this._projectionMatrix = projection;
  16469. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16470. // Update frustum
  16471. if (!this._frustumPlanes) {
  16472. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16473. }
  16474. else {
  16475. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16476. }
  16477. };
  16478. // Methods
  16479. Scene.prototype.addMesh = function (newMesh) {
  16480. newMesh.uniqueId = this._uniqueIdCounter++;
  16481. var position = this.meshes.push(newMesh);
  16482. //notify the collision coordinator
  16483. this.collisionCoordinator.onMeshAdded(newMesh);
  16484. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16485. };
  16486. Scene.prototype.removeMesh = function (toRemove) {
  16487. var index = this.meshes.indexOf(toRemove);
  16488. if (index !== -1) {
  16489. // Remove from the scene if mesh found
  16490. this.meshes.splice(index, 1);
  16491. }
  16492. //notify the collision coordinator
  16493. this.collisionCoordinator.onMeshRemoved(toRemove);
  16494. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16495. return index;
  16496. };
  16497. Scene.prototype.removeSkeleton = function (toRemove) {
  16498. var index = this.skeletons.indexOf(toRemove);
  16499. if (index !== -1) {
  16500. // Remove from the scene if mesh found
  16501. this.skeletons.splice(index, 1);
  16502. }
  16503. return index;
  16504. };
  16505. Scene.prototype.removeLight = function (toRemove) {
  16506. var index = this.lights.indexOf(toRemove);
  16507. if (index !== -1) {
  16508. // Remove from the scene if mesh found
  16509. this.lights.splice(index, 1);
  16510. }
  16511. this.onLightRemovedObservable.notifyObservers(toRemove);
  16512. return index;
  16513. };
  16514. Scene.prototype.removeCamera = function (toRemove) {
  16515. var index = this.cameras.indexOf(toRemove);
  16516. if (index !== -1) {
  16517. // Remove from the scene if mesh found
  16518. this.cameras.splice(index, 1);
  16519. }
  16520. // Remove from activeCameras
  16521. var index2 = this.activeCameras.indexOf(toRemove);
  16522. if (index2 !== -1) {
  16523. // Remove from the scene if mesh found
  16524. this.activeCameras.splice(index2, 1);
  16525. }
  16526. // Reset the activeCamera
  16527. if (this.activeCamera === toRemove) {
  16528. if (this.cameras.length > 0) {
  16529. this.activeCamera = this.cameras[0];
  16530. }
  16531. else {
  16532. this.activeCamera = null;
  16533. }
  16534. }
  16535. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16536. return index;
  16537. };
  16538. Scene.prototype.addLight = function (newLight) {
  16539. newLight.uniqueId = this._uniqueIdCounter++;
  16540. var position = this.lights.push(newLight);
  16541. this.onNewLightAddedObservable.notifyObservers(newLight);
  16542. };
  16543. Scene.prototype.addCamera = function (newCamera) {
  16544. newCamera.uniqueId = this._uniqueIdCounter++;
  16545. var position = this.cameras.push(newCamera);
  16546. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16547. };
  16548. /**
  16549. * Switch active camera
  16550. * @param {Camera} newCamera - new active camera
  16551. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16552. */
  16553. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16554. if (attachControl === void 0) { attachControl = true; }
  16555. var canvas = this._engine.getRenderingCanvas();
  16556. this.activeCamera.detachControl(canvas);
  16557. this.activeCamera = newCamera;
  16558. if (attachControl) {
  16559. newCamera.attachControl(canvas);
  16560. }
  16561. };
  16562. /**
  16563. * sets the active camera of the scene using its ID
  16564. * @param {string} id - the camera's ID
  16565. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16566. * @see activeCamera
  16567. */
  16568. Scene.prototype.setActiveCameraByID = function (id) {
  16569. var camera = this.getCameraByID(id);
  16570. if (camera) {
  16571. this.activeCamera = camera;
  16572. return camera;
  16573. }
  16574. return null;
  16575. };
  16576. /**
  16577. * sets the active camera of the scene using its name
  16578. * @param {string} name - the camera's name
  16579. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16580. * @see activeCamera
  16581. */
  16582. Scene.prototype.setActiveCameraByName = function (name) {
  16583. var camera = this.getCameraByName(name);
  16584. if (camera) {
  16585. this.activeCamera = camera;
  16586. return camera;
  16587. }
  16588. return null;
  16589. };
  16590. /**
  16591. * get a material using its id
  16592. * @param {string} the material's ID
  16593. * @return {BABYLON.Material|null} the material or null if none found.
  16594. */
  16595. Scene.prototype.getMaterialByID = function (id) {
  16596. for (var index = 0; index < this.materials.length; index++) {
  16597. if (this.materials[index].id === id) {
  16598. return this.materials[index];
  16599. }
  16600. }
  16601. return null;
  16602. };
  16603. /**
  16604. * get a material using its name
  16605. * @param {string} the material's name
  16606. * @return {BABYLON.Material|null} the material or null if none found.
  16607. */
  16608. Scene.prototype.getMaterialByName = function (name) {
  16609. for (var index = 0; index < this.materials.length; index++) {
  16610. if (this.materials[index].name === name) {
  16611. return this.materials[index];
  16612. }
  16613. }
  16614. return null;
  16615. };
  16616. Scene.prototype.getLensFlareSystemByName = function (name) {
  16617. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16618. if (this.lensFlareSystems[index].name === name) {
  16619. return this.lensFlareSystems[index];
  16620. }
  16621. }
  16622. return null;
  16623. };
  16624. Scene.prototype.getLensFlareSystemByID = function (id) {
  16625. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16626. if (this.lensFlareSystems[index].id === id) {
  16627. return this.lensFlareSystems[index];
  16628. }
  16629. }
  16630. return null;
  16631. };
  16632. Scene.prototype.getCameraByID = function (id) {
  16633. for (var index = 0; index < this.cameras.length; index++) {
  16634. if (this.cameras[index].id === id) {
  16635. return this.cameras[index];
  16636. }
  16637. }
  16638. return null;
  16639. };
  16640. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16641. for (var index = 0; index < this.cameras.length; index++) {
  16642. if (this.cameras[index].uniqueId === uniqueId) {
  16643. return this.cameras[index];
  16644. }
  16645. }
  16646. return null;
  16647. };
  16648. /**
  16649. * get a camera using its name
  16650. * @param {string} the camera's name
  16651. * @return {BABYLON.Camera|null} the camera or null if none found.
  16652. */
  16653. Scene.prototype.getCameraByName = function (name) {
  16654. for (var index = 0; index < this.cameras.length; index++) {
  16655. if (this.cameras[index].name === name) {
  16656. return this.cameras[index];
  16657. }
  16658. }
  16659. return null;
  16660. };
  16661. /**
  16662. * get a bone using its id
  16663. * @param {string} the bone's id
  16664. * @return {BABYLON.Bone|null} the bone or null if not found
  16665. */
  16666. Scene.prototype.getBoneByID = function (id) {
  16667. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16668. var skeleton = this.skeletons[skeletonIndex];
  16669. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16670. if (skeleton.bones[boneIndex].id === id) {
  16671. return skeleton.bones[boneIndex];
  16672. }
  16673. }
  16674. }
  16675. return null;
  16676. };
  16677. /**
  16678. * get a bone using its id
  16679. * @param {string} the bone's name
  16680. * @return {BABYLON.Bone|null} the bone or null if not found
  16681. */
  16682. Scene.prototype.getBoneByName = function (name) {
  16683. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16684. var skeleton = this.skeletons[skeletonIndex];
  16685. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16686. if (skeleton.bones[boneIndex].name === name) {
  16687. return skeleton.bones[boneIndex];
  16688. }
  16689. }
  16690. }
  16691. return null;
  16692. };
  16693. /**
  16694. * get a light node using its name
  16695. * @param {string} the light's name
  16696. * @return {BABYLON.Light|null} the light or null if none found.
  16697. */
  16698. Scene.prototype.getLightByName = function (name) {
  16699. for (var index = 0; index < this.lights.length; index++) {
  16700. if (this.lights[index].name === name) {
  16701. return this.lights[index];
  16702. }
  16703. }
  16704. return null;
  16705. };
  16706. /**
  16707. * get a light node using its ID
  16708. * @param {string} the light's id
  16709. * @return {BABYLON.Light|null} the light or null if none found.
  16710. */
  16711. Scene.prototype.getLightByID = function (id) {
  16712. for (var index = 0; index < this.lights.length; index++) {
  16713. if (this.lights[index].id === id) {
  16714. return this.lights[index];
  16715. }
  16716. }
  16717. return null;
  16718. };
  16719. /**
  16720. * get a light node using its scene-generated unique ID
  16721. * @param {number} the light's unique id
  16722. * @return {BABYLON.Light|null} the light or null if none found.
  16723. */
  16724. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  16725. for (var index = 0; index < this.lights.length; index++) {
  16726. if (this.lights[index].uniqueId === uniqueId) {
  16727. return this.lights[index];
  16728. }
  16729. }
  16730. return null;
  16731. };
  16732. /**
  16733. * get a particle system by id
  16734. * @param id {number} the particle system id
  16735. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16736. */
  16737. Scene.prototype.getParticleSystemByID = function (id) {
  16738. for (var index = 0; index < this.particleSystems.length; index++) {
  16739. if (this.particleSystems[index].id === id) {
  16740. return this.particleSystems[index];
  16741. }
  16742. }
  16743. return null;
  16744. };
  16745. /**
  16746. * get a geometry using its ID
  16747. * @param {string} the geometry's id
  16748. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  16749. */
  16750. Scene.prototype.getGeometryByID = function (id) {
  16751. for (var index = 0; index < this._geometries.length; index++) {
  16752. if (this._geometries[index].id === id) {
  16753. return this._geometries[index];
  16754. }
  16755. }
  16756. return null;
  16757. };
  16758. /**
  16759. * add a new geometry to this scene.
  16760. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  16761. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  16762. * @return {boolean} was the geometry added or not
  16763. */
  16764. Scene.prototype.pushGeometry = function (geometry, force) {
  16765. if (!force && this.getGeometryByID(geometry.id)) {
  16766. return false;
  16767. }
  16768. this._geometries.push(geometry);
  16769. //notify the collision coordinator
  16770. this.collisionCoordinator.onGeometryAdded(geometry);
  16771. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  16772. return true;
  16773. };
  16774. /**
  16775. * Removes an existing geometry
  16776. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  16777. * @return {boolean} was the geometry removed or not
  16778. */
  16779. Scene.prototype.removeGeometry = function (geometry) {
  16780. var index = this._geometries.indexOf(geometry);
  16781. if (index > -1) {
  16782. this._geometries.splice(index, 1);
  16783. //notify the collision coordinator
  16784. this.collisionCoordinator.onGeometryDeleted(geometry);
  16785. this.onGeometryRemovedObservable.notifyObservers(geometry);
  16786. return true;
  16787. }
  16788. return false;
  16789. };
  16790. Scene.prototype.getGeometries = function () {
  16791. return this._geometries;
  16792. };
  16793. /**
  16794. * Get the first added mesh found of a given ID
  16795. * @param {string} id - the id to search for
  16796. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16797. */
  16798. Scene.prototype.getMeshByID = function (id) {
  16799. for (var index = 0; index < this.meshes.length; index++) {
  16800. if (this.meshes[index].id === id) {
  16801. return this.meshes[index];
  16802. }
  16803. }
  16804. return null;
  16805. };
  16806. Scene.prototype.getMeshesByID = function (id) {
  16807. return this.meshes.filter(function (m) {
  16808. return m.id === id;
  16809. });
  16810. };
  16811. /**
  16812. * Get a mesh with its auto-generated unique id
  16813. * @param {number} uniqueId - the unique id to search for
  16814. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16815. */
  16816. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  16817. for (var index = 0; index < this.meshes.length; index++) {
  16818. if (this.meshes[index].uniqueId === uniqueId) {
  16819. return this.meshes[index];
  16820. }
  16821. }
  16822. return null;
  16823. };
  16824. /**
  16825. * Get a the last added mesh found of a given ID
  16826. * @param {string} id - the id to search for
  16827. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16828. */
  16829. Scene.prototype.getLastMeshByID = function (id) {
  16830. for (var index = this.meshes.length - 1; index >= 0; index--) {
  16831. if (this.meshes[index].id === id) {
  16832. return this.meshes[index];
  16833. }
  16834. }
  16835. return null;
  16836. };
  16837. /**
  16838. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  16839. * @param {string} id - the id to search for
  16840. * @return {BABYLON.Node|null} the node found or null if not found at all.
  16841. */
  16842. Scene.prototype.getLastEntryByID = function (id) {
  16843. var index;
  16844. for (index = this.meshes.length - 1; index >= 0; index--) {
  16845. if (this.meshes[index].id === id) {
  16846. return this.meshes[index];
  16847. }
  16848. }
  16849. for (index = this.cameras.length - 1; index >= 0; index--) {
  16850. if (this.cameras[index].id === id) {
  16851. return this.cameras[index];
  16852. }
  16853. }
  16854. for (index = this.lights.length - 1; index >= 0; index--) {
  16855. if (this.lights[index].id === id) {
  16856. return this.lights[index];
  16857. }
  16858. }
  16859. return null;
  16860. };
  16861. Scene.prototype.getNodeByID = function (id) {
  16862. var mesh = this.getMeshByID(id);
  16863. if (mesh) {
  16864. return mesh;
  16865. }
  16866. var light = this.getLightByID(id);
  16867. if (light) {
  16868. return light;
  16869. }
  16870. var camera = this.getCameraByID(id);
  16871. if (camera) {
  16872. return camera;
  16873. }
  16874. var bone = this.getBoneByID(id);
  16875. return bone;
  16876. };
  16877. Scene.prototype.getNodeByName = function (name) {
  16878. var mesh = this.getMeshByName(name);
  16879. if (mesh) {
  16880. return mesh;
  16881. }
  16882. var light = this.getLightByName(name);
  16883. if (light) {
  16884. return light;
  16885. }
  16886. var camera = this.getCameraByName(name);
  16887. if (camera) {
  16888. return camera;
  16889. }
  16890. var bone = this.getBoneByName(name);
  16891. return bone;
  16892. };
  16893. Scene.prototype.getMeshByName = function (name) {
  16894. for (var index = 0; index < this.meshes.length; index++) {
  16895. if (this.meshes[index].name === name) {
  16896. return this.meshes[index];
  16897. }
  16898. }
  16899. return null;
  16900. };
  16901. Scene.prototype.getSoundByName = function (name) {
  16902. var index;
  16903. if (BABYLON.AudioEngine) {
  16904. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  16905. if (this.mainSoundTrack.soundCollection[index].name === name) {
  16906. return this.mainSoundTrack.soundCollection[index];
  16907. }
  16908. }
  16909. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  16910. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  16911. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  16912. return this.soundTracks[sdIndex].soundCollection[index];
  16913. }
  16914. }
  16915. }
  16916. }
  16917. return null;
  16918. };
  16919. Scene.prototype.getLastSkeletonByID = function (id) {
  16920. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  16921. if (this.skeletons[index].id === id) {
  16922. return this.skeletons[index];
  16923. }
  16924. }
  16925. return null;
  16926. };
  16927. Scene.prototype.getSkeletonById = function (id) {
  16928. for (var index = 0; index < this.skeletons.length; index++) {
  16929. if (this.skeletons[index].id === id) {
  16930. return this.skeletons[index];
  16931. }
  16932. }
  16933. return null;
  16934. };
  16935. Scene.prototype.getSkeletonByName = function (name) {
  16936. for (var index = 0; index < this.skeletons.length; index++) {
  16937. if (this.skeletons[index].name === name) {
  16938. return this.skeletons[index];
  16939. }
  16940. }
  16941. return null;
  16942. };
  16943. Scene.prototype.isActiveMesh = function (mesh) {
  16944. return (this._activeMeshes.indexOf(mesh) !== -1);
  16945. };
  16946. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  16947. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  16948. var material = subMesh.getMaterial();
  16949. if (mesh.showSubMeshesBoundingBox) {
  16950. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  16951. }
  16952. if (material) {
  16953. // Render targets
  16954. if (material.getRenderTargetTextures) {
  16955. if (this._processedMaterials.indexOf(material) === -1) {
  16956. this._processedMaterials.push(material);
  16957. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  16958. }
  16959. }
  16960. // Dispatch
  16961. this._activeIndices.addCount(subMesh.indexCount, false);
  16962. this._renderingManager.dispatch(subMesh);
  16963. }
  16964. }
  16965. };
  16966. Scene.prototype._isInIntermediateRendering = function () {
  16967. return this._intermediateRendering;
  16968. };
  16969. Scene.prototype._evaluateActiveMeshes = function () {
  16970. this.activeCamera._activeMeshes.reset();
  16971. this._activeMeshes.reset();
  16972. this._renderingManager.reset();
  16973. this._processedMaterials.reset();
  16974. this._activeParticleSystems.reset();
  16975. this._activeSkeletons.reset();
  16976. this._softwareSkinnedMeshes.reset();
  16977. this._boundingBoxRenderer.reset();
  16978. this._edgesRenderers.reset();
  16979. // Meshes
  16980. var meshes;
  16981. var len;
  16982. if (this._selectionOctree) {
  16983. var selection = this._selectionOctree.select(this._frustumPlanes);
  16984. meshes = selection.data;
  16985. len = selection.length;
  16986. }
  16987. else {
  16988. len = this.meshes.length;
  16989. meshes = this.meshes;
  16990. }
  16991. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  16992. var mesh = meshes[meshIndex];
  16993. if (mesh.isBlocked) {
  16994. continue;
  16995. }
  16996. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  16997. if (!mesh.isReady() || !mesh.isEnabled()) {
  16998. continue;
  16999. }
  17000. mesh.computeWorldMatrix();
  17001. // Intersections
  17002. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17003. this._meshesForIntersections.pushNoDuplicate(mesh);
  17004. }
  17005. // Switch to current LOD
  17006. var meshLOD = mesh.getLOD(this.activeCamera);
  17007. if (!meshLOD) {
  17008. continue;
  17009. }
  17010. mesh._preActivate();
  17011. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17012. this._activeMeshes.push(mesh);
  17013. this.activeCamera._activeMeshes.push(mesh);
  17014. mesh._activate(this._renderId);
  17015. this._activeMesh(mesh, meshLOD);
  17016. }
  17017. }
  17018. // Particle systems
  17019. this._particlesDuration.beginMonitoring();
  17020. var beforeParticlesDate = BABYLON.Tools.Now;
  17021. if (this.particlesEnabled) {
  17022. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17023. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17024. var particleSystem = this.particleSystems[particleIndex];
  17025. if (!particleSystem.isStarted()) {
  17026. continue;
  17027. }
  17028. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17029. this._activeParticleSystems.push(particleSystem);
  17030. particleSystem.animate();
  17031. }
  17032. }
  17033. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17034. }
  17035. this._particlesDuration.endMonitoring(false);
  17036. };
  17037. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17038. if (mesh.skeleton && this.skeletonsEnabled) {
  17039. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17040. mesh.skeleton.prepare();
  17041. }
  17042. if (!mesh.computeBonesUsingShaders) {
  17043. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17044. }
  17045. }
  17046. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17047. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17048. }
  17049. if (sourceMesh._edgesRenderer) {
  17050. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  17051. }
  17052. if (mesh && mesh.subMeshes) {
  17053. // Submeshes Octrees
  17054. var len;
  17055. var subMeshes;
  17056. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17057. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17058. len = intersections.length;
  17059. subMeshes = intersections.data;
  17060. }
  17061. else {
  17062. subMeshes = mesh.subMeshes;
  17063. len = subMeshes.length;
  17064. }
  17065. for (var subIndex = 0; subIndex < len; subIndex++) {
  17066. var subMesh = subMeshes[subIndex];
  17067. this._evaluateSubMesh(subMesh, mesh);
  17068. }
  17069. }
  17070. };
  17071. Scene.prototype.updateTransformMatrix = function (force) {
  17072. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17073. };
  17074. Scene.prototype._renderForCamera = function (camera) {
  17075. var engine = this._engine;
  17076. var startTime = BABYLON.Tools.Now;
  17077. this.activeCamera = camera;
  17078. if (!this.activeCamera)
  17079. throw new Error("Active camera not set");
  17080. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17081. // Viewport
  17082. engine.setViewport(this.activeCamera.viewport);
  17083. // Camera
  17084. this.resetCachedMaterial();
  17085. this._renderId++;
  17086. this.updateTransformMatrix();
  17087. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17088. // Meshes
  17089. this._evaluateActiveMeshesDuration.beginMonitoring();
  17090. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17091. this._evaluateActiveMeshes();
  17092. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17093. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17094. // Software skinning
  17095. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17096. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17097. mesh.applySkeleton(mesh.skeleton);
  17098. }
  17099. // Render targets
  17100. this._renderTargetsDuration.beginMonitoring();
  17101. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17102. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17103. this._intermediateRendering = true;
  17104. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17105. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17106. var renderTarget = this._renderTargets.data[renderIndex];
  17107. if (renderTarget._shouldRender()) {
  17108. this._renderId++;
  17109. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17110. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17111. }
  17112. }
  17113. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17114. this._intermediateRendering = false;
  17115. this._renderId++;
  17116. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17117. }
  17118. this._renderTargetsDuration.endMonitoring(false);
  17119. // Prepare Frame
  17120. this.postProcessManager._prepareFrame();
  17121. this._renderDuration.beginMonitoring();
  17122. // Backgrounds
  17123. var layerIndex;
  17124. var layer;
  17125. if (this.layers.length) {
  17126. engine.setDepthBuffer(false);
  17127. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17128. layer = this.layers[layerIndex];
  17129. if (layer.isBackground) {
  17130. layer.render();
  17131. }
  17132. }
  17133. engine.setDepthBuffer(true);
  17134. }
  17135. // Render
  17136. BABYLON.Tools.StartPerformanceCounter("Main render");
  17137. this._renderingManager.render(null, null, true, true);
  17138. BABYLON.Tools.EndPerformanceCounter("Main render");
  17139. // Bounding boxes
  17140. this._boundingBoxRenderer.render();
  17141. // Edges
  17142. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17143. this._edgesRenderers.data[edgesRendererIndex].render();
  17144. }
  17145. // Lens flares
  17146. if (this.lensFlaresEnabled) {
  17147. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17148. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17149. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17150. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17151. lensFlareSystem.render();
  17152. }
  17153. }
  17154. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17155. }
  17156. // Foregrounds
  17157. if (this.layers.length) {
  17158. engine.setDepthBuffer(false);
  17159. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17160. layer = this.layers[layerIndex];
  17161. if (!layer.isBackground) {
  17162. layer.render();
  17163. }
  17164. }
  17165. engine.setDepthBuffer(true);
  17166. }
  17167. this._renderDuration.endMonitoring(false);
  17168. // Finalize frame
  17169. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17170. // Update camera
  17171. this.activeCamera._updateFromScene();
  17172. // Reset some special arrays
  17173. this._renderTargets.reset();
  17174. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17175. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17176. };
  17177. Scene.prototype._processSubCameras = function (camera) {
  17178. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17179. this._renderForCamera(camera);
  17180. return;
  17181. }
  17182. // rig cameras
  17183. for (var index = 0; index < camera._rigCameras.length; index++) {
  17184. this._renderForCamera(camera._rigCameras[index]);
  17185. }
  17186. this.activeCamera = camera;
  17187. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17188. // Update camera
  17189. this.activeCamera._updateFromScene();
  17190. };
  17191. Scene.prototype._checkIntersections = function () {
  17192. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17193. var sourceMesh = this._meshesForIntersections.data[index];
  17194. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17195. var action = sourceMesh.actionManager.actions[actionIndex];
  17196. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17197. var parameters = action.getTriggerParameter();
  17198. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17199. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17200. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17201. if (areIntersecting && currentIntersectionInProgress === -1) {
  17202. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17203. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17204. sourceMesh._intersectionsInProgress.push(otherMesh);
  17205. }
  17206. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17207. sourceMesh._intersectionsInProgress.push(otherMesh);
  17208. }
  17209. }
  17210. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17211. //They intersected, and now they don't.
  17212. //is this trigger an exit trigger? execute an event.
  17213. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17214. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17215. }
  17216. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17217. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17218. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17219. }
  17220. }
  17221. }
  17222. }
  17223. }
  17224. };
  17225. Scene.prototype.render = function () {
  17226. this._lastFrameDuration.beginMonitoring();
  17227. this._particlesDuration.fetchNewFrame();
  17228. this._spritesDuration.fetchNewFrame();
  17229. this._activeParticles.fetchNewFrame();
  17230. this._renderDuration.fetchNewFrame();
  17231. this._renderTargetsDuration.fetchNewFrame();
  17232. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17233. this._totalVertices.fetchNewFrame();
  17234. this._activeIndices.fetchNewFrame();
  17235. this._activeBones.fetchNewFrame();
  17236. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17237. this._meshesForIntersections.reset();
  17238. this.resetCachedMaterial();
  17239. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17240. // Actions
  17241. if (this.actionManager) {
  17242. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17243. }
  17244. //Simplification Queue
  17245. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17246. this.simplificationQueue.executeNext();
  17247. }
  17248. // Animations
  17249. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17250. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17251. this._animate();
  17252. // Physics
  17253. if (this._physicsEngine) {
  17254. BABYLON.Tools.StartPerformanceCounter("Physics");
  17255. this._physicsEngine._step(deltaTime / 1000.0);
  17256. BABYLON.Tools.EndPerformanceCounter("Physics");
  17257. }
  17258. // Before render
  17259. this.onBeforeRenderObservable.notifyObservers(this);
  17260. // Customs render targets
  17261. this._renderTargetsDuration.beginMonitoring();
  17262. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17263. var engine = this.getEngine();
  17264. var currentActiveCamera = this.activeCamera;
  17265. if (this.renderTargetsEnabled) {
  17266. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17267. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17268. var renderTarget = this.customRenderTargets[customIndex];
  17269. if (renderTarget._shouldRender()) {
  17270. this._renderId++;
  17271. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17272. if (!this.activeCamera)
  17273. throw new Error("Active camera not set");
  17274. // Viewport
  17275. engine.setViewport(this.activeCamera.viewport);
  17276. // Camera
  17277. this.updateTransformMatrix();
  17278. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17279. }
  17280. }
  17281. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17282. this._renderId++;
  17283. }
  17284. if (this.customRenderTargets.length > 0) {
  17285. engine.restoreDefaultFramebuffer();
  17286. }
  17287. this._renderTargetsDuration.endMonitoring();
  17288. this.activeCamera = currentActiveCamera;
  17289. // Procedural textures
  17290. if (this.proceduralTexturesEnabled) {
  17291. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17292. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17293. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17294. if (proceduralTexture._shouldRender()) {
  17295. proceduralTexture.render();
  17296. }
  17297. }
  17298. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17299. }
  17300. // Clear
  17301. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  17302. // Shadows
  17303. if (this.shadowsEnabled) {
  17304. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17305. var light = this.lights[lightIndex];
  17306. var shadowGenerator = light.getShadowGenerator();
  17307. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  17308. this._renderTargets.push(shadowGenerator.getShadowMap());
  17309. }
  17310. }
  17311. }
  17312. // Depth renderer
  17313. if (this._depthRenderer) {
  17314. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17315. }
  17316. // RenderPipeline
  17317. this.postProcessRenderPipelineManager.update();
  17318. // Multi-cameras?
  17319. if (this.activeCameras.length > 0) {
  17320. var currentRenderId = this._renderId;
  17321. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17322. this._renderId = currentRenderId;
  17323. if (cameraIndex > 0) {
  17324. this._engine.clear(0, false, true, true);
  17325. }
  17326. this._processSubCameras(this.activeCameras[cameraIndex]);
  17327. }
  17328. }
  17329. else {
  17330. if (!this.activeCamera) {
  17331. throw new Error("No camera defined");
  17332. }
  17333. this._processSubCameras(this.activeCamera);
  17334. }
  17335. // Intersection checks
  17336. this._checkIntersections();
  17337. // Update the audio listener attached to the camera
  17338. if (BABYLON.AudioEngine) {
  17339. this._updateAudioParameters();
  17340. }
  17341. // After render
  17342. if (this.afterRender) {
  17343. this.afterRender();
  17344. }
  17345. this.onAfterRenderObservable.notifyObservers(this);
  17346. // Cleaning
  17347. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17348. this._toBeDisposed.data[index].dispose();
  17349. this._toBeDisposed[index] = null;
  17350. }
  17351. this._toBeDisposed.reset();
  17352. if (this.dumpNextRenderTargets) {
  17353. this.dumpNextRenderTargets = false;
  17354. }
  17355. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17356. this._lastFrameDuration.endMonitoring();
  17357. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17358. this._totalLightsCounter.addCount(this.lights.length, true);
  17359. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17360. this._totalTexturesCounter.addCount(this.textures.length, true);
  17361. this._activeBones.addCount(0, true);
  17362. this._activeIndices.addCount(0, true);
  17363. this._activeParticles.addCount(0, true);
  17364. };
  17365. Scene.prototype._updateAudioParameters = function () {
  17366. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17367. return;
  17368. }
  17369. var listeningCamera;
  17370. var audioEngine = BABYLON.Engine.audioEngine;
  17371. if (this.activeCameras.length > 0) {
  17372. listeningCamera = this.activeCameras[0];
  17373. }
  17374. else {
  17375. listeningCamera = this.activeCamera;
  17376. }
  17377. if (listeningCamera && audioEngine.canUseWebAudio) {
  17378. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17379. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17380. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17381. cameraDirection.normalize();
  17382. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17383. var i;
  17384. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17385. var sound = this.mainSoundTrack.soundCollection[i];
  17386. if (sound.useCustomAttenuation) {
  17387. sound.updateDistanceFromListener();
  17388. }
  17389. }
  17390. for (i = 0; i < this.soundTracks.length; i++) {
  17391. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17392. sound = this.soundTracks[i].soundCollection[j];
  17393. if (sound.useCustomAttenuation) {
  17394. sound.updateDistanceFromListener();
  17395. }
  17396. }
  17397. }
  17398. }
  17399. };
  17400. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17401. // Audio
  17402. get: function () {
  17403. return this._audioEnabled;
  17404. },
  17405. set: function (value) {
  17406. this._audioEnabled = value;
  17407. if (BABYLON.AudioEngine) {
  17408. if (this._audioEnabled) {
  17409. this._enableAudio();
  17410. }
  17411. else {
  17412. this._disableAudio();
  17413. }
  17414. }
  17415. },
  17416. enumerable: true,
  17417. configurable: true
  17418. });
  17419. Scene.prototype._disableAudio = function () {
  17420. var i;
  17421. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17422. this.mainSoundTrack.soundCollection[i].pause();
  17423. }
  17424. for (i = 0; i < this.soundTracks.length; i++) {
  17425. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17426. this.soundTracks[i].soundCollection[j].pause();
  17427. }
  17428. }
  17429. };
  17430. Scene.prototype._enableAudio = function () {
  17431. var i;
  17432. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17433. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17434. this.mainSoundTrack.soundCollection[i].play();
  17435. }
  17436. }
  17437. for (i = 0; i < this.soundTracks.length; i++) {
  17438. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17439. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17440. this.soundTracks[i].soundCollection[j].play();
  17441. }
  17442. }
  17443. }
  17444. };
  17445. Object.defineProperty(Scene.prototype, "headphone", {
  17446. get: function () {
  17447. return this._headphone;
  17448. },
  17449. set: function (value) {
  17450. this._headphone = value;
  17451. if (BABYLON.AudioEngine) {
  17452. if (this._headphone) {
  17453. this._switchAudioModeForHeadphones();
  17454. }
  17455. else {
  17456. this._switchAudioModeForNormalSpeakers();
  17457. }
  17458. }
  17459. },
  17460. enumerable: true,
  17461. configurable: true
  17462. });
  17463. Scene.prototype._switchAudioModeForHeadphones = function () {
  17464. this.mainSoundTrack.switchPanningModelToHRTF();
  17465. for (var i = 0; i < this.soundTracks.length; i++) {
  17466. this.soundTracks[i].switchPanningModelToHRTF();
  17467. }
  17468. };
  17469. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17470. this.mainSoundTrack.switchPanningModelToEqualPower();
  17471. for (var i = 0; i < this.soundTracks.length; i++) {
  17472. this.soundTracks[i].switchPanningModelToEqualPower();
  17473. }
  17474. };
  17475. Scene.prototype.enableDepthRenderer = function () {
  17476. if (this._depthRenderer) {
  17477. return this._depthRenderer;
  17478. }
  17479. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17480. return this._depthRenderer;
  17481. };
  17482. Scene.prototype.disableDepthRenderer = function () {
  17483. if (!this._depthRenderer) {
  17484. return;
  17485. }
  17486. this._depthRenderer.dispose();
  17487. this._depthRenderer = null;
  17488. };
  17489. Scene.prototype.freezeMaterials = function () {
  17490. for (var i = 0; i < this.materials.length; i++) {
  17491. this.materials[i].freeze();
  17492. }
  17493. };
  17494. Scene.prototype.unfreezeMaterials = function () {
  17495. for (var i = 0; i < this.materials.length; i++) {
  17496. this.materials[i].unfreeze();
  17497. }
  17498. };
  17499. Scene.prototype.dispose = function () {
  17500. this.beforeRender = null;
  17501. this.afterRender = null;
  17502. this.skeletons = [];
  17503. this._boundingBoxRenderer.dispose();
  17504. if (this._depthRenderer) {
  17505. this._depthRenderer.dispose();
  17506. }
  17507. // Debug layer
  17508. if (this._debugLayer) {
  17509. this._debugLayer.hide();
  17510. }
  17511. // Events
  17512. this.onDisposeObservable.notifyObservers(this);
  17513. this.onDisposeObservable.clear();
  17514. this.onBeforeRenderObservable.clear();
  17515. this.onAfterRenderObservable.clear();
  17516. this.detachControl();
  17517. // Release sounds & sounds tracks
  17518. if (BABYLON.AudioEngine) {
  17519. this.disposeSounds();
  17520. }
  17521. // Detach cameras
  17522. var canvas = this._engine.getRenderingCanvas();
  17523. var index;
  17524. for (index = 0; index < this.cameras.length; index++) {
  17525. this.cameras[index].detachControl(canvas);
  17526. }
  17527. // Release lights
  17528. while (this.lights.length) {
  17529. this.lights[0].dispose();
  17530. }
  17531. // Release meshes
  17532. while (this.meshes.length) {
  17533. this.meshes[0].dispose(true);
  17534. }
  17535. // Release cameras
  17536. while (this.cameras.length) {
  17537. this.cameras[0].dispose();
  17538. }
  17539. // Release materials
  17540. while (this.materials.length) {
  17541. this.materials[0].dispose();
  17542. }
  17543. // Release particles
  17544. while (this.particleSystems.length) {
  17545. this.particleSystems[0].dispose();
  17546. }
  17547. // Release sprites
  17548. while (this.spriteManagers.length) {
  17549. this.spriteManagers[0].dispose();
  17550. }
  17551. // Release layers
  17552. while (this.layers.length) {
  17553. this.layers[0].dispose();
  17554. }
  17555. // Release textures
  17556. while (this.textures.length) {
  17557. this.textures[0].dispose();
  17558. }
  17559. // Post-processes
  17560. this.postProcessManager.dispose();
  17561. // Physics
  17562. if (this._physicsEngine) {
  17563. this.disablePhysicsEngine();
  17564. }
  17565. // Remove from engine
  17566. index = this._engine.scenes.indexOf(this);
  17567. if (index > -1) {
  17568. this._engine.scenes.splice(index, 1);
  17569. }
  17570. this._engine.wipeCaches();
  17571. };
  17572. // Release sounds & sounds tracks
  17573. Scene.prototype.disposeSounds = function () {
  17574. this.mainSoundTrack.dispose();
  17575. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  17576. this.soundTracks[scIndex].dispose();
  17577. }
  17578. };
  17579. // Octrees
  17580. Scene.prototype.getWorldExtends = function () {
  17581. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17582. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17583. for (var index = 0; index < this.meshes.length; index++) {
  17584. var mesh = this.meshes[index];
  17585. mesh.computeWorldMatrix(true);
  17586. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  17587. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  17588. BABYLON.Tools.CheckExtends(minBox, min, max);
  17589. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17590. }
  17591. return {
  17592. min: min,
  17593. max: max
  17594. };
  17595. };
  17596. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  17597. if (maxCapacity === void 0) { maxCapacity = 64; }
  17598. if (maxDepth === void 0) { maxDepth = 2; }
  17599. if (!this._selectionOctree) {
  17600. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  17601. }
  17602. var worldExtends = this.getWorldExtends();
  17603. // Update octree
  17604. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  17605. return this._selectionOctree;
  17606. };
  17607. // Picking
  17608. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  17609. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  17610. var engine = this._engine;
  17611. if (!camera) {
  17612. if (!this.activeCamera)
  17613. throw new Error("Active camera not set");
  17614. camera = this.activeCamera;
  17615. }
  17616. var cameraViewport = camera.viewport;
  17617. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17618. // Moving coordinates to local viewport world
  17619. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17620. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17621. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  17622. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  17623. };
  17624. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  17625. var engine = this._engine;
  17626. if (!camera) {
  17627. if (!this.activeCamera)
  17628. throw new Error("Active camera not set");
  17629. camera = this.activeCamera;
  17630. }
  17631. var cameraViewport = camera.viewport;
  17632. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17633. var identity = BABYLON.Matrix.Identity();
  17634. // Moving coordinates to local viewport world
  17635. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17636. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17637. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  17638. };
  17639. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  17640. var pickingInfo = null;
  17641. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17642. var mesh = this.meshes[meshIndex];
  17643. if (predicate) {
  17644. if (!predicate(mesh)) {
  17645. continue;
  17646. }
  17647. }
  17648. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17649. continue;
  17650. }
  17651. var world = mesh.getWorldMatrix();
  17652. var ray = rayFunction(world);
  17653. var result = mesh.intersects(ray, fastCheck);
  17654. if (!result || !result.hit)
  17655. continue;
  17656. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17657. continue;
  17658. pickingInfo = result;
  17659. if (fastCheck) {
  17660. break;
  17661. }
  17662. }
  17663. return pickingInfo || new BABYLON.PickingInfo();
  17664. };
  17665. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  17666. var pickingInfo = null;
  17667. camera = camera || this.activeCamera;
  17668. if (this.spriteManagers.length > 0) {
  17669. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  17670. var spriteManager = this.spriteManagers[spriteIndex];
  17671. if (!spriteManager.isPickable) {
  17672. continue;
  17673. }
  17674. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  17675. if (!result || !result.hit)
  17676. continue;
  17677. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17678. continue;
  17679. pickingInfo = result;
  17680. if (fastCheck) {
  17681. break;
  17682. }
  17683. }
  17684. }
  17685. return pickingInfo || new BABYLON.PickingInfo();
  17686. };
  17687. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  17688. var _this = this;
  17689. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17690. /// <param name="x">X position on screen</param>
  17691. /// <param name="y">Y position on screen</param>
  17692. /// <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>
  17693. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17694. /// <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>
  17695. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  17696. };
  17697. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  17698. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17699. /// <param name="x">X position on screen</param>
  17700. /// <param name="y">Y position on screen</param>
  17701. /// <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>
  17702. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17703. /// <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>
  17704. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  17705. };
  17706. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  17707. var _this = this;
  17708. return this._internalPick(function (world) {
  17709. if (!_this._pickWithRayInverseMatrix) {
  17710. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  17711. }
  17712. world.invertToRef(_this._pickWithRayInverseMatrix);
  17713. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  17714. }, predicate, fastCheck);
  17715. };
  17716. Scene.prototype.setPointerOverMesh = function (mesh) {
  17717. if (this._pointerOverMesh === mesh) {
  17718. return;
  17719. }
  17720. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17721. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17722. }
  17723. this._pointerOverMesh = mesh;
  17724. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17725. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17726. }
  17727. };
  17728. Scene.prototype.getPointerOverMesh = function () {
  17729. return this._pointerOverMesh;
  17730. };
  17731. Scene.prototype.setPointerOverSprite = function (sprite) {
  17732. if (this._pointerOverSprite === sprite) {
  17733. return;
  17734. }
  17735. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17736. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17737. }
  17738. this._pointerOverSprite = sprite;
  17739. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17740. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17741. }
  17742. };
  17743. Scene.prototype.getPointerOverSprite = function () {
  17744. return this._pointerOverSprite;
  17745. };
  17746. // Physics
  17747. Scene.prototype.getPhysicsEngine = function () {
  17748. return this._physicsEngine;
  17749. };
  17750. /**
  17751. * Enables physics to the current scene
  17752. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  17753. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  17754. * @return {boolean} was the physics engine initialized
  17755. */
  17756. Scene.prototype.enablePhysics = function (gravity, plugin) {
  17757. if (this._physicsEngine) {
  17758. return true;
  17759. }
  17760. try {
  17761. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  17762. return true;
  17763. }
  17764. catch (e) {
  17765. BABYLON.Tools.Error(e.message);
  17766. return false;
  17767. }
  17768. };
  17769. Scene.prototype.disablePhysicsEngine = function () {
  17770. if (!this._physicsEngine) {
  17771. return;
  17772. }
  17773. this._physicsEngine.dispose();
  17774. this._physicsEngine = undefined;
  17775. };
  17776. Scene.prototype.isPhysicsEnabled = function () {
  17777. return this._physicsEngine !== undefined;
  17778. };
  17779. /**
  17780. *
  17781. * Sets the gravity of the physics engine (and NOT of the scene)
  17782. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  17783. */
  17784. Scene.prototype.setGravity = function (gravity) {
  17785. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  17786. if (!this._physicsEngine) {
  17787. return;
  17788. }
  17789. this._physicsEngine.setGravity(gravity);
  17790. };
  17791. /**
  17792. * Legacy support, using the new API
  17793. * @Deprecated
  17794. */
  17795. Scene.prototype.createCompoundImpostor = function (parts, options) {
  17796. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  17797. if (parts.parts) {
  17798. options = parts;
  17799. parts = parts.parts;
  17800. }
  17801. var mainMesh = parts[0].mesh;
  17802. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  17803. for (var index = 1; index < parts.length; index++) {
  17804. var mesh = parts[index].mesh;
  17805. if (mesh.parent !== mainMesh) {
  17806. mesh.position = mesh.position.subtract(mainMesh.position);
  17807. mesh.parent = mainMesh;
  17808. }
  17809. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  17810. }
  17811. mainMesh.physicsImpostor.forceUpdate();
  17812. };
  17813. Scene.prototype.deleteCompoundImpostor = function (compound) {
  17814. var mesh = compound.parts[0].mesh;
  17815. mesh.physicsImpostor.dispose();
  17816. mesh.physicsImpostor = null;
  17817. };
  17818. // Misc.
  17819. Scene.prototype.createDefaultCameraOrLight = function () {
  17820. // Light
  17821. if (this.lights.length === 0) {
  17822. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  17823. }
  17824. // Camera
  17825. if (!this.activeCamera) {
  17826. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  17827. // Compute position
  17828. var worldExtends = this.getWorldExtends();
  17829. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  17830. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  17831. camera.setTarget(worldCenter);
  17832. this.activeCamera = camera;
  17833. }
  17834. };
  17835. // Tags
  17836. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  17837. if (tagsQuery === undefined) {
  17838. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  17839. return list;
  17840. }
  17841. var listByTags = [];
  17842. forEach = forEach || (function (item) { return; });
  17843. for (var i in list) {
  17844. var item = list[i];
  17845. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  17846. listByTags.push(item);
  17847. forEach(item);
  17848. }
  17849. }
  17850. return listByTags;
  17851. };
  17852. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  17853. return this._getByTags(this.meshes, tagsQuery, forEach);
  17854. };
  17855. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  17856. return this._getByTags(this.cameras, tagsQuery, forEach);
  17857. };
  17858. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  17859. return this._getByTags(this.lights, tagsQuery, forEach);
  17860. };
  17861. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  17862. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  17863. };
  17864. /**
  17865. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  17866. * This allowed control for front to back rendering or reversly depending of the special needs.
  17867. *
  17868. * @param renderingGroupId The rendering group id corresponding to its index
  17869. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  17870. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  17871. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  17872. */
  17873. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17874. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17875. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17876. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17877. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  17878. };
  17879. /**
  17880. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  17881. *
  17882. * @param renderingGroupId The rendering group id corresponding to its index
  17883. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  17884. */
  17885. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  17886. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  17887. };
  17888. // Statics
  17889. Scene._FOGMODE_NONE = 0;
  17890. Scene._FOGMODE_EXP = 1;
  17891. Scene._FOGMODE_EXP2 = 2;
  17892. Scene._FOGMODE_LINEAR = 3;
  17893. Scene.MinDeltaTime = 1.0;
  17894. Scene.MaxDeltaTime = 1000.0;
  17895. return Scene;
  17896. })();
  17897. BABYLON.Scene = Scene;
  17898. })(BABYLON || (BABYLON = {}));
  17899. var BABYLON;
  17900. (function (BABYLON) {
  17901. var Buffer = (function () {
  17902. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  17903. if (engine instanceof BABYLON.Mesh) {
  17904. this._engine = engine.getScene().getEngine();
  17905. }
  17906. else {
  17907. this._engine = engine;
  17908. }
  17909. this._updatable = updatable;
  17910. this._data = data;
  17911. this._strideSize = stride;
  17912. if (!postponeInternalCreation) {
  17913. this.create();
  17914. }
  17915. this._instanced = instanced;
  17916. }
  17917. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  17918. // a lot of these parameters are ignored as they are overriden by the buffer
  17919. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  17920. };
  17921. // Properties
  17922. Buffer.prototype.isUpdatable = function () {
  17923. return this._updatable;
  17924. };
  17925. Buffer.prototype.getData = function () {
  17926. return this._data;
  17927. };
  17928. Buffer.prototype.getBuffer = function () {
  17929. return this._buffer;
  17930. };
  17931. Buffer.prototype.getStrideSize = function () {
  17932. return this._strideSize;
  17933. };
  17934. Buffer.prototype.getIsInstanced = function () {
  17935. return this._instanced;
  17936. };
  17937. // Methods
  17938. Buffer.prototype.create = function (data) {
  17939. if (!data && this._buffer) {
  17940. return; // nothing to do
  17941. }
  17942. data = data || this._data;
  17943. if (!this._buffer) {
  17944. if (this._updatable) {
  17945. this._buffer = this._engine.createDynamicVertexBuffer(data);
  17946. this._data = data;
  17947. }
  17948. else {
  17949. this._buffer = this._engine.createVertexBuffer(data);
  17950. }
  17951. }
  17952. else if (this._updatable) {
  17953. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  17954. this._data = data;
  17955. }
  17956. };
  17957. Buffer.prototype.update = function (data) {
  17958. this.create(data);
  17959. };
  17960. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  17961. if (!this._buffer) {
  17962. return;
  17963. }
  17964. if (this._updatable) {
  17965. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  17966. this._data = null;
  17967. }
  17968. };
  17969. Buffer.prototype.dispose = function () {
  17970. if (!this._buffer) {
  17971. return;
  17972. }
  17973. if (this._engine._releaseBuffer(this._buffer)) {
  17974. this._buffer = null;
  17975. }
  17976. };
  17977. return Buffer;
  17978. })();
  17979. BABYLON.Buffer = Buffer;
  17980. })(BABYLON || (BABYLON = {}));
  17981. var BABYLON;
  17982. (function (BABYLON) {
  17983. var VertexBuffer = (function () {
  17984. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  17985. if (!stride) {
  17986. // Deduce stride from kind
  17987. switch (kind) {
  17988. case VertexBuffer.PositionKind:
  17989. stride = 3;
  17990. break;
  17991. case VertexBuffer.NormalKind:
  17992. stride = 3;
  17993. break;
  17994. case VertexBuffer.UVKind:
  17995. case VertexBuffer.UV2Kind:
  17996. case VertexBuffer.UV3Kind:
  17997. case VertexBuffer.UV4Kind:
  17998. case VertexBuffer.UV5Kind:
  17999. case VertexBuffer.UV6Kind:
  18000. stride = 2;
  18001. break;
  18002. case VertexBuffer.ColorKind:
  18003. stride = 4;
  18004. break;
  18005. case VertexBuffer.MatricesIndicesKind:
  18006. case VertexBuffer.MatricesIndicesExtraKind:
  18007. stride = 4;
  18008. break;
  18009. case VertexBuffer.MatricesWeightsKind:
  18010. case VertexBuffer.MatricesWeightsExtraKind:
  18011. stride = 4;
  18012. break;
  18013. }
  18014. }
  18015. if (data instanceof BABYLON.Buffer) {
  18016. if (!stride) {
  18017. stride = data.getStrideSize();
  18018. }
  18019. this._buffer = data;
  18020. this._ownsBuffer = false;
  18021. }
  18022. else {
  18023. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18024. this._ownsBuffer = true;
  18025. }
  18026. this._stride = stride;
  18027. this._offset = offset ? offset : 0;
  18028. this._size = size ? size : stride;
  18029. this._kind = kind;
  18030. }
  18031. VertexBuffer.prototype.getKind = function () {
  18032. return this._kind;
  18033. };
  18034. // Properties
  18035. VertexBuffer.prototype.isUpdatable = function () {
  18036. return this._buffer.isUpdatable();
  18037. };
  18038. VertexBuffer.prototype.getData = function () {
  18039. return this._buffer.getData();
  18040. };
  18041. VertexBuffer.prototype.getBuffer = function () {
  18042. return this._buffer.getBuffer();
  18043. };
  18044. VertexBuffer.prototype.getStrideSize = function () {
  18045. return this._stride;
  18046. };
  18047. VertexBuffer.prototype.getOffset = function () {
  18048. return this._offset;
  18049. };
  18050. VertexBuffer.prototype.getSize = function () {
  18051. return this._size;
  18052. };
  18053. VertexBuffer.prototype.getIsInstanced = function () {
  18054. return this._buffer.getIsInstanced();
  18055. };
  18056. // Methods
  18057. VertexBuffer.prototype.create = function (data) {
  18058. return this._buffer.create(data);
  18059. };
  18060. VertexBuffer.prototype.update = function (data) {
  18061. return this._buffer.update(data);
  18062. };
  18063. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18064. return this._buffer.updateDirectly(data, offset);
  18065. };
  18066. VertexBuffer.prototype.dispose = function () {
  18067. if (this._ownsBuffer) {
  18068. this._buffer.dispose();
  18069. }
  18070. };
  18071. Object.defineProperty(VertexBuffer, "PositionKind", {
  18072. get: function () {
  18073. return VertexBuffer._PositionKind;
  18074. },
  18075. enumerable: true,
  18076. configurable: true
  18077. });
  18078. Object.defineProperty(VertexBuffer, "NormalKind", {
  18079. get: function () {
  18080. return VertexBuffer._NormalKind;
  18081. },
  18082. enumerable: true,
  18083. configurable: true
  18084. });
  18085. Object.defineProperty(VertexBuffer, "UVKind", {
  18086. get: function () {
  18087. return VertexBuffer._UVKind;
  18088. },
  18089. enumerable: true,
  18090. configurable: true
  18091. });
  18092. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18093. get: function () {
  18094. return VertexBuffer._UV2Kind;
  18095. },
  18096. enumerable: true,
  18097. configurable: true
  18098. });
  18099. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18100. get: function () {
  18101. return VertexBuffer._UV3Kind;
  18102. },
  18103. enumerable: true,
  18104. configurable: true
  18105. });
  18106. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18107. get: function () {
  18108. return VertexBuffer._UV4Kind;
  18109. },
  18110. enumerable: true,
  18111. configurable: true
  18112. });
  18113. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18114. get: function () {
  18115. return VertexBuffer._UV5Kind;
  18116. },
  18117. enumerable: true,
  18118. configurable: true
  18119. });
  18120. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18121. get: function () {
  18122. return VertexBuffer._UV6Kind;
  18123. },
  18124. enumerable: true,
  18125. configurable: true
  18126. });
  18127. Object.defineProperty(VertexBuffer, "ColorKind", {
  18128. get: function () {
  18129. return VertexBuffer._ColorKind;
  18130. },
  18131. enumerable: true,
  18132. configurable: true
  18133. });
  18134. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18135. get: function () {
  18136. return VertexBuffer._MatricesIndicesKind;
  18137. },
  18138. enumerable: true,
  18139. configurable: true
  18140. });
  18141. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18142. get: function () {
  18143. return VertexBuffer._MatricesWeightsKind;
  18144. },
  18145. enumerable: true,
  18146. configurable: true
  18147. });
  18148. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18149. get: function () {
  18150. return VertexBuffer._MatricesIndicesExtraKind;
  18151. },
  18152. enumerable: true,
  18153. configurable: true
  18154. });
  18155. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18156. get: function () {
  18157. return VertexBuffer._MatricesWeightsExtraKind;
  18158. },
  18159. enumerable: true,
  18160. configurable: true
  18161. });
  18162. // Enums
  18163. VertexBuffer._PositionKind = "position";
  18164. VertexBuffer._NormalKind = "normal";
  18165. VertexBuffer._UVKind = "uv";
  18166. VertexBuffer._UV2Kind = "uv2";
  18167. VertexBuffer._UV3Kind = "uv3";
  18168. VertexBuffer._UV4Kind = "uv4";
  18169. VertexBuffer._UV5Kind = "uv5";
  18170. VertexBuffer._UV6Kind = "uv6";
  18171. VertexBuffer._ColorKind = "color";
  18172. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18173. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18174. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18175. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18176. return VertexBuffer;
  18177. })();
  18178. BABYLON.VertexBuffer = VertexBuffer;
  18179. })(BABYLON || (BABYLON = {}));
  18180. var BABYLON;
  18181. (function (BABYLON) {
  18182. /**
  18183. * Creates an instance based on a source mesh.
  18184. */
  18185. var InstancedMesh = (function (_super) {
  18186. __extends(InstancedMesh, _super);
  18187. function InstancedMesh(name, source) {
  18188. _super.call(this, name, source.getScene());
  18189. source.instances.push(this);
  18190. this._sourceMesh = source;
  18191. this.position.copyFrom(source.position);
  18192. this.rotation.copyFrom(source.rotation);
  18193. this.scaling.copyFrom(source.scaling);
  18194. if (source.rotationQuaternion) {
  18195. this.rotationQuaternion = source.rotationQuaternion.clone();
  18196. }
  18197. this.infiniteDistance = source.infiniteDistance;
  18198. this.setPivotMatrix(source.getPivotMatrix());
  18199. this.refreshBoundingInfo();
  18200. this._syncSubMeshes();
  18201. }
  18202. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  18203. // Methods
  18204. get: function () {
  18205. return this._sourceMesh.receiveShadows;
  18206. },
  18207. enumerable: true,
  18208. configurable: true
  18209. });
  18210. Object.defineProperty(InstancedMesh.prototype, "material", {
  18211. get: function () {
  18212. return this._sourceMesh.material;
  18213. },
  18214. enumerable: true,
  18215. configurable: true
  18216. });
  18217. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  18218. get: function () {
  18219. return this._sourceMesh.visibility;
  18220. },
  18221. enumerable: true,
  18222. configurable: true
  18223. });
  18224. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  18225. get: function () {
  18226. return this._sourceMesh.skeleton;
  18227. },
  18228. enumerable: true,
  18229. configurable: true
  18230. });
  18231. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  18232. get: function () {
  18233. return this._sourceMesh.renderingGroupId;
  18234. },
  18235. enumerable: true,
  18236. configurable: true
  18237. });
  18238. InstancedMesh.prototype.getTotalVertices = function () {
  18239. return this._sourceMesh.getTotalVertices();
  18240. };
  18241. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  18242. get: function () {
  18243. return this._sourceMesh;
  18244. },
  18245. enumerable: true,
  18246. configurable: true
  18247. });
  18248. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18249. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  18250. };
  18251. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  18252. return this._sourceMesh.isVerticesDataPresent(kind);
  18253. };
  18254. InstancedMesh.prototype.getIndices = function () {
  18255. return this._sourceMesh.getIndices();
  18256. };
  18257. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  18258. get: function () {
  18259. return this._sourceMesh._positions;
  18260. },
  18261. enumerable: true,
  18262. configurable: true
  18263. });
  18264. InstancedMesh.prototype.refreshBoundingInfo = function () {
  18265. var meshBB = this._sourceMesh.getBoundingInfo();
  18266. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  18267. this._updateBoundingInfo();
  18268. };
  18269. InstancedMesh.prototype._preActivate = function () {
  18270. if (this._currentLOD) {
  18271. this._currentLOD._preActivate();
  18272. }
  18273. };
  18274. InstancedMesh.prototype._activate = function (renderId) {
  18275. if (this._currentLOD) {
  18276. this._currentLOD._registerInstanceForRenderId(this, renderId);
  18277. }
  18278. };
  18279. InstancedMesh.prototype.getLOD = function (camera) {
  18280. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  18281. if (this._currentLOD === this.sourceMesh) {
  18282. return this;
  18283. }
  18284. return this._currentLOD;
  18285. };
  18286. InstancedMesh.prototype._syncSubMeshes = function () {
  18287. this.releaseSubMeshes();
  18288. if (this._sourceMesh.subMeshes) {
  18289. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  18290. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  18291. }
  18292. }
  18293. };
  18294. InstancedMesh.prototype._generatePointsArray = function () {
  18295. return this._sourceMesh._generatePointsArray();
  18296. };
  18297. // Clone
  18298. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18299. var result = this._sourceMesh.createInstance(name);
  18300. // Deep copy
  18301. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  18302. // Bounding info
  18303. this.refreshBoundingInfo();
  18304. // Parent
  18305. if (newParent) {
  18306. result.parent = newParent;
  18307. }
  18308. if (!doNotCloneChildren) {
  18309. // Children
  18310. for (var index = 0; index < this.getScene().meshes.length; index++) {
  18311. var mesh = this.getScene().meshes[index];
  18312. if (mesh.parent === this) {
  18313. mesh.clone(mesh.name, result);
  18314. }
  18315. }
  18316. }
  18317. result.computeWorldMatrix(true);
  18318. return result;
  18319. };
  18320. // Dispoe
  18321. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  18322. // Remove from mesh
  18323. var index = this._sourceMesh.instances.indexOf(this);
  18324. this._sourceMesh.instances.splice(index, 1);
  18325. _super.prototype.dispose.call(this, doNotRecurse);
  18326. };
  18327. return InstancedMesh;
  18328. })(BABYLON.AbstractMesh);
  18329. BABYLON.InstancedMesh = InstancedMesh;
  18330. })(BABYLON || (BABYLON = {}));
  18331. var BABYLON;
  18332. (function (BABYLON) {
  18333. var _InstancesBatch = (function () {
  18334. function _InstancesBatch() {
  18335. this.mustReturn = false;
  18336. this.visibleInstances = new Array();
  18337. this.renderSelf = new Array();
  18338. }
  18339. return _InstancesBatch;
  18340. })();
  18341. BABYLON._InstancesBatch = _InstancesBatch;
  18342. var Mesh = (function (_super) {
  18343. __extends(Mesh, _super);
  18344. /**
  18345. * @constructor
  18346. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  18347. * @param {Scene} scene The scene to add this mesh to.
  18348. * @param {Node} parent The parent of this mesh, if it has one
  18349. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  18350. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  18351. * When false, achieved by calling a clone(), also passing False.
  18352. * This will make creation of children, recursive.
  18353. */
  18354. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  18355. if (parent === void 0) { parent = null; }
  18356. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  18357. _super.call(this, name, scene);
  18358. // Events
  18359. /**
  18360. * An event triggered before rendering the mesh
  18361. * @type {BABYLON.Observable}
  18362. */
  18363. this.onBeforeRenderObservable = new BABYLON.Observable();
  18364. /**
  18365. * An event triggered after rendering the mesh
  18366. * @type {BABYLON.Observable}
  18367. */
  18368. this.onAfterRenderObservable = new BABYLON.Observable();
  18369. /**
  18370. * An event triggered before drawing the mesh
  18371. * @type {BABYLON.Observable}
  18372. */
  18373. this.onBeforeDrawObservable = new BABYLON.Observable();
  18374. // Members
  18375. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18376. this.instances = new Array();
  18377. this._LODLevels = new Array();
  18378. this._visibleInstances = {};
  18379. this._renderIdForInstances = new Array();
  18380. this._batchCache = new _InstancesBatch();
  18381. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  18382. this._sideOrientation = Mesh._DEFAULTSIDE;
  18383. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  18384. if (source) {
  18385. // Geometry
  18386. if (source._geometry) {
  18387. source._geometry.applyToMesh(this);
  18388. }
  18389. // Deep copy
  18390. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  18391. // Pivot
  18392. this.setPivotMatrix(source.getPivotMatrix());
  18393. this.id = name + "." + source.id;
  18394. // Material
  18395. this.material = source.material;
  18396. var index;
  18397. if (!doNotCloneChildren) {
  18398. // Children
  18399. for (index = 0; index < scene.meshes.length; index++) {
  18400. var mesh = scene.meshes[index];
  18401. if (mesh.parent === source) {
  18402. // doNotCloneChildren is always going to be False
  18403. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  18404. }
  18405. }
  18406. }
  18407. // Physics clone
  18408. var physicsEngine = this.getScene().getPhysicsEngine();
  18409. if (clonePhysicsImpostor && physicsEngine) {
  18410. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  18411. if (impostor) {
  18412. this.physicsImpostor = impostor.clone(this);
  18413. }
  18414. }
  18415. // Particles
  18416. for (index = 0; index < scene.particleSystems.length; index++) {
  18417. var system = scene.particleSystems[index];
  18418. if (system.emitter === source) {
  18419. system.clone(system.name, this);
  18420. }
  18421. }
  18422. this.computeWorldMatrix(true);
  18423. }
  18424. // Parent
  18425. if (parent !== null) {
  18426. this.parent = parent;
  18427. }
  18428. }
  18429. Object.defineProperty(Mesh, "FRONTSIDE", {
  18430. /**
  18431. * Mesh side orientation : usually the external or front surface
  18432. */
  18433. get: function () {
  18434. return Mesh._FRONTSIDE;
  18435. },
  18436. enumerable: true,
  18437. configurable: true
  18438. });
  18439. Object.defineProperty(Mesh, "BACKSIDE", {
  18440. /**
  18441. * Mesh side orientation : usually the internal or back surface
  18442. */
  18443. get: function () {
  18444. return Mesh._BACKSIDE;
  18445. },
  18446. enumerable: true,
  18447. configurable: true
  18448. });
  18449. Object.defineProperty(Mesh, "DOUBLESIDE", {
  18450. /**
  18451. * Mesh side orientation : both internal and external or front and back surfaces
  18452. */
  18453. get: function () {
  18454. return Mesh._DOUBLESIDE;
  18455. },
  18456. enumerable: true,
  18457. configurable: true
  18458. });
  18459. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  18460. /**
  18461. * Mesh side orientation : by default, `FRONTSIDE`
  18462. */
  18463. get: function () {
  18464. return Mesh._DEFAULTSIDE;
  18465. },
  18466. enumerable: true,
  18467. configurable: true
  18468. });
  18469. Object.defineProperty(Mesh, "NO_CAP", {
  18470. /**
  18471. * Mesh cap setting : no cap
  18472. */
  18473. get: function () {
  18474. return Mesh._NO_CAP;
  18475. },
  18476. enumerable: true,
  18477. configurable: true
  18478. });
  18479. Object.defineProperty(Mesh, "CAP_START", {
  18480. /**
  18481. * Mesh cap setting : one cap at the beginning of the mesh
  18482. */
  18483. get: function () {
  18484. return Mesh._CAP_START;
  18485. },
  18486. enumerable: true,
  18487. configurable: true
  18488. });
  18489. Object.defineProperty(Mesh, "CAP_END", {
  18490. /**
  18491. * Mesh cap setting : one cap at the end of the mesh
  18492. */
  18493. get: function () {
  18494. return Mesh._CAP_END;
  18495. },
  18496. enumerable: true,
  18497. configurable: true
  18498. });
  18499. Object.defineProperty(Mesh, "CAP_ALL", {
  18500. /**
  18501. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  18502. */
  18503. get: function () {
  18504. return Mesh._CAP_ALL;
  18505. },
  18506. enumerable: true,
  18507. configurable: true
  18508. });
  18509. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  18510. set: function (callback) {
  18511. if (this._onBeforeDrawObserver) {
  18512. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  18513. }
  18514. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  18515. },
  18516. enumerable: true,
  18517. configurable: true
  18518. });
  18519. // Methods
  18520. /**
  18521. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18522. */
  18523. Mesh.prototype.toString = function (fullDetails) {
  18524. var ret = _super.prototype.toString.call(this, fullDetails);
  18525. ret += ", n vertices: " + this.getTotalVertices();
  18526. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  18527. if (this.animations) {
  18528. for (var i = 0; i < this.animations.length; i++) {
  18529. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18530. }
  18531. }
  18532. if (fullDetails) {
  18533. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  18534. }
  18535. return ret;
  18536. };
  18537. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  18538. get: function () {
  18539. return this._LODLevels.length > 0;
  18540. },
  18541. enumerable: true,
  18542. configurable: true
  18543. });
  18544. Mesh.prototype._sortLODLevels = function () {
  18545. this._LODLevels.sort(function (a, b) {
  18546. if (a.distance < b.distance) {
  18547. return 1;
  18548. }
  18549. if (a.distance > b.distance) {
  18550. return -1;
  18551. }
  18552. return 0;
  18553. });
  18554. };
  18555. /**
  18556. * Add a mesh as LOD level triggered at the given distance.
  18557. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18558. * @param {number} distance The distance from the center of the object to show this level
  18559. * @param {Mesh} mesh The mesh to be added as LOD level
  18560. * @return {Mesh} This mesh (for chaining)
  18561. */
  18562. Mesh.prototype.addLODLevel = function (distance, mesh) {
  18563. if (mesh && mesh._masterMesh) {
  18564. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  18565. return this;
  18566. }
  18567. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  18568. this._LODLevels.push(level);
  18569. if (mesh) {
  18570. mesh._masterMesh = this;
  18571. }
  18572. this._sortLODLevels();
  18573. return this;
  18574. };
  18575. /**
  18576. * Returns the LOD level mesh at the passed distance or null if not found.
  18577. * It is related to the method `addLODLevel(distance, mesh)`.
  18578. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18579. */
  18580. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  18581. for (var index = 0; index < this._LODLevels.length; index++) {
  18582. var level = this._LODLevels[index];
  18583. if (level.distance === distance) {
  18584. return level.mesh;
  18585. }
  18586. }
  18587. return null;
  18588. };
  18589. /**
  18590. * Remove a mesh from the LOD array
  18591. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18592. * @param {Mesh} mesh The mesh to be removed.
  18593. * @return {Mesh} This mesh (for chaining)
  18594. */
  18595. Mesh.prototype.removeLODLevel = function (mesh) {
  18596. for (var index = 0; index < this._LODLevels.length; index++) {
  18597. if (this._LODLevels[index].mesh === mesh) {
  18598. this._LODLevels.splice(index, 1);
  18599. if (mesh) {
  18600. mesh._masterMesh = null;
  18601. }
  18602. }
  18603. }
  18604. this._sortLODLevels();
  18605. return this;
  18606. };
  18607. /**
  18608. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  18609. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18610. */
  18611. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  18612. if (!this._LODLevels || this._LODLevels.length === 0) {
  18613. return this;
  18614. }
  18615. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  18616. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  18617. if (this.onLODLevelSelection) {
  18618. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  18619. }
  18620. return this;
  18621. }
  18622. for (var index = 0; index < this._LODLevels.length; index++) {
  18623. var level = this._LODLevels[index];
  18624. if (level.distance < distanceToCamera) {
  18625. if (level.mesh) {
  18626. level.mesh._preActivate();
  18627. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18628. }
  18629. if (this.onLODLevelSelection) {
  18630. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  18631. }
  18632. return level.mesh;
  18633. }
  18634. }
  18635. if (this.onLODLevelSelection) {
  18636. this.onLODLevelSelection(distanceToCamera, this, this);
  18637. }
  18638. return this;
  18639. };
  18640. Object.defineProperty(Mesh.prototype, "geometry", {
  18641. /**
  18642. * Returns the mesh internal Geometry object.
  18643. */
  18644. get: function () {
  18645. return this._geometry;
  18646. },
  18647. enumerable: true,
  18648. configurable: true
  18649. });
  18650. /**
  18651. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  18652. */
  18653. Mesh.prototype.getTotalVertices = function () {
  18654. if (!this._geometry) {
  18655. return 0;
  18656. }
  18657. return this._geometry.getTotalVertices();
  18658. };
  18659. /**
  18660. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  18661. * 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.
  18662. * Returns null if the mesh has no geometry or no vertex buffer.
  18663. * Possible `kind` values :
  18664. * - BABYLON.VertexBuffer.PositionKind
  18665. * - BABYLON.VertexBuffer.UVKind
  18666. * - BABYLON.VertexBuffer.UV2Kind
  18667. * - BABYLON.VertexBuffer.UV3Kind
  18668. * - BABYLON.VertexBuffer.UV4Kind
  18669. * - BABYLON.VertexBuffer.UV5Kind
  18670. * - BABYLON.VertexBuffer.UV6Kind
  18671. * - BABYLON.VertexBuffer.ColorKind
  18672. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18673. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18674. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18675. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18676. */
  18677. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18678. if (!this._geometry) {
  18679. return null;
  18680. }
  18681. return this._geometry.getVerticesData(kind, copyWhenShared);
  18682. };
  18683. /**
  18684. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  18685. * Returns `undefined` if the mesh has no geometry.
  18686. * Possible `kind` values :
  18687. * - BABYLON.VertexBuffer.PositionKind
  18688. * - BABYLON.VertexBuffer.UVKind
  18689. * - BABYLON.VertexBuffer.UV2Kind
  18690. * - BABYLON.VertexBuffer.UV3Kind
  18691. * - BABYLON.VertexBuffer.UV4Kind
  18692. * - BABYLON.VertexBuffer.UV5Kind
  18693. * - BABYLON.VertexBuffer.UV6Kind
  18694. * - BABYLON.VertexBuffer.ColorKind
  18695. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18696. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18697. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18698. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18699. */
  18700. Mesh.prototype.getVertexBuffer = function (kind) {
  18701. if (!this._geometry) {
  18702. return undefined;
  18703. }
  18704. return this._geometry.getVertexBuffer(kind);
  18705. };
  18706. /**
  18707. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  18708. * Possible `kind` values :
  18709. * - BABYLON.VertexBuffer.PositionKind
  18710. * - BABYLON.VertexBuffer.UVKind
  18711. * - BABYLON.VertexBuffer.UV2Kind
  18712. * - BABYLON.VertexBuffer.UV3Kind
  18713. * - BABYLON.VertexBuffer.UV4Kind
  18714. * - BABYLON.VertexBuffer.UV5Kind
  18715. * - BABYLON.VertexBuffer.UV6Kind
  18716. * - BABYLON.VertexBuffer.ColorKind
  18717. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18718. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18719. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18720. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18721. */
  18722. Mesh.prototype.isVerticesDataPresent = function (kind) {
  18723. if (!this._geometry) {
  18724. if (this._delayInfo) {
  18725. return this._delayInfo.indexOf(kind) !== -1;
  18726. }
  18727. return false;
  18728. }
  18729. return this._geometry.isVerticesDataPresent(kind);
  18730. };
  18731. /**
  18732. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  18733. * Possible `kind` values :
  18734. * - BABYLON.VertexBuffer.PositionKind
  18735. * - BABYLON.VertexBuffer.UVKind
  18736. * - BABYLON.VertexBuffer.UV2Kind
  18737. * - BABYLON.VertexBuffer.UV3Kind
  18738. * - BABYLON.VertexBuffer.UV4Kind
  18739. * - BABYLON.VertexBuffer.UV5Kind
  18740. * - BABYLON.VertexBuffer.UV6Kind
  18741. * - BABYLON.VertexBuffer.ColorKind
  18742. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18743. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18744. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18745. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18746. */
  18747. Mesh.prototype.getVerticesDataKinds = function () {
  18748. if (!this._geometry) {
  18749. var result = [];
  18750. if (this._delayInfo) {
  18751. for (var kind in this._delayInfo) {
  18752. result.push(kind);
  18753. }
  18754. }
  18755. return result;
  18756. }
  18757. return this._geometry.getVerticesDataKinds();
  18758. };
  18759. /**
  18760. * Returns a positive integer : the total number of indices in this mesh geometry.
  18761. * Returns zero if the mesh has no geometry.
  18762. */
  18763. Mesh.prototype.getTotalIndices = function () {
  18764. if (!this._geometry) {
  18765. return 0;
  18766. }
  18767. return this._geometry.getTotalIndices();
  18768. };
  18769. /**
  18770. * Returns an array of integers or a Int32Array populated with the mesh indices.
  18771. * 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.
  18772. * Returns an empty array if the mesh has no geometry.
  18773. */
  18774. Mesh.prototype.getIndices = function (copyWhenShared) {
  18775. if (!this._geometry) {
  18776. return [];
  18777. }
  18778. return this._geometry.getIndices(copyWhenShared);
  18779. };
  18780. Object.defineProperty(Mesh.prototype, "isBlocked", {
  18781. get: function () {
  18782. return this._masterMesh !== null && this._masterMesh !== undefined;
  18783. },
  18784. enumerable: true,
  18785. configurable: true
  18786. });
  18787. /**
  18788. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  18789. */
  18790. Mesh.prototype.isReady = function () {
  18791. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18792. return false;
  18793. }
  18794. return _super.prototype.isReady.call(this);
  18795. };
  18796. /**
  18797. * Boolean : true if the mesh has been disposed.
  18798. */
  18799. Mesh.prototype.isDisposed = function () {
  18800. return this._isDisposed;
  18801. };
  18802. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  18803. get: function () {
  18804. return this._sideOrientation;
  18805. },
  18806. /**
  18807. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  18808. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  18809. */
  18810. set: function (sideO) {
  18811. this._sideOrientation = sideO;
  18812. },
  18813. enumerable: true,
  18814. configurable: true
  18815. });
  18816. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  18817. /**
  18818. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  18819. * This property is pertinent only for updatable parametric shapes.
  18820. */
  18821. get: function () {
  18822. return this._areNormalsFrozen;
  18823. },
  18824. enumerable: true,
  18825. configurable: true
  18826. });
  18827. /**
  18828. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18829. * It has no effect at all on other shapes.
  18830. * It prevents the mesh normals from being recomputed on next `positions` array update.
  18831. */
  18832. Mesh.prototype.freezeNormals = function () {
  18833. this._areNormalsFrozen = true;
  18834. };
  18835. /**
  18836. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18837. * It has no effect at all on other shapes.
  18838. * It reactivates the mesh normals computation if it was previously frozen.
  18839. */
  18840. Mesh.prototype.unfreezeNormals = function () {
  18841. this._areNormalsFrozen = false;
  18842. };
  18843. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  18844. /**
  18845. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  18846. */
  18847. set: function (count) {
  18848. this._overridenInstanceCount = count;
  18849. },
  18850. enumerable: true,
  18851. configurable: true
  18852. });
  18853. // Methods
  18854. Mesh.prototype._preActivate = function () {
  18855. var sceneRenderId = this.getScene().getRenderId();
  18856. if (this._preActivateId === sceneRenderId) {
  18857. return;
  18858. }
  18859. this._preActivateId = sceneRenderId;
  18860. this._visibleInstances = null;
  18861. };
  18862. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18863. if (this._visibleInstances) {
  18864. this._visibleInstances.intermediateDefaultRenderId = renderId;
  18865. }
  18866. };
  18867. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  18868. if (!this._visibleInstances) {
  18869. this._visibleInstances = {};
  18870. this._visibleInstances.defaultRenderId = renderId;
  18871. this._visibleInstances.selfDefaultRenderId = this._renderId;
  18872. }
  18873. if (!this._visibleInstances[renderId]) {
  18874. this._visibleInstances[renderId] = new Array();
  18875. }
  18876. this._visibleInstances[renderId].push(instance);
  18877. };
  18878. /**
  18879. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  18880. * This means the mesh underlying bounding box and sphere are recomputed.
  18881. */
  18882. Mesh.prototype.refreshBoundingInfo = function () {
  18883. if (this._boundingInfo.isLocked) {
  18884. return;
  18885. }
  18886. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18887. if (data) {
  18888. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  18889. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18890. }
  18891. if (this.subMeshes) {
  18892. for (var index = 0; index < this.subMeshes.length; index++) {
  18893. this.subMeshes[index].refreshBoundingInfo();
  18894. }
  18895. }
  18896. this._updateBoundingInfo();
  18897. };
  18898. Mesh.prototype._createGlobalSubMesh = function () {
  18899. var totalVertices = this.getTotalVertices();
  18900. if (!totalVertices || !this.getIndices()) {
  18901. return null;
  18902. }
  18903. this.releaseSubMeshes();
  18904. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  18905. };
  18906. Mesh.prototype.subdivide = function (count) {
  18907. if (count < 1) {
  18908. return;
  18909. }
  18910. var totalIndices = this.getTotalIndices();
  18911. var subdivisionSize = (totalIndices / count) | 0;
  18912. var offset = 0;
  18913. // Ensure that subdivisionSize is a multiple of 3
  18914. while (subdivisionSize % 3 !== 0) {
  18915. subdivisionSize++;
  18916. }
  18917. this.releaseSubMeshes();
  18918. for (var index = 0; index < count; index++) {
  18919. if (offset >= totalIndices) {
  18920. break;
  18921. }
  18922. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  18923. offset += subdivisionSize;
  18924. }
  18925. this.synchronizeInstances();
  18926. };
  18927. /**
  18928. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18929. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18930. * The `data` are either a numeric array either a Float32Array.
  18931. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18932. * 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).
  18933. * Note that a new underlying VertexBuffer object is created each call.
  18934. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18935. *
  18936. * Possible `kind` values :
  18937. * - BABYLON.VertexBuffer.PositionKind
  18938. * - BABYLON.VertexBuffer.UVKind
  18939. * - BABYLON.VertexBuffer.UV2Kind
  18940. * - BABYLON.VertexBuffer.UV3Kind
  18941. * - BABYLON.VertexBuffer.UV4Kind
  18942. * - BABYLON.VertexBuffer.UV5Kind
  18943. * - BABYLON.VertexBuffer.UV6Kind
  18944. * - BABYLON.VertexBuffer.ColorKind
  18945. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18946. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18947. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18948. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18949. */
  18950. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18951. if (!this._geometry) {
  18952. var vertexData = new BABYLON.VertexData();
  18953. vertexData.set(data, kind);
  18954. var scene = this.getScene();
  18955. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  18956. }
  18957. else {
  18958. this._geometry.setVerticesData(kind, data, updatable, stride);
  18959. }
  18960. };
  18961. Mesh.prototype.setVerticesBuffer = function (buffer) {
  18962. if (!this._geometry) {
  18963. var scene = this.getScene();
  18964. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  18965. }
  18966. this._geometry.setVerticesBuffer(buffer);
  18967. };
  18968. /**
  18969. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18970. * If the mesh has no geometry, it is simply returned as it is.
  18971. * The `data` are either a numeric array either a Float32Array.
  18972. * No new underlying VertexBuffer object is created.
  18973. * 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.
  18974. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18975. *
  18976. * Possible `kind` values :
  18977. * - BABYLON.VertexBuffer.PositionKind
  18978. * - BABYLON.VertexBuffer.UVKind
  18979. * - BABYLON.VertexBuffer.UV2Kind
  18980. * - BABYLON.VertexBuffer.UV3Kind
  18981. * - BABYLON.VertexBuffer.UV4Kind
  18982. * - BABYLON.VertexBuffer.UV5Kind
  18983. * - BABYLON.VertexBuffer.UV6Kind
  18984. * - BABYLON.VertexBuffer.ColorKind
  18985. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18986. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18987. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18988. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18989. */
  18990. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18991. if (!this._geometry) {
  18992. return;
  18993. }
  18994. if (!makeItUnique) {
  18995. this._geometry.updateVerticesData(kind, data, updateExtends);
  18996. }
  18997. else {
  18998. this.makeGeometryUnique();
  18999. this.updateVerticesData(kind, data, updateExtends, false);
  19000. }
  19001. };
  19002. /**
  19003. * Deprecated since BabylonJS v2.3
  19004. */
  19005. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  19006. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  19007. if (!this._geometry) {
  19008. return;
  19009. }
  19010. if (!makeItUnique) {
  19011. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  19012. }
  19013. else {
  19014. this.makeGeometryUnique();
  19015. this.updateVerticesDataDirectly(kind, data, offset, false);
  19016. }
  19017. };
  19018. /**
  19019. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  19020. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  19021. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  19022. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  19023. */
  19024. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  19025. if (computeNormals === void 0) { computeNormals = true; }
  19026. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19027. positionFunction(positions);
  19028. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19029. if (computeNormals) {
  19030. var indices = this.getIndices();
  19031. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19032. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19033. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19034. }
  19035. };
  19036. Mesh.prototype.makeGeometryUnique = function () {
  19037. if (!this._geometry) {
  19038. return;
  19039. }
  19040. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  19041. geometry.applyToMesh(this);
  19042. };
  19043. /**
  19044. * Sets the mesh indices.
  19045. * Expects an array populated with integers or a Int32Array.
  19046. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19047. * This method creates a new index buffer each call.
  19048. */
  19049. Mesh.prototype.setIndices = function (indices, totalVertices) {
  19050. if (!this._geometry) {
  19051. var vertexData = new BABYLON.VertexData();
  19052. vertexData.indices = indices;
  19053. var scene = this.getScene();
  19054. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  19055. }
  19056. else {
  19057. this._geometry.setIndices(indices, totalVertices);
  19058. }
  19059. };
  19060. /**
  19061. * Invert the geometry to move from a right handed system to a left handed one.
  19062. */
  19063. Mesh.prototype.toLeftHanded = function () {
  19064. if (!this._geometry) {
  19065. return;
  19066. }
  19067. this._geometry.toLeftHanded();
  19068. };
  19069. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  19070. var engine = this.getScene().getEngine();
  19071. // Wireframe
  19072. var indexToBind;
  19073. if (this._unIndexed) {
  19074. indexToBind = null;
  19075. }
  19076. else {
  19077. switch (fillMode) {
  19078. case BABYLON.Material.PointFillMode:
  19079. indexToBind = null;
  19080. break;
  19081. case BABYLON.Material.WireFrameFillMode:
  19082. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  19083. break;
  19084. default:
  19085. case BABYLON.Material.TriangleFillMode:
  19086. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  19087. break;
  19088. }
  19089. }
  19090. // VBOs
  19091. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  19092. };
  19093. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  19094. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19095. return;
  19096. }
  19097. this.onBeforeDrawObservable.notifyObservers(this);
  19098. var engine = this.getScene().getEngine();
  19099. // Draw order
  19100. switch (fillMode) {
  19101. case BABYLON.Material.PointFillMode:
  19102. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19103. break;
  19104. case BABYLON.Material.WireFrameFillMode:
  19105. if (this._unIndexed) {
  19106. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19107. }
  19108. else {
  19109. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  19110. }
  19111. break;
  19112. default:
  19113. if (this._unIndexed) {
  19114. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19115. }
  19116. else {
  19117. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  19118. }
  19119. }
  19120. };
  19121. /**
  19122. * Registers for this mesh a javascript function called just before the rendering process.
  19123. * This function is passed the current mesh and doesn't return anything.
  19124. */
  19125. Mesh.prototype.registerBeforeRender = function (func) {
  19126. this.onBeforeRenderObservable.add(func);
  19127. };
  19128. /**
  19129. * Disposes a previously registered javascript function called before the rendering.
  19130. * This function is passed the current mesh and doesn't return anything.
  19131. */
  19132. Mesh.prototype.unregisterBeforeRender = function (func) {
  19133. this.onBeforeRenderObservable.removeCallback(func);
  19134. };
  19135. /**
  19136. * Registers for this mesh a javascript function called just after the rendering is complete.
  19137. * This function is passed the current mesh and doesn't return anything.
  19138. */
  19139. Mesh.prototype.registerAfterRender = function (func) {
  19140. this.onAfterRenderObservable.add(func);
  19141. };
  19142. /**
  19143. * Disposes a previously registered javascript function called after the rendering.
  19144. * This function is passed the current mesh and doesn't return anything.
  19145. */
  19146. Mesh.prototype.unregisterAfterRender = function (func) {
  19147. this.onAfterRenderObservable.removeCallback(func);
  19148. };
  19149. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  19150. var scene = this.getScene();
  19151. this._batchCache.mustReturn = false;
  19152. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  19153. this._batchCache.visibleInstances[subMeshId] = null;
  19154. if (this._visibleInstances) {
  19155. var currentRenderId = scene.getRenderId();
  19156. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  19157. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  19158. var selfRenderId = this._renderId;
  19159. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  19160. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  19161. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  19162. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  19163. }
  19164. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  19165. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  19166. this._batchCache.mustReturn = true;
  19167. return this._batchCache;
  19168. }
  19169. if (currentRenderId !== selfRenderId) {
  19170. this._batchCache.renderSelf[subMeshId] = false;
  19171. }
  19172. }
  19173. this._renderIdForInstances[subMeshId] = currentRenderId;
  19174. }
  19175. return this._batchCache;
  19176. };
  19177. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  19178. var visibleInstances = batch.visibleInstances[subMesh._id];
  19179. var matricesCount = visibleInstances.length + 1;
  19180. var bufferSize = matricesCount * 16 * 4;
  19181. var currentInstancesBufferSize = this._instancesBufferSize;
  19182. var instancesBuffer = this._instancesBuffer;
  19183. while (this._instancesBufferSize < bufferSize) {
  19184. this._instancesBufferSize *= 2;
  19185. }
  19186. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  19187. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  19188. }
  19189. var offset = 0;
  19190. var instancesCount = 0;
  19191. var world = this.getWorldMatrix();
  19192. if (batch.renderSelf[subMesh._id]) {
  19193. world.copyToArray(this._instancesData, offset);
  19194. offset += 16;
  19195. instancesCount++;
  19196. }
  19197. if (visibleInstances) {
  19198. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  19199. var instance = visibleInstances[instanceIndex];
  19200. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  19201. offset += 16;
  19202. instancesCount++;
  19203. }
  19204. }
  19205. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  19206. if (instancesBuffer) {
  19207. instancesBuffer.dispose();
  19208. }
  19209. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  19210. this._instancesBuffer = instancesBuffer;
  19211. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  19212. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  19213. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  19214. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  19215. }
  19216. else {
  19217. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  19218. }
  19219. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  19220. this._draw(subMesh, fillMode, instancesCount);
  19221. engine.unbindInstanceAttributes();
  19222. };
  19223. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  19224. var scene = this.getScene();
  19225. var engine = scene.getEngine();
  19226. if (hardwareInstancedRendering) {
  19227. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  19228. }
  19229. else {
  19230. if (batch.renderSelf[subMesh._id]) {
  19231. // Draw
  19232. if (onBeforeDraw) {
  19233. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  19234. }
  19235. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  19236. }
  19237. if (batch.visibleInstances[subMesh._id]) {
  19238. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  19239. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  19240. // World
  19241. var world = instance.getWorldMatrix();
  19242. if (onBeforeDraw) {
  19243. onBeforeDraw(true, world, effectiveMaterial);
  19244. }
  19245. // Draw
  19246. this._draw(subMesh, fillMode);
  19247. }
  19248. }
  19249. }
  19250. };
  19251. /**
  19252. * Triggers the draw call for the mesh.
  19253. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  19254. */
  19255. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  19256. var scene = this.getScene();
  19257. // Managing instances
  19258. var batch = this._getInstancesRenderList(subMesh._id);
  19259. if (batch.mustReturn) {
  19260. return;
  19261. }
  19262. // Checking geometry state
  19263. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19264. return;
  19265. }
  19266. var callbackIndex;
  19267. this.onBeforeRenderObservable.notifyObservers(this);
  19268. var engine = scene.getEngine();
  19269. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  19270. // Material
  19271. var effectiveMaterial = subMesh.getMaterial();
  19272. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  19273. return;
  19274. }
  19275. // Outline - step 1
  19276. var savedDepthWrite = engine.getDepthWrite();
  19277. if (this.renderOutline) {
  19278. engine.setDepthWrite(false);
  19279. scene.getOutlineRenderer().render(subMesh, batch);
  19280. engine.setDepthWrite(savedDepthWrite);
  19281. }
  19282. effectiveMaterial._preBind();
  19283. var effect = effectiveMaterial.getEffect();
  19284. // Bind
  19285. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  19286. this._bind(subMesh, effect, fillMode);
  19287. var world = this.getWorldMatrix();
  19288. effectiveMaterial.bind(world, this);
  19289. // Alpha mode
  19290. if (enableAlphaMode) {
  19291. engine.setAlphaMode(effectiveMaterial.alphaMode);
  19292. }
  19293. // Draw
  19294. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw);
  19295. // Unbind
  19296. effectiveMaterial.unbind();
  19297. // Outline - step 2
  19298. if (this.renderOutline && savedDepthWrite) {
  19299. engine.setDepthWrite(true);
  19300. engine.setColorWrite(false);
  19301. scene.getOutlineRenderer().render(subMesh, batch);
  19302. engine.setColorWrite(true);
  19303. }
  19304. // Overlay
  19305. if (this.renderOverlay) {
  19306. var currentMode = engine.getAlphaMode();
  19307. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19308. scene.getOutlineRenderer().render(subMesh, batch, true);
  19309. engine.setAlphaMode(currentMode);
  19310. }
  19311. this.onAfterRenderObservable.notifyObservers(this);
  19312. };
  19313. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  19314. if (isInstance) {
  19315. effectiveMaterial.bindOnlyWorldMatrix(world);
  19316. }
  19317. };
  19318. /**
  19319. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  19320. */
  19321. Mesh.prototype.getEmittedParticleSystems = function () {
  19322. var results = new Array();
  19323. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19324. var particleSystem = this.getScene().particleSystems[index];
  19325. if (particleSystem.emitter === this) {
  19326. results.push(particleSystem);
  19327. }
  19328. }
  19329. return results;
  19330. };
  19331. /**
  19332. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  19333. */
  19334. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  19335. var results = new Array();
  19336. var descendants = this.getDescendants();
  19337. descendants.push(this);
  19338. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19339. var particleSystem = this.getScene().particleSystems[index];
  19340. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  19341. results.push(particleSystem);
  19342. }
  19343. }
  19344. return results;
  19345. };
  19346. Mesh.prototype._checkDelayState = function () {
  19347. var scene = this.getScene();
  19348. if (this._geometry) {
  19349. this._geometry.load(scene);
  19350. }
  19351. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19352. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19353. this._queueLoad(this, scene);
  19354. }
  19355. };
  19356. Mesh.prototype._queueLoad = function (mesh, scene) {
  19357. var _this = this;
  19358. scene._addPendingData(mesh);
  19359. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  19360. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19361. if (data instanceof ArrayBuffer) {
  19362. _this._delayLoadingFunction(data, _this);
  19363. }
  19364. else {
  19365. _this._delayLoadingFunction(JSON.parse(data), _this);
  19366. }
  19367. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19368. scene._removePendingData(_this);
  19369. }, function () { }, scene.database, getBinaryData);
  19370. };
  19371. /**
  19372. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  19373. */
  19374. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  19375. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19376. return false;
  19377. }
  19378. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  19379. return false;
  19380. }
  19381. this._checkDelayState();
  19382. return true;
  19383. };
  19384. /**
  19385. * Sets the mesh material by the material or multiMaterial `id` property.
  19386. * The material `id` is a string identifying the material or the multiMaterial.
  19387. * This method returns nothing.
  19388. */
  19389. Mesh.prototype.setMaterialByID = function (id) {
  19390. var materials = this.getScene().materials;
  19391. var index;
  19392. for (index = 0; index < materials.length; index++) {
  19393. if (materials[index].id === id) {
  19394. this.material = materials[index];
  19395. return;
  19396. }
  19397. }
  19398. // Multi
  19399. var multiMaterials = this.getScene().multiMaterials;
  19400. for (index = 0; index < multiMaterials.length; index++) {
  19401. if (multiMaterials[index].id === id) {
  19402. this.material = multiMaterials[index];
  19403. return;
  19404. }
  19405. }
  19406. };
  19407. /**
  19408. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  19409. */
  19410. Mesh.prototype.getAnimatables = function () {
  19411. var results = [];
  19412. if (this.material) {
  19413. results.push(this.material);
  19414. }
  19415. if (this.skeleton) {
  19416. results.push(this.skeleton);
  19417. }
  19418. return results;
  19419. };
  19420. /**
  19421. * Modifies the mesh geometry according to the passed transformation matrix.
  19422. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  19423. * The mesh normals are modified accordingly the same transformation.
  19424. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19425. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19426. */
  19427. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  19428. // Position
  19429. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19430. return;
  19431. }
  19432. var submeshes = this.subMeshes.splice(0);
  19433. this._resetPointsArrayCache();
  19434. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19435. var temp = [];
  19436. var index;
  19437. for (index = 0; index < data.length; index += 3) {
  19438. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  19439. }
  19440. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  19441. // Normals
  19442. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19443. return;
  19444. }
  19445. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19446. temp = [];
  19447. for (index = 0; index < data.length; index += 3) {
  19448. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  19449. }
  19450. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  19451. // flip faces?
  19452. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  19453. this.flipFaces();
  19454. }
  19455. // Restore submeshes
  19456. this.releaseSubMeshes();
  19457. this.subMeshes = submeshes;
  19458. };
  19459. /**
  19460. * Modifies the mesh geometry according to its own current World Matrix.
  19461. * The mesh World Matrix is then reset.
  19462. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  19463. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19464. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19465. */
  19466. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  19467. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  19468. this.scaling.copyFromFloats(1, 1, 1);
  19469. this.position.copyFromFloats(0, 0, 0);
  19470. this.rotation.copyFromFloats(0, 0, 0);
  19471. //only if quaternion is already set
  19472. if (this.rotationQuaternion) {
  19473. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  19474. }
  19475. this._worldMatrix = BABYLON.Matrix.Identity();
  19476. };
  19477. // Cache
  19478. Mesh.prototype._resetPointsArrayCache = function () {
  19479. this._positions = null;
  19480. };
  19481. Mesh.prototype._generatePointsArray = function () {
  19482. if (this._positions)
  19483. return true;
  19484. this._positions = [];
  19485. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19486. if (!data) {
  19487. return false;
  19488. }
  19489. for (var index = 0; index < data.length; index += 3) {
  19490. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  19491. }
  19492. return true;
  19493. };
  19494. /**
  19495. * Returns a new Mesh object generated from the current mesh properties.
  19496. * This method must not get confused with createInstance().
  19497. * The parameter `name` is a string, the name given to the new mesh.
  19498. * The optional parameter `newParent` can be any Node object (default `null`).
  19499. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  19500. * 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.
  19501. */
  19502. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  19503. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19504. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  19505. };
  19506. /**
  19507. * Disposes the mesh.
  19508. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  19509. */
  19510. Mesh.prototype.dispose = function (doNotRecurse) {
  19511. if (this._geometry) {
  19512. this._geometry.releaseForMesh(this, true);
  19513. }
  19514. // Instances
  19515. if (this._instancesBuffer) {
  19516. this._instancesBuffer.dispose();
  19517. this._instancesBuffer = null;
  19518. }
  19519. while (this.instances.length) {
  19520. this.instances[0].dispose();
  19521. }
  19522. _super.prototype.dispose.call(this, doNotRecurse);
  19523. };
  19524. /**
  19525. * Modifies the mesh geometry according to a displacement map.
  19526. * 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.
  19527. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19528. * This method returns nothing.
  19529. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  19530. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19531. * 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.
  19532. */
  19533. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  19534. var _this = this;
  19535. var scene = this.getScene();
  19536. var onload = function (img) {
  19537. // Getting height map data
  19538. var canvas = document.createElement("canvas");
  19539. var context = canvas.getContext("2d");
  19540. var heightMapWidth = img.width;
  19541. var heightMapHeight = img.height;
  19542. canvas.width = heightMapWidth;
  19543. canvas.height = heightMapHeight;
  19544. context.drawImage(img, 0, 0);
  19545. // Create VertexData from map data
  19546. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19547. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  19548. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  19549. //execute success callback, if set
  19550. if (onSuccess) {
  19551. onSuccess(_this);
  19552. }
  19553. };
  19554. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19555. };
  19556. /**
  19557. * Modifies the mesh geometry according to a displacementMap buffer.
  19558. * 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.
  19559. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19560. * This method returns nothing.
  19561. * 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.
  19562. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  19563. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19564. */
  19565. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  19566. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  19567. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  19568. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19569. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  19570. return;
  19571. }
  19572. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19573. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19574. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19575. var position = BABYLON.Vector3.Zero();
  19576. var normal = BABYLON.Vector3.Zero();
  19577. var uv = BABYLON.Vector2.Zero();
  19578. for (var index = 0; index < positions.length; index += 3) {
  19579. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  19580. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  19581. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  19582. // Compute height
  19583. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  19584. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  19585. var pos = (u + v * heightMapWidth) * 4;
  19586. var r = buffer[pos] / 255.0;
  19587. var g = buffer[pos + 1] / 255.0;
  19588. var b = buffer[pos + 2] / 255.0;
  19589. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  19590. normal.normalize();
  19591. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  19592. position = position.add(normal);
  19593. position.toArray(positions, index);
  19594. }
  19595. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  19596. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  19597. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19598. };
  19599. /**
  19600. * Modify the mesh to get a flat shading rendering.
  19601. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  19602. * This method returns nothing.
  19603. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  19604. */
  19605. Mesh.prototype.convertToFlatShadedMesh = function () {
  19606. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  19607. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19608. var kinds = this.getVerticesDataKinds();
  19609. var vbs = [];
  19610. var data = [];
  19611. var newdata = [];
  19612. var updatableNormals = false;
  19613. var kindIndex;
  19614. var kind;
  19615. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19616. kind = kinds[kindIndex];
  19617. var vertexBuffer = this.getVertexBuffer(kind);
  19618. if (kind === BABYLON.VertexBuffer.NormalKind) {
  19619. updatableNormals = vertexBuffer.isUpdatable();
  19620. kinds.splice(kindIndex, 1);
  19621. kindIndex--;
  19622. continue;
  19623. }
  19624. vbs[kind] = vertexBuffer;
  19625. data[kind] = vbs[kind].getData();
  19626. newdata[kind] = [];
  19627. }
  19628. // Save previous submeshes
  19629. var previousSubmeshes = this.subMeshes.slice(0);
  19630. var indices = this.getIndices();
  19631. var totalIndices = this.getTotalIndices();
  19632. // Generating unique vertices per face
  19633. var index;
  19634. for (index = 0; index < totalIndices; index++) {
  19635. var vertexIndex = indices[index];
  19636. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19637. kind = kinds[kindIndex];
  19638. var stride = vbs[kind].getStrideSize();
  19639. for (var offset = 0; offset < stride; offset++) {
  19640. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19641. }
  19642. }
  19643. }
  19644. // Updating faces & normal
  19645. var normals = [];
  19646. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  19647. for (index = 0; index < totalIndices; index += 3) {
  19648. indices[index] = index;
  19649. indices[index + 1] = index + 1;
  19650. indices[index + 2] = index + 2;
  19651. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  19652. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  19653. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  19654. var p1p2 = p1.subtract(p2);
  19655. var p3p2 = p3.subtract(p2);
  19656. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  19657. // Store same normals for every vertex
  19658. for (var localIndex = 0; localIndex < 3; localIndex++) {
  19659. normals.push(normal.x);
  19660. normals.push(normal.y);
  19661. normals.push(normal.z);
  19662. }
  19663. }
  19664. this.setIndices(indices);
  19665. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  19666. // Updating vertex buffers
  19667. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19668. kind = kinds[kindIndex];
  19669. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19670. }
  19671. // Updating submeshes
  19672. this.releaseSubMeshes();
  19673. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19674. var previousOne = previousSubmeshes[submeshIndex];
  19675. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19676. }
  19677. this.synchronizeInstances();
  19678. };
  19679. /**
  19680. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  19681. * In other words, more vertices, no more indices and a single bigger VBO.
  19682. * This method returns nothing.
  19683. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  19684. *
  19685. */
  19686. Mesh.prototype.convertToUnIndexedMesh = function () {
  19687. /// <summary>Remove indices by unfolding faces into buffers</summary>
  19688. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19689. var kinds = this.getVerticesDataKinds();
  19690. var vbs = [];
  19691. var data = [];
  19692. var newdata = [];
  19693. var updatableNormals = false;
  19694. var kindIndex;
  19695. var kind;
  19696. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19697. kind = kinds[kindIndex];
  19698. var vertexBuffer = this.getVertexBuffer(kind);
  19699. vbs[kind] = vertexBuffer;
  19700. data[kind] = vbs[kind].getData();
  19701. newdata[kind] = [];
  19702. }
  19703. // Save previous submeshes
  19704. var previousSubmeshes = this.subMeshes.slice(0);
  19705. var indices = this.getIndices();
  19706. var totalIndices = this.getTotalIndices();
  19707. // Generating unique vertices per face
  19708. var index;
  19709. for (index = 0; index < totalIndices; index++) {
  19710. var vertexIndex = indices[index];
  19711. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19712. kind = kinds[kindIndex];
  19713. var stride = vbs[kind].getStrideSize();
  19714. for (var offset = 0; offset < stride; offset++) {
  19715. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19716. }
  19717. }
  19718. }
  19719. // Updating indices
  19720. for (index = 0; index < totalIndices; index += 3) {
  19721. indices[index] = index;
  19722. indices[index + 1] = index + 1;
  19723. indices[index + 2] = index + 2;
  19724. }
  19725. this.setIndices(indices);
  19726. // Updating vertex buffers
  19727. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19728. kind = kinds[kindIndex];
  19729. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19730. }
  19731. // Updating submeshes
  19732. this.releaseSubMeshes();
  19733. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19734. var previousOne = previousSubmeshes[submeshIndex];
  19735. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19736. }
  19737. this._unIndexed = true;
  19738. this.synchronizeInstances();
  19739. };
  19740. /**
  19741. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  19742. * This method returns nothing.
  19743. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  19744. */
  19745. Mesh.prototype.flipFaces = function (flipNormals) {
  19746. if (flipNormals === void 0) { flipNormals = false; }
  19747. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  19748. var i;
  19749. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19750. for (i = 0; i < vertex_data.normals.length; i++) {
  19751. vertex_data.normals[i] *= -1;
  19752. }
  19753. }
  19754. var temp;
  19755. for (i = 0; i < vertex_data.indices.length; i += 3) {
  19756. // reassign indices
  19757. temp = vertex_data.indices[i + 1];
  19758. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  19759. vertex_data.indices[i + 2] = temp;
  19760. }
  19761. vertex_data.applyToMesh(this);
  19762. };
  19763. // Instances
  19764. /**
  19765. * Creates a new InstancedMesh object from the mesh model.
  19766. * An instance shares the same properties and the same material than its model.
  19767. * Only these properties of each instance can then be set individually :
  19768. * - position
  19769. * - rotation
  19770. * - rotationQuaternion
  19771. * - setPivotMatrix
  19772. * - scaling
  19773. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  19774. * Warning : this method is not supported for Line mesh and LineSystem
  19775. */
  19776. Mesh.prototype.createInstance = function (name) {
  19777. return new BABYLON.InstancedMesh(name, this);
  19778. };
  19779. /**
  19780. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  19781. * After this call, all the mesh instances have the same submeshes than the current mesh.
  19782. * This method returns nothing.
  19783. */
  19784. Mesh.prototype.synchronizeInstances = function () {
  19785. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  19786. var instance = this.instances[instanceIndex];
  19787. instance._syncSubMeshes();
  19788. }
  19789. };
  19790. /**
  19791. * Simplify the mesh according to the given array of settings.
  19792. * Function will return immediately and will simplify async. It returns nothing.
  19793. * @param settings a collection of simplification settings.
  19794. * @param parallelProcessing should all levels calculate parallel or one after the other.
  19795. * @param type the type of simplification to run.
  19796. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  19797. */
  19798. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  19799. if (parallelProcessing === void 0) { parallelProcessing = true; }
  19800. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  19801. this.getScene().simplificationQueue.addTask({
  19802. settings: settings,
  19803. parallelProcessing: parallelProcessing,
  19804. mesh: this,
  19805. simplificationType: simplificationType,
  19806. successCallback: successCallback
  19807. });
  19808. };
  19809. /**
  19810. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  19811. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  19812. * This should be used together with the simplification to avoid disappearing triangles.
  19813. * @param successCallback an optional success callback to be called after the optimization finished.
  19814. */
  19815. Mesh.prototype.optimizeIndices = function (successCallback) {
  19816. var _this = this;
  19817. var indices = this.getIndices();
  19818. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19819. var vectorPositions = [];
  19820. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  19821. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  19822. }
  19823. var dupes = [];
  19824. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  19825. var realPos = vectorPositions.length - 1 - iteration;
  19826. var testedPosition = vectorPositions[realPos];
  19827. for (var j = 0; j < realPos; ++j) {
  19828. var againstPosition = vectorPositions[j];
  19829. if (testedPosition.equals(againstPosition)) {
  19830. dupes[realPos] = j;
  19831. break;
  19832. }
  19833. }
  19834. }, function () {
  19835. for (var i = 0; i < indices.length; ++i) {
  19836. indices[i] = dupes[indices[i]] || indices[i];
  19837. }
  19838. //indices are now reordered
  19839. var originalSubMeshes = _this.subMeshes.slice(0);
  19840. _this.setIndices(indices);
  19841. _this.subMeshes = originalSubMeshes;
  19842. if (successCallback) {
  19843. successCallback(_this);
  19844. }
  19845. });
  19846. };
  19847. // Statics
  19848. /**
  19849. * Returns a new Mesh object what is a deep copy of the passed mesh.
  19850. * The parameter `parsedMesh` is the mesh to be copied.
  19851. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19852. */
  19853. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  19854. var mesh = new Mesh(parsedMesh.name, scene);
  19855. mesh.id = parsedMesh.id;
  19856. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19857. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19858. if (parsedMesh.rotationQuaternion) {
  19859. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19860. }
  19861. else if (parsedMesh.rotation) {
  19862. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19863. }
  19864. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19865. if (parsedMesh.localMatrix) {
  19866. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19867. }
  19868. else if (parsedMesh.pivotMatrix) {
  19869. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19870. }
  19871. mesh.setEnabled(parsedMesh.isEnabled);
  19872. mesh.isVisible = parsedMesh.isVisible;
  19873. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19874. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19875. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19876. if (parsedMesh.applyFog !== undefined) {
  19877. mesh.applyFog = parsedMesh.applyFog;
  19878. }
  19879. if (parsedMesh.pickable !== undefined) {
  19880. mesh.isPickable = parsedMesh.pickable;
  19881. }
  19882. if (parsedMesh.alphaIndex !== undefined) {
  19883. mesh.alphaIndex = parsedMesh.alphaIndex;
  19884. }
  19885. mesh.receiveShadows = parsedMesh.receiveShadows;
  19886. mesh.billboardMode = parsedMesh.billboardMode;
  19887. if (parsedMesh.visibility !== undefined) {
  19888. mesh.visibility = parsedMesh.visibility;
  19889. }
  19890. mesh.checkCollisions = parsedMesh.checkCollisions;
  19891. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19892. // freezeWorldMatrix
  19893. if (parsedMesh.freezeWorldMatrix) {
  19894. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  19895. }
  19896. // Parent
  19897. if (parsedMesh.parentId) {
  19898. mesh._waitingParentId = parsedMesh.parentId;
  19899. }
  19900. // Actions
  19901. if (parsedMesh.actions !== undefined) {
  19902. mesh._waitingActions = parsedMesh.actions;
  19903. }
  19904. // Geometry
  19905. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19906. if (parsedMesh.delayLoadingFile) {
  19907. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19908. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19909. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19910. if (parsedMesh._binaryInfo) {
  19911. mesh._binaryInfo = parsedMesh._binaryInfo;
  19912. }
  19913. mesh._delayInfo = [];
  19914. if (parsedMesh.hasUVs) {
  19915. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19916. }
  19917. if (parsedMesh.hasUVs2) {
  19918. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19919. }
  19920. if (parsedMesh.hasUVs3) {
  19921. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19922. }
  19923. if (parsedMesh.hasUVs4) {
  19924. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19925. }
  19926. if (parsedMesh.hasUVs5) {
  19927. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19928. }
  19929. if (parsedMesh.hasUVs6) {
  19930. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19931. }
  19932. if (parsedMesh.hasColors) {
  19933. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19934. }
  19935. if (parsedMesh.hasMatricesIndices) {
  19936. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19937. }
  19938. if (parsedMesh.hasMatricesWeights) {
  19939. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19940. }
  19941. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  19942. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19943. mesh._checkDelayState();
  19944. }
  19945. }
  19946. else {
  19947. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  19948. }
  19949. // Material
  19950. if (parsedMesh.materialId) {
  19951. mesh.setMaterialByID(parsedMesh.materialId);
  19952. }
  19953. else {
  19954. mesh.material = null;
  19955. }
  19956. // Skeleton
  19957. if (parsedMesh.skeletonId > -1) {
  19958. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19959. if (parsedMesh.numBoneInfluencers) {
  19960. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  19961. }
  19962. }
  19963. // Animations
  19964. if (parsedMesh.animations) {
  19965. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19966. var parsedAnimation = parsedMesh.animations[animationIndex];
  19967. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19968. }
  19969. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  19970. }
  19971. if (parsedMesh.autoAnimate) {
  19972. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  19973. }
  19974. // Layer Mask
  19975. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19976. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19977. }
  19978. else {
  19979. mesh.layerMask = 0x0FFFFFFF;
  19980. }
  19981. //(Deprecated) physics
  19982. if (parsedMesh.physicsImpostor) {
  19983. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  19984. mass: parsedMesh.physicsMass,
  19985. friction: parsedMesh.physicsFriction,
  19986. restitution: parsedMesh.physicsRestitution
  19987. }, scene);
  19988. }
  19989. // Instances
  19990. if (parsedMesh.instances) {
  19991. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19992. var parsedInstance = parsedMesh.instances[index];
  19993. var instance = mesh.createInstance(parsedInstance.name);
  19994. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19995. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19996. if (parsedInstance.rotationQuaternion) {
  19997. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19998. }
  19999. else if (parsedInstance.rotation) {
  20000. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20001. }
  20002. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20003. instance.checkCollisions = mesh.checkCollisions;
  20004. if (parsedMesh.animations) {
  20005. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20006. parsedAnimation = parsedMesh.animations[animationIndex];
  20007. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20008. }
  20009. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  20010. }
  20011. }
  20012. }
  20013. return mesh;
  20014. };
  20015. /**
  20016. * Creates a ribbon mesh.
  20017. * Please consider using the same method from the MeshBuilder class instead.
  20018. * 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.
  20019. *
  20020. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20021. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20022. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20023. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20024. * 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.
  20025. * 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.
  20026. * 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
  20027. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20028. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20029. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20030. */
  20031. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  20032. return BABYLON.MeshBuilder.CreateRibbon(name, {
  20033. pathArray: pathArray,
  20034. closeArray: closeArray,
  20035. closePath: closePath,
  20036. offset: offset,
  20037. updatable: updatable,
  20038. sideOrientation: sideOrientation,
  20039. instance: instance
  20040. }, scene);
  20041. };
  20042. /**
  20043. * Creates a plane polygonal mesh. By default, this is a disc.
  20044. * Please consider using the same method from the MeshBuilder class instead.
  20045. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20046. * 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.
  20047. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20048. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20049. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20050. */
  20051. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  20052. var options = {
  20053. radius: radius,
  20054. tessellation: tessellation,
  20055. sideOrientation: sideOrientation,
  20056. updatable: updatable
  20057. };
  20058. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  20059. };
  20060. /**
  20061. * Creates a box mesh.
  20062. * Please consider using the same method from the MeshBuilder class instead.
  20063. * The parameter `size` sets the size (float) of each box side (default 1).
  20064. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20065. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20066. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20067. */
  20068. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  20069. var options = {
  20070. size: size,
  20071. sideOrientation: sideOrientation,
  20072. updatable: updatable
  20073. };
  20074. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  20075. };
  20076. /**
  20077. * Creates a sphere mesh.
  20078. * Please consider using the same method from the MeshBuilder class instead.
  20079. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20080. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20081. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20082. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20083. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20084. */
  20085. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  20086. var options = {
  20087. segments: segments,
  20088. diameterX: diameter,
  20089. diameterY: diameter,
  20090. diameterZ: diameter,
  20091. sideOrientation: sideOrientation,
  20092. updatable: updatable
  20093. };
  20094. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  20095. };
  20096. /**
  20097. * Creates a cylinder or a cone mesh.
  20098. * Please consider using the same method from the MeshBuilder class instead.
  20099. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20100. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20101. * 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.
  20102. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20103. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20104. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20105. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20106. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20107. */
  20108. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  20109. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  20110. if (scene !== undefined) {
  20111. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  20112. updatable = scene;
  20113. }
  20114. scene = subdivisions;
  20115. subdivisions = 1;
  20116. }
  20117. var options = {
  20118. height: height,
  20119. diameterTop: diameterTop,
  20120. diameterBottom: diameterBottom,
  20121. tessellation: tessellation,
  20122. subdivisions: subdivisions,
  20123. sideOrientation: sideOrientation,
  20124. updatable: updatable
  20125. };
  20126. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  20127. };
  20128. // Torus (Code from SharpDX.org)
  20129. /**
  20130. * Creates a torus mesh.
  20131. * Please consider using the same method from the MeshBuilder class instead.
  20132. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20133. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20134. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20135. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20136. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20137. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20138. */
  20139. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  20140. var options = {
  20141. diameter: diameter,
  20142. thickness: thickness,
  20143. tessellation: tessellation,
  20144. sideOrientation: sideOrientation,
  20145. updatable: updatable
  20146. };
  20147. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  20148. };
  20149. /**
  20150. * Creates a torus knot mesh.
  20151. * Please consider using the same method from the MeshBuilder class instead.
  20152. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20153. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20154. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20155. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20156. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20157. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20158. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20159. */
  20160. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  20161. var options = {
  20162. radius: radius,
  20163. tube: tube,
  20164. radialSegments: radialSegments,
  20165. tubularSegments: tubularSegments,
  20166. p: p,
  20167. q: q,
  20168. sideOrientation: sideOrientation,
  20169. updatable: updatable
  20170. };
  20171. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  20172. };
  20173. /**
  20174. * Creates a line mesh.
  20175. * Please consider using the same method from the MeshBuilder class instead.
  20176. * 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.
  20177. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20178. * The parameter `points` is an array successive Vector3.
  20179. * 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
  20180. * When updating an instance, remember that only point positions can change, not the number of points.
  20181. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20182. */
  20183. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  20184. var options = {
  20185. points: points,
  20186. updatable: updatable,
  20187. instance: instance
  20188. };
  20189. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  20190. };
  20191. /**
  20192. * Creates a dashed line mesh.
  20193. * Please consider using the same method from the MeshBuilder class instead.
  20194. * 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.
  20195. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20196. * The parameter `points` is an array successive Vector3.
  20197. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20198. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20199. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20200. * 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
  20201. * When updating an instance, remember that only point positions can change, not the number of points.
  20202. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20203. */
  20204. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  20205. var options = {
  20206. points: points,
  20207. dashSize: dashSize,
  20208. gapSize: gapSize,
  20209. dashNb: dashNb,
  20210. updatable: updatable,
  20211. instance: instance
  20212. };
  20213. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  20214. };
  20215. /**
  20216. * Creates an extruded shape mesh.
  20217. * 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.
  20218. * Please consider using the same method from the MeshBuilder class instead.
  20219. *
  20220. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20221. * 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
  20222. * extruded along the Z axis.
  20223. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20224. * 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.
  20225. * The parameter `scale` (float, default 1) is the value to scale the shape.
  20226. * 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
  20227. * 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
  20228. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20229. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20230. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20231. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20232. */
  20233. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  20234. var options = {
  20235. shape: shape,
  20236. path: path,
  20237. scale: scale,
  20238. rotation: rotation,
  20239. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20240. sideOrientation: sideOrientation,
  20241. instance: instance,
  20242. updatable: updatable
  20243. };
  20244. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  20245. };
  20246. /**
  20247. * Creates an custom extruded shape mesh.
  20248. * 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.
  20249. * Please consider using the same method from the MeshBuilder class instead.
  20250. *
  20251. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20252. * 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
  20253. * extruded along the Z axis.
  20254. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20255. * 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
  20256. * and the distance of this point from the begining of the path :
  20257. * ```javascript
  20258. * var rotationFunction = function(i, distance) {
  20259. * // do things
  20260. * return rotationValue; }
  20261. * ```
  20262. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20263. * 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
  20264. * and the distance of this point from the begining of the path :
  20265. * ```javascript
  20266. * var scaleFunction = function(i, distance) {
  20267. * // do things
  20268. * return scaleValue;}
  20269. * ```
  20270. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20271. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20272. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20273. * 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
  20274. * 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
  20275. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20276. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20277. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20278. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20279. */
  20280. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  20281. var options = {
  20282. shape: shape,
  20283. path: path,
  20284. scaleFunction: scaleFunction,
  20285. rotationFunction: rotationFunction,
  20286. ribbonCloseArray: ribbonCloseArray,
  20287. ribbonClosePath: ribbonClosePath,
  20288. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20289. sideOrientation: sideOrientation,
  20290. instance: instance,
  20291. updatable: updatable
  20292. };
  20293. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  20294. };
  20295. /**
  20296. * Creates lathe mesh.
  20297. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20298. * Please consider using the same method from the MeshBuilder class instead.
  20299. * 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
  20300. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20301. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20302. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20303. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20304. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20305. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20306. */
  20307. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  20308. var options = {
  20309. shape: shape,
  20310. radius: radius,
  20311. tessellation: tessellation,
  20312. sideOrientation: sideOrientation,
  20313. updatable: updatable
  20314. };
  20315. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  20316. };
  20317. /**
  20318. * Creates a plane mesh.
  20319. * Please consider using the same method from the MeshBuilder class instead.
  20320. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20321. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20322. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20323. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20324. */
  20325. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  20326. var options = {
  20327. size: size,
  20328. width: size,
  20329. height: size,
  20330. sideOrientation: sideOrientation,
  20331. updatable: updatable
  20332. };
  20333. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  20334. };
  20335. /**
  20336. * Creates a ground mesh.
  20337. * Please consider using the same method from the MeshBuilder class instead.
  20338. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20339. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20340. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20341. */
  20342. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  20343. var options = {
  20344. width: width,
  20345. height: height,
  20346. subdivisions: subdivisions,
  20347. updatable: updatable
  20348. };
  20349. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  20350. };
  20351. /**
  20352. * Creates a tiled ground mesh.
  20353. * Please consider using the same method from the MeshBuilder class instead.
  20354. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20355. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20356. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20357. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20358. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20359. * numbers of subdivisions on the ground width and height of each tile.
  20360. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20361. */
  20362. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  20363. var options = {
  20364. xmin: xmin,
  20365. zmin: zmin,
  20366. xmax: xmax,
  20367. zmax: zmax,
  20368. subdivisions: subdivisions,
  20369. precision: precision,
  20370. updatable: updatable
  20371. };
  20372. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  20373. };
  20374. /**
  20375. * Creates a ground mesh from a height map.
  20376. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  20377. * Please consider using the same method from the MeshBuilder class instead.
  20378. * The parameter `url` sets the URL of the height map image resource.
  20379. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  20380. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  20381. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  20382. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  20383. * 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).
  20384. * This function is passed the newly built mesh :
  20385. * ```javascript
  20386. * function(mesh) { // do things
  20387. * return; }
  20388. * ```
  20389. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20390. */
  20391. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  20392. var options = {
  20393. width: width,
  20394. height: height,
  20395. subdivisions: subdivisions,
  20396. minHeight: minHeight,
  20397. maxHeight: maxHeight,
  20398. updatable: updatable,
  20399. onReady: onReady
  20400. };
  20401. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  20402. };
  20403. /**
  20404. * Creates a tube mesh.
  20405. * 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.
  20406. * Please consider using the same method from the MeshBuilder class instead.
  20407. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  20408. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  20409. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  20410. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  20411. * 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.
  20412. * It must return a radius value (positive float) :
  20413. * ```javascript
  20414. * var radiusFunction = function(i, distance) {
  20415. * // do things
  20416. * return radius; }
  20417. * ```
  20418. * 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
  20419. * 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
  20420. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20421. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20422. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20423. */
  20424. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  20425. var options = {
  20426. path: path,
  20427. radius: radius,
  20428. tessellation: tessellation,
  20429. radiusFunction: radiusFunction,
  20430. arc: 1,
  20431. cap: cap,
  20432. updatable: updatable,
  20433. sideOrientation: sideOrientation,
  20434. instance: instance
  20435. };
  20436. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  20437. };
  20438. /**
  20439. * Creates a polyhedron mesh.
  20440. * Please consider using the same method from the MeshBuilder class instead.
  20441. * 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
  20442. * to choose the wanted type.
  20443. * The parameter `size` (positive float, default 1) sets the polygon size.
  20444. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  20445. * 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`.
  20446. * 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
  20447. * 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)`).
  20448. * 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
  20449. * 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.
  20450. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20451. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20452. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20453. */
  20454. Mesh.CreatePolyhedron = function (name, options, scene) {
  20455. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  20456. };
  20457. /**
  20458. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  20459. * Please consider using the same method from the MeshBuilder class instead.
  20460. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  20461. * 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`).
  20462. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  20463. * 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.
  20464. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20465. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20466. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20467. */
  20468. Mesh.CreateIcoSphere = function (name, options, scene) {
  20469. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  20470. };
  20471. /**
  20472. * Creates a decal mesh.
  20473. * Please consider using the same method from the MeshBuilder class instead.
  20474. * 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.
  20475. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  20476. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  20477. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  20478. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  20479. */
  20480. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  20481. var options = {
  20482. position: position,
  20483. normal: normal,
  20484. size: size,
  20485. angle: angle
  20486. };
  20487. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  20488. };
  20489. // Skeletons
  20490. /**
  20491. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20492. */
  20493. Mesh.prototype.setPositionsForCPUSkinning = function () {
  20494. var source;
  20495. if (!this._sourcePositions) {
  20496. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20497. this._sourcePositions = new Float32Array(source);
  20498. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  20499. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  20500. }
  20501. }
  20502. return this._sourcePositions;
  20503. };
  20504. /**
  20505. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20506. */
  20507. Mesh.prototype.setNormalsForCPUSkinning = function () {
  20508. var source;
  20509. if (!this._sourceNormals) {
  20510. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20511. this._sourceNormals = new Float32Array(source);
  20512. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  20513. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  20514. }
  20515. }
  20516. return this._sourceNormals;
  20517. };
  20518. /**
  20519. * Update the vertex buffers by applying transformation from the bones
  20520. * @param {skeleton} skeleton to apply
  20521. */
  20522. Mesh.prototype.applySkeleton = function (skeleton) {
  20523. if (!this.geometry) {
  20524. return;
  20525. }
  20526. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  20527. return;
  20528. }
  20529. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  20530. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20531. return this;
  20532. }
  20533. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20534. return this;
  20535. }
  20536. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20537. return this;
  20538. }
  20539. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20540. return this;
  20541. }
  20542. if (!this._sourcePositions) {
  20543. this.setPositionsForCPUSkinning();
  20544. }
  20545. if (!this._sourceNormals) {
  20546. this.setNormalsForCPUSkinning();
  20547. }
  20548. // positionsData checks for not being Float32Array will only pass at most once
  20549. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20550. if (!(positionsData instanceof Float32Array)) {
  20551. positionsData = new Float32Array(positionsData);
  20552. }
  20553. // normalsData checks for not being Float32Array will only pass at most once
  20554. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20555. if (!(normalsData instanceof Float32Array)) {
  20556. normalsData = new Float32Array(normalsData);
  20557. }
  20558. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20559. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20560. var needExtras = this.numBoneInfluencers > 4;
  20561. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  20562. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  20563. var skeletonMatrices = skeleton.getTransformMatrices(this);
  20564. var tempVector3 = BABYLON.Vector3.Zero();
  20565. var finalMatrix = new BABYLON.Matrix();
  20566. var tempMatrix = new BABYLON.Matrix();
  20567. var matWeightIdx = 0;
  20568. var inf;
  20569. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  20570. var weight;
  20571. for (inf = 0; inf < 4; inf++) {
  20572. weight = matricesWeightsData[matWeightIdx + inf];
  20573. if (weight > 0) {
  20574. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20575. finalMatrix.addToSelf(tempMatrix);
  20576. }
  20577. else
  20578. break;
  20579. }
  20580. if (needExtras) {
  20581. for (inf = 0; inf < 4; inf++) {
  20582. weight = matricesWeightsExtraData[matWeightIdx + inf];
  20583. if (weight > 0) {
  20584. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20585. finalMatrix.addToSelf(tempMatrix);
  20586. }
  20587. else
  20588. break;
  20589. }
  20590. }
  20591. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  20592. tempVector3.toArray(positionsData, index);
  20593. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  20594. tempVector3.toArray(normalsData, index);
  20595. finalMatrix.reset();
  20596. }
  20597. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  20598. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  20599. return this;
  20600. };
  20601. // Tools
  20602. /**
  20603. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  20604. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  20605. */
  20606. Mesh.MinMax = function (meshes) {
  20607. var minVector = null;
  20608. var maxVector = null;
  20609. for (var i in meshes) {
  20610. var mesh = meshes[i];
  20611. var boundingBox = mesh.getBoundingInfo().boundingBox;
  20612. if (!minVector) {
  20613. minVector = boundingBox.minimumWorld;
  20614. maxVector = boundingBox.maximumWorld;
  20615. continue;
  20616. }
  20617. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  20618. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  20619. }
  20620. return {
  20621. min: minVector,
  20622. max: maxVector
  20623. };
  20624. };
  20625. /**
  20626. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  20627. */
  20628. Mesh.Center = function (meshesOrMinMaxVector) {
  20629. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  20630. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  20631. };
  20632. /**
  20633. * Merge the array of meshes into a single mesh for performance reasons.
  20634. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  20635. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  20636. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  20637. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  20638. */
  20639. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  20640. if (disposeSource === void 0) { disposeSource = true; }
  20641. var index;
  20642. if (!allow32BitsIndices) {
  20643. var totalVertices = 0;
  20644. // Counting vertices
  20645. for (index = 0; index < meshes.length; index++) {
  20646. if (meshes[index]) {
  20647. totalVertices += meshes[index].getTotalVertices();
  20648. if (totalVertices > 65536) {
  20649. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  20650. return null;
  20651. }
  20652. }
  20653. }
  20654. }
  20655. // Merge
  20656. var vertexData;
  20657. var otherVertexData;
  20658. var source;
  20659. for (index = 0; index < meshes.length; index++) {
  20660. if (meshes[index]) {
  20661. meshes[index].computeWorldMatrix(true);
  20662. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  20663. otherVertexData.transform(meshes[index].getWorldMatrix());
  20664. if (vertexData) {
  20665. vertexData.merge(otherVertexData);
  20666. }
  20667. else {
  20668. vertexData = otherVertexData;
  20669. source = meshes[index];
  20670. }
  20671. }
  20672. }
  20673. if (!meshSubclass) {
  20674. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  20675. }
  20676. vertexData.applyToMesh(meshSubclass);
  20677. // Setting properties
  20678. meshSubclass.material = source.material;
  20679. meshSubclass.checkCollisions = source.checkCollisions;
  20680. // Cleaning
  20681. if (disposeSource) {
  20682. for (index = 0; index < meshes.length; index++) {
  20683. if (meshes[index]) {
  20684. meshes[index].dispose();
  20685. }
  20686. }
  20687. }
  20688. return meshSubclass;
  20689. };
  20690. // Consts
  20691. Mesh._FRONTSIDE = 0;
  20692. Mesh._BACKSIDE = 1;
  20693. Mesh._DOUBLESIDE = 2;
  20694. Mesh._DEFAULTSIDE = 0;
  20695. Mesh._NO_CAP = 0;
  20696. Mesh._CAP_START = 1;
  20697. Mesh._CAP_END = 2;
  20698. Mesh._CAP_ALL = 3;
  20699. return Mesh;
  20700. })(BABYLON.AbstractMesh);
  20701. BABYLON.Mesh = Mesh;
  20702. })(BABYLON || (BABYLON = {}));
  20703. var BABYLON;
  20704. (function (BABYLON) {
  20705. var SubMesh = (function () {
  20706. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  20707. if (createBoundingBox === void 0) { createBoundingBox = true; }
  20708. this.materialIndex = materialIndex;
  20709. this.verticesStart = verticesStart;
  20710. this.verticesCount = verticesCount;
  20711. this.indexStart = indexStart;
  20712. this.indexCount = indexCount;
  20713. this._renderId = 0;
  20714. this._mesh = mesh;
  20715. this._renderingMesh = renderingMesh || mesh;
  20716. mesh.subMeshes.push(this);
  20717. this._trianglePlanes = [];
  20718. this._id = mesh.subMeshes.length - 1;
  20719. if (createBoundingBox) {
  20720. this.refreshBoundingInfo();
  20721. mesh.computeWorldMatrix(true);
  20722. }
  20723. }
  20724. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  20725. get: function () {
  20726. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  20727. },
  20728. enumerable: true,
  20729. configurable: true
  20730. });
  20731. SubMesh.prototype.getBoundingInfo = function () {
  20732. if (this.IsGlobal) {
  20733. return this._mesh.getBoundingInfo();
  20734. }
  20735. return this._boundingInfo;
  20736. };
  20737. SubMesh.prototype.getMesh = function () {
  20738. return this._mesh;
  20739. };
  20740. SubMesh.prototype.getRenderingMesh = function () {
  20741. return this._renderingMesh;
  20742. };
  20743. SubMesh.prototype.getMaterial = function () {
  20744. var rootMaterial = this._renderingMesh.material;
  20745. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  20746. var multiMaterial = rootMaterial;
  20747. return multiMaterial.getSubMaterial(this.materialIndex);
  20748. }
  20749. if (!rootMaterial) {
  20750. return this._mesh.getScene().defaultMaterial;
  20751. }
  20752. return rootMaterial;
  20753. };
  20754. // Methods
  20755. SubMesh.prototype.refreshBoundingInfo = function () {
  20756. this._lastColliderWorldVertices = null;
  20757. if (this.IsGlobal) {
  20758. return;
  20759. }
  20760. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20761. if (!data) {
  20762. this._boundingInfo = this._mesh._boundingInfo;
  20763. return;
  20764. }
  20765. var indices = this._renderingMesh.getIndices();
  20766. var extend;
  20767. //is this the only submesh?
  20768. if (this.indexStart === 0 && this.indexCount === indices.length) {
  20769. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  20770. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  20771. }
  20772. else {
  20773. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  20774. }
  20775. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20776. };
  20777. SubMesh.prototype._checkCollision = function (collider) {
  20778. return this.getBoundingInfo()._checkCollision(collider);
  20779. };
  20780. SubMesh.prototype.updateBoundingInfo = function (world) {
  20781. if (!this.getBoundingInfo()) {
  20782. this.refreshBoundingInfo();
  20783. }
  20784. this.getBoundingInfo().update(world);
  20785. };
  20786. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  20787. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  20788. };
  20789. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20790. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  20791. };
  20792. SubMesh.prototype.render = function (enableAlphaMode) {
  20793. this._renderingMesh.render(this, enableAlphaMode);
  20794. };
  20795. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  20796. if (!this._linesIndexBuffer) {
  20797. var linesIndices = [];
  20798. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  20799. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  20800. }
  20801. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  20802. this.linesIndexCount = linesIndices.length;
  20803. }
  20804. return this._linesIndexBuffer;
  20805. };
  20806. SubMesh.prototype.canIntersects = function (ray) {
  20807. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  20808. };
  20809. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  20810. var intersectInfo = null;
  20811. // LineMesh first as it's also a Mesh...
  20812. if (this._mesh instanceof BABYLON.LinesMesh) {
  20813. var lineMesh = this._mesh;
  20814. // Line test
  20815. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  20816. var p0 = positions[indices[index]];
  20817. var p1 = positions[indices[index + 1]];
  20818. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  20819. if (length < 0) {
  20820. continue;
  20821. }
  20822. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  20823. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  20824. if (fastCheck) {
  20825. break;
  20826. }
  20827. }
  20828. }
  20829. }
  20830. else {
  20831. // Triangles test
  20832. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  20833. var p0 = positions[indices[index]];
  20834. var p1 = positions[indices[index + 1]];
  20835. var p2 = positions[indices[index + 2]];
  20836. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  20837. if (currentIntersectInfo) {
  20838. if (currentIntersectInfo.distance < 0) {
  20839. continue;
  20840. }
  20841. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20842. intersectInfo = currentIntersectInfo;
  20843. intersectInfo.faceId = index / 3;
  20844. if (fastCheck) {
  20845. break;
  20846. }
  20847. }
  20848. }
  20849. }
  20850. }
  20851. return intersectInfo;
  20852. };
  20853. // Clone
  20854. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  20855. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  20856. if (!this.IsGlobal) {
  20857. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  20858. }
  20859. return result;
  20860. };
  20861. // Dispose
  20862. SubMesh.prototype.dispose = function () {
  20863. if (this._linesIndexBuffer) {
  20864. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  20865. this._linesIndexBuffer = null;
  20866. }
  20867. // Remove from mesh
  20868. var index = this._mesh.subMeshes.indexOf(this);
  20869. this._mesh.subMeshes.splice(index, 1);
  20870. };
  20871. // Statics
  20872. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  20873. var minVertexIndex = Number.MAX_VALUE;
  20874. var maxVertexIndex = -Number.MAX_VALUE;
  20875. renderingMesh = renderingMesh || mesh;
  20876. var indices = renderingMesh.getIndices();
  20877. for (var index = startIndex; index < startIndex + indexCount; index++) {
  20878. var vertexIndex = indices[index];
  20879. if (vertexIndex < minVertexIndex)
  20880. minVertexIndex = vertexIndex;
  20881. if (vertexIndex > maxVertexIndex)
  20882. maxVertexIndex = vertexIndex;
  20883. }
  20884. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  20885. };
  20886. return SubMesh;
  20887. })();
  20888. BABYLON.SubMesh = SubMesh;
  20889. })(BABYLON || (BABYLON = {}));
  20890. var BABYLON;
  20891. (function (BABYLON) {
  20892. var MeshBuilder = (function () {
  20893. function MeshBuilder() {
  20894. }
  20895. /**
  20896. * Creates a box mesh.
  20897. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  20898. * The parameter `size` sets the size (float) of each box side (default 1).
  20899. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  20900. * 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).
  20901. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  20902. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20903. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20904. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20905. */
  20906. MeshBuilder.CreateBox = function (name, options, scene) {
  20907. var box = new BABYLON.Mesh(name, scene);
  20908. var vertexData = BABYLON.VertexData.CreateBox(options);
  20909. vertexData.applyToMesh(box, options.updatable);
  20910. return box;
  20911. };
  20912. /**
  20913. * Creates a sphere mesh.
  20914. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  20915. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20916. * 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`).
  20917. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20918. * 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
  20919. * 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).
  20920. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20921. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20922. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20923. */
  20924. MeshBuilder.CreateSphere = function (name, options, scene) {
  20925. var sphere = new BABYLON.Mesh(name, scene);
  20926. var vertexData = BABYLON.VertexData.CreateSphere(options);
  20927. vertexData.applyToMesh(sphere, options.updatable);
  20928. return sphere;
  20929. };
  20930. /**
  20931. * Creates a plane polygonal mesh. By default, this is a disc.
  20932. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  20933. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20934. * 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.
  20935. * 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
  20936. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20937. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20938. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20939. */
  20940. MeshBuilder.CreateDisc = function (name, options, scene) {
  20941. var disc = new BABYLON.Mesh(name, scene);
  20942. var vertexData = BABYLON.VertexData.CreateDisc(options);
  20943. vertexData.applyToMesh(disc, options.updatable);
  20944. return disc;
  20945. };
  20946. /**
  20947. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  20948. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  20949. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  20950. * 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`).
  20951. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  20952. * 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.
  20953. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20954. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20955. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20956. */
  20957. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  20958. var sphere = new BABYLON.Mesh(name, scene);
  20959. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  20960. vertexData.applyToMesh(sphere, options.updatable);
  20961. return sphere;
  20962. };
  20963. ;
  20964. /**
  20965. * Creates a ribbon mesh.
  20966. * 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.
  20967. *
  20968. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20969. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20970. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20971. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20972. * 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.
  20973. * 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.
  20974. * 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
  20975. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20976. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20977. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20978. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20979. */
  20980. MeshBuilder.CreateRibbon = function (name, options, scene) {
  20981. var pathArray = options.pathArray;
  20982. var closeArray = options.closeArray;
  20983. var closePath = options.closePath;
  20984. var offset = options.offset;
  20985. var sideOrientation = options.sideOrientation;
  20986. var instance = options.instance;
  20987. var updatable = options.updatable;
  20988. if (instance) {
  20989. // positionFunction : ribbon case
  20990. // only pathArray and sideOrientation parameters are taken into account for positions update
  20991. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  20992. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  20993. var positionFunction = function (positions) {
  20994. var minlg = pathArray[0].length;
  20995. var i = 0;
  20996. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  20997. for (var si = 1; si <= ns; si++) {
  20998. for (var p = 0; p < pathArray.length; p++) {
  20999. var path = pathArray[p];
  21000. var l = path.length;
  21001. minlg = (minlg < l) ? minlg : l;
  21002. var j = 0;
  21003. while (j < minlg) {
  21004. positions[i] = path[j].x;
  21005. positions[i + 1] = path[j].y;
  21006. positions[i + 2] = path[j].z;
  21007. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  21008. BABYLON.Tmp.Vector3[0].x = path[j].x;
  21009. }
  21010. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  21011. BABYLON.Tmp.Vector3[1].x = path[j].x;
  21012. }
  21013. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  21014. BABYLON.Tmp.Vector3[0].y = path[j].y;
  21015. }
  21016. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  21017. BABYLON.Tmp.Vector3[1].y = path[j].y;
  21018. }
  21019. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  21020. BABYLON.Tmp.Vector3[0].z = path[j].z;
  21021. }
  21022. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  21023. BABYLON.Tmp.Vector3[1].z = path[j].z;
  21024. }
  21025. j++;
  21026. i += 3;
  21027. }
  21028. if (instance._closePath) {
  21029. positions[i] = path[0].x;
  21030. positions[i + 1] = path[0].y;
  21031. positions[i + 2] = path[0].z;
  21032. i += 3;
  21033. }
  21034. }
  21035. }
  21036. };
  21037. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21038. positionFunction(positions);
  21039. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  21040. instance._boundingInfo.update(instance._worldMatrix);
  21041. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21042. if (!(instance.areNormalsFrozen)) {
  21043. var indices = instance.getIndices();
  21044. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21045. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21046. if (instance._closePath) {
  21047. var indexFirst = 0;
  21048. var indexLast = 0;
  21049. for (var p = 0; p < pathArray.length; p++) {
  21050. indexFirst = instance._idx[p] * 3;
  21051. if (p + 1 < pathArray.length) {
  21052. indexLast = (instance._idx[p + 1] - 1) * 3;
  21053. }
  21054. else {
  21055. indexLast = normals.length - 3;
  21056. }
  21057. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  21058. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  21059. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  21060. normals[indexLast] = normals[indexFirst];
  21061. normals[indexLast + 1] = normals[indexFirst + 1];
  21062. normals[indexLast + 2] = normals[indexFirst + 2];
  21063. }
  21064. }
  21065. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21066. }
  21067. return instance;
  21068. }
  21069. else {
  21070. var ribbon = new BABYLON.Mesh(name, scene);
  21071. ribbon.sideOrientation = sideOrientation;
  21072. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  21073. if (closePath) {
  21074. ribbon._idx = vertexData._idx;
  21075. }
  21076. ribbon._closePath = closePath;
  21077. ribbon._closeArray = closeArray;
  21078. vertexData.applyToMesh(ribbon, updatable);
  21079. return ribbon;
  21080. }
  21081. };
  21082. /**
  21083. * Creates a cylinder or a cone mesh.
  21084. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  21085. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21086. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21087. * 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.
  21088. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21089. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21090. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  21091. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  21092. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  21093. * 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).
  21094. * 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
  21095. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  21096. * 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
  21097. * 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.
  21098. * If `enclose` is false, a ring surface is one element.
  21099. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  21100. * 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
  21101. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21102. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21103. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21104. */
  21105. MeshBuilder.CreateCylinder = function (name, options, scene) {
  21106. var cylinder = new BABYLON.Mesh(name, scene);
  21107. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  21108. vertexData.applyToMesh(cylinder, options.updatable);
  21109. return cylinder;
  21110. };
  21111. /**
  21112. * Creates a torus mesh.
  21113. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  21114. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21115. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21116. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21117. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21118. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21119. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21120. */
  21121. MeshBuilder.CreateTorus = function (name, options, scene) {
  21122. var torus = new BABYLON.Mesh(name, scene);
  21123. var vertexData = BABYLON.VertexData.CreateTorus(options);
  21124. vertexData.applyToMesh(torus, options.updatable);
  21125. return torus;
  21126. };
  21127. /**
  21128. * Creates a torus knot mesh.
  21129. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  21130. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21131. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21132. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21133. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21134. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21135. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21136. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21137. */
  21138. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  21139. var torusKnot = new BABYLON.Mesh(name, scene);
  21140. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  21141. vertexData.applyToMesh(torusKnot, options.updatable);
  21142. return torusKnot;
  21143. };
  21144. /**
  21145. * Creates a line system mesh.
  21146. * A line system is a pool of many lines gathered in a single mesh.
  21147. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  21148. * 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.
  21149. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  21150. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  21151. * 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
  21152. * 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
  21153. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  21154. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21155. */
  21156. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  21157. var instance = options.instance;
  21158. var lines = options.lines;
  21159. if (instance) {
  21160. var positionFunction = function (positions) {
  21161. var i = 0;
  21162. for (var l = 0; l < lines.length; l++) {
  21163. var points = lines[l];
  21164. for (var p = 0; p < points.length; p++) {
  21165. positions[i] = points[p].x;
  21166. positions[i + 1] = points[p].y;
  21167. positions[i + 2] = points[p].z;
  21168. i += 3;
  21169. }
  21170. }
  21171. };
  21172. instance.updateMeshPositions(positionFunction, false);
  21173. return instance;
  21174. }
  21175. // line system creation
  21176. var lineSystem = new BABYLON.LinesMesh(name, scene);
  21177. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  21178. vertexData.applyToMesh(lineSystem, options.updatable);
  21179. return lineSystem;
  21180. };
  21181. /**
  21182. * Creates a line mesh.
  21183. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  21184. * 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.
  21185. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21186. * The parameter `points` is an array successive Vector3.
  21187. * 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
  21188. * When updating an instance, remember that only point positions can change, not the number of points.
  21189. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21190. */
  21191. MeshBuilder.CreateLines = function (name, options, scene) {
  21192. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  21193. return lines;
  21194. };
  21195. /**
  21196. * Creates a dashed line mesh.
  21197. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  21198. * 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.
  21199. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21200. * The parameter `points` is an array successive Vector3.
  21201. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21202. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21203. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21204. * 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
  21205. * When updating an instance, remember that only point positions can change, not the number of points.
  21206. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21207. */
  21208. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  21209. var points = options.points;
  21210. var instance = options.instance;
  21211. var gapSize = options.gapSize;
  21212. var dashNb = options.dashNb;
  21213. var dashSize = options.dashSize;
  21214. if (instance) {
  21215. var positionFunction = function (positions) {
  21216. var curvect = BABYLON.Vector3.Zero();
  21217. var nbSeg = positions.length / 6;
  21218. var lg = 0;
  21219. var nb = 0;
  21220. var shft = 0;
  21221. var dashshft = 0;
  21222. var curshft = 0;
  21223. var p = 0;
  21224. var i = 0;
  21225. var j = 0;
  21226. for (i = 0; i < points.length - 1; i++) {
  21227. points[i + 1].subtractToRef(points[i], curvect);
  21228. lg += curvect.length();
  21229. }
  21230. shft = lg / nbSeg;
  21231. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  21232. for (i = 0; i < points.length - 1; i++) {
  21233. points[i + 1].subtractToRef(points[i], curvect);
  21234. nb = Math.floor(curvect.length() / shft);
  21235. curvect.normalize();
  21236. j = 0;
  21237. while (j < nb && p < positions.length) {
  21238. curshft = shft * j;
  21239. positions[p] = points[i].x + curshft * curvect.x;
  21240. positions[p + 1] = points[i].y + curshft * curvect.y;
  21241. positions[p + 2] = points[i].z + curshft * curvect.z;
  21242. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  21243. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  21244. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  21245. p += 6;
  21246. j++;
  21247. }
  21248. }
  21249. while (p < positions.length) {
  21250. positions[p] = points[i].x;
  21251. positions[p + 1] = points[i].y;
  21252. positions[p + 2] = points[i].z;
  21253. p += 3;
  21254. }
  21255. };
  21256. instance.updateMeshPositions(positionFunction, false);
  21257. return instance;
  21258. }
  21259. // dashed lines creation
  21260. var dashedLines = new BABYLON.LinesMesh(name, scene);
  21261. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  21262. vertexData.applyToMesh(dashedLines, options.updatable);
  21263. dashedLines.dashSize = dashSize;
  21264. dashedLines.gapSize = gapSize;
  21265. return dashedLines;
  21266. };
  21267. /**
  21268. * Creates an extruded shape mesh.
  21269. * 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.
  21270. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  21271. *
  21272. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21273. * 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
  21274. * extruded along the Z axis.
  21275. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21276. * 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.
  21277. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21278. * 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
  21279. * 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
  21280. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21281. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21282. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21283. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21284. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21285. */
  21286. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  21287. var path = options.path;
  21288. var shape = options.shape;
  21289. var scale = options.scale || 1;
  21290. var rotation = options.rotation || 0;
  21291. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  21292. var updatable = options.updatable;
  21293. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21294. var instance = options.instance;
  21295. var invertUV = options.invertUV || false;
  21296. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  21297. };
  21298. /**
  21299. * Creates an custom extruded shape mesh.
  21300. * 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.
  21301. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  21302. *
  21303. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21304. * 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
  21305. * extruded along the Z axis.
  21306. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21307. * 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
  21308. * and the distance of this point from the begining of the path :
  21309. * ```javascript
  21310. * var rotationFunction = function(i, distance) {
  21311. * // do things
  21312. * return rotationValue; }
  21313. * ```
  21314. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21315. * 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
  21316. * and the distance of this point from the begining of the path :
  21317. * ```javascript
  21318. * var scaleFunction = function(i, distance) {
  21319. * // do things
  21320. * return scaleValue;}
  21321. * ```
  21322. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21323. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21324. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21325. * 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
  21326. * 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
  21327. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21328. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21329. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21330. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21331. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21332. */
  21333. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  21334. var path = options.path;
  21335. var shape = options.shape;
  21336. var scaleFunction = options.scaleFunction || (function () { return 1; });
  21337. var rotationFunction = options.rotationFunction || (function () { return 0; });
  21338. var ribbonCloseArray = options.ribbonCloseArray || false;
  21339. var ribbonClosePath = options.ribbonClosePath || false;
  21340. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  21341. var updatable = options.updatable;
  21342. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21343. var instance = options.instance;
  21344. var invertUV = options.invertUV || false;
  21345. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  21346. };
  21347. /**
  21348. * Creates lathe mesh.
  21349. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21350. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  21351. *
  21352. * 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
  21353. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21354. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21355. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21356. * 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.
  21357. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  21358. * 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
  21359. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21360. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21361. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21362. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21363. */
  21364. MeshBuilder.CreateLathe = function (name, options, scene) {
  21365. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  21366. var closed = (options.closed === undefined) ? true : options.closed;
  21367. var shape = options.shape;
  21368. var radius = options.radius || 1;
  21369. var tessellation = options.tessellation || 64;
  21370. var updatable = options.updatable;
  21371. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21372. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  21373. var pi2 = Math.PI * 2;
  21374. var paths = new Array();
  21375. var invertUV = options.invertUV || false;
  21376. var i = 0;
  21377. var p = 0;
  21378. var step = pi2 / tessellation * arc;
  21379. var rotated;
  21380. var path = new Array();
  21381. ;
  21382. for (i = 0; i <= tessellation; i++) {
  21383. var path = [];
  21384. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  21385. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  21386. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  21387. }
  21388. for (p = 0; p < shape.length; p++) {
  21389. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  21390. path.push(rotated);
  21391. }
  21392. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  21393. 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));
  21394. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  21395. }
  21396. paths.push(path);
  21397. }
  21398. // lathe ribbon
  21399. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  21400. return lathe;
  21401. };
  21402. /**
  21403. * Creates a plane mesh.
  21404. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  21405. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21406. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  21407. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  21408. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21409. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21410. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21411. */
  21412. MeshBuilder.CreatePlane = function (name, options, scene) {
  21413. var plane = new BABYLON.Mesh(name, scene);
  21414. var vertexData = BABYLON.VertexData.CreatePlane(options);
  21415. vertexData.applyToMesh(plane, options.updatable);
  21416. if (options.sourcePlane) {
  21417. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  21418. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  21419. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  21420. plane.rotate(vectorProduct, product);
  21421. }
  21422. return plane;
  21423. };
  21424. /**
  21425. * Creates a ground mesh.
  21426. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  21427. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21428. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21429. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21430. */
  21431. MeshBuilder.CreateGround = function (name, options, scene) {
  21432. var ground = new BABYLON.GroundMesh(name, scene);
  21433. ground._setReady(false);
  21434. ground._subdivisions = options.subdivisions || 1;
  21435. ground._width = options.width || 1;
  21436. ground._height = options.height || 1;
  21437. ground._maxX = ground._width / 2;
  21438. ground._maxZ = ground._height / 2;
  21439. ground._minX = -ground._maxX;
  21440. ground._minZ = -ground._maxZ;
  21441. var vertexData = BABYLON.VertexData.CreateGround(options);
  21442. vertexData.applyToMesh(ground, options.updatable);
  21443. ground._setReady(true);
  21444. return ground;
  21445. };
  21446. /**
  21447. * Creates a tiled ground mesh.
  21448. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  21449. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21450. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21451. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21452. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21453. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21454. * numbers of subdivisions on the ground width and height of each tile.
  21455. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21456. */
  21457. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  21458. var tiledGround = new BABYLON.Mesh(name, scene);
  21459. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  21460. vertexData.applyToMesh(tiledGround, options.updatable);
  21461. return tiledGround;
  21462. };
  21463. /**
  21464. * Creates a ground mesh from a height map.
  21465. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21466. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  21467. * The parameter `url` sets the URL of the height map image resource.
  21468. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21469. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21470. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21471. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21472. * 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).
  21473. * This function is passed the newly built mesh :
  21474. * ```javascript
  21475. * function(mesh) { // do things
  21476. * return; }
  21477. * ```
  21478. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21479. */
  21480. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  21481. var width = options.width || 10.0;
  21482. var height = options.height || 10.0;
  21483. var subdivisions = options.subdivisions || 1 | 0;
  21484. var minHeight = options.minHeight || 0.0;
  21485. var maxHeight = options.maxHeight || 10.0;
  21486. var updatable = options.updatable;
  21487. var onReady = options.onReady;
  21488. var ground = new BABYLON.GroundMesh(name, scene);
  21489. ground._subdivisions = subdivisions;
  21490. ground._width = width;
  21491. ground._height = height;
  21492. ground._maxX = ground._width / 2.0;
  21493. ground._maxZ = ground._height / 2.0;
  21494. ground._minX = -ground._maxX;
  21495. ground._minZ = -ground._maxZ;
  21496. ground._setReady(false);
  21497. var onload = function (img) {
  21498. // Getting height map data
  21499. var canvas = document.createElement("canvas");
  21500. var context = canvas.getContext("2d");
  21501. var bufferWidth = img.width;
  21502. var bufferHeight = img.height;
  21503. canvas.width = bufferWidth;
  21504. canvas.height = bufferHeight;
  21505. context.drawImage(img, 0, 0);
  21506. // Create VertexData from map data
  21507. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  21508. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  21509. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  21510. width: width, height: height,
  21511. subdivisions: subdivisions,
  21512. minHeight: minHeight, maxHeight: maxHeight,
  21513. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  21514. });
  21515. vertexData.applyToMesh(ground, updatable);
  21516. ground._setReady(true);
  21517. //execute ready callback, if set
  21518. if (onReady) {
  21519. onReady(ground);
  21520. }
  21521. };
  21522. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  21523. return ground;
  21524. };
  21525. /**
  21526. * Creates a tube mesh.
  21527. * 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.
  21528. *
  21529. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  21530. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21531. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21532. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21533. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21534. * 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.
  21535. * It must return a radius value (positive float) :
  21536. * ```javascript
  21537. * var radiusFunction = function(i, distance) {
  21538. * // do things
  21539. * return radius; }
  21540. * ```
  21541. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  21542. * 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
  21543. * 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
  21544. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21545. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21546. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21547. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21548. */
  21549. MeshBuilder.CreateTube = function (name, options, scene) {
  21550. var path = options.path;
  21551. var radius = options.radius || 1.0;
  21552. var tessellation = options.tessellation || 64 | 0;
  21553. var radiusFunction = options.radiusFunction;
  21554. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  21555. var invertUV = options.invertUV || false;
  21556. var updatable = options.updatable;
  21557. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21558. var instance = options.instance;
  21559. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  21560. // tube geometry
  21561. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  21562. var tangents = path3D.getTangents();
  21563. var normals = path3D.getNormals();
  21564. var distances = path3D.getDistances();
  21565. var pi2 = Math.PI * 2;
  21566. var step = pi2 / tessellation * arc;
  21567. var returnRadius = function () { return radius; };
  21568. var radiusFunctionFinal = radiusFunction || returnRadius;
  21569. var circlePath;
  21570. var rad;
  21571. var normal;
  21572. var rotated;
  21573. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  21574. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  21575. for (var i = 0; i < path.length; i++) {
  21576. rad = radiusFunctionFinal(i, distances[i]); // current radius
  21577. circlePath = Array(); // current circle array
  21578. normal = normals[i]; // current normal
  21579. for (var t = 0; t < tessellation; t++) {
  21580. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  21581. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  21582. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  21583. rotated.scaleInPlace(rad).addInPlace(path[i]);
  21584. circlePath[t] = rotated;
  21585. }
  21586. circlePaths[index] = circlePath;
  21587. index++;
  21588. }
  21589. // cap
  21590. var capPath = function (nbPoints, pathIndex) {
  21591. var pointCap = Array();
  21592. for (var i = 0; i < nbPoints; i++) {
  21593. pointCap.push(path[pathIndex]);
  21594. }
  21595. return pointCap;
  21596. };
  21597. switch (cap) {
  21598. case BABYLON.Mesh.NO_CAP:
  21599. break;
  21600. case BABYLON.Mesh.CAP_START:
  21601. circlePaths[0] = capPath(tessellation, 0);
  21602. circlePaths[1] = circlePaths[2].slice(0);
  21603. break;
  21604. case BABYLON.Mesh.CAP_END:
  21605. circlePaths[index] = circlePaths[index - 1].slice(0);
  21606. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  21607. break;
  21608. case BABYLON.Mesh.CAP_ALL:
  21609. circlePaths[0] = capPath(tessellation, 0);
  21610. circlePaths[1] = circlePaths[2].slice(0);
  21611. circlePaths[index] = circlePaths[index - 1].slice(0);
  21612. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  21613. break;
  21614. default:
  21615. break;
  21616. }
  21617. return circlePaths;
  21618. };
  21619. var path3D;
  21620. var pathArray;
  21621. if (instance) {
  21622. var arc = options.arc || instance.arc;
  21623. path3D = (instance.path3D).update(path);
  21624. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  21625. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  21626. instance.path3D = path3D;
  21627. instance.pathArray = pathArray;
  21628. instance.arc = arc;
  21629. return instance;
  21630. }
  21631. // tube creation
  21632. path3D = new BABYLON.Path3D(path);
  21633. var newPathArray = new Array();
  21634. cap = (cap < 0 || cap > 3) ? 0 : cap;
  21635. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  21636. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  21637. tube.pathArray = pathArray;
  21638. tube.path3D = path3D;
  21639. tube.tessellation = tessellation;
  21640. tube.cap = cap;
  21641. tube.arc = options.arc;
  21642. return tube;
  21643. };
  21644. /**
  21645. * Creates a polyhedron mesh.
  21646. *
  21647. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  21648. * 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
  21649. * to choose the wanted type.
  21650. * The parameter `size` (positive float, default 1) sets the polygon size.
  21651. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21652. * 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`.
  21653. * 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
  21654. * 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)`).
  21655. * 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
  21656. * 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.
  21657. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21658. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21659. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21660. */
  21661. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  21662. var polyhedron = new BABYLON.Mesh(name, scene);
  21663. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  21664. vertexData.applyToMesh(polyhedron, options.updatable);
  21665. return polyhedron;
  21666. };
  21667. /**
  21668. * Creates a decal mesh.
  21669. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  21670. * 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.
  21671. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21672. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21673. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21674. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21675. */
  21676. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  21677. var indices = sourceMesh.getIndices();
  21678. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21679. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21680. var position = options.position || BABYLON.Vector3.Zero();
  21681. var normal = options.normal || BABYLON.Vector3.Up();
  21682. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  21683. var angle = options.angle || 0;
  21684. // Getting correct rotation
  21685. if (!normal) {
  21686. var target = new BABYLON.Vector3(0, 0, 1);
  21687. var camera = sourceMesh.getScene().activeCamera;
  21688. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  21689. normal = camera.globalPosition.subtract(cameraWorldTarget);
  21690. }
  21691. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  21692. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  21693. var pitch = Math.atan2(normal.y, len);
  21694. // Matrix
  21695. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  21696. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  21697. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  21698. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  21699. var vertexData = new BABYLON.VertexData();
  21700. vertexData.indices = [];
  21701. vertexData.positions = [];
  21702. vertexData.normals = [];
  21703. vertexData.uvs = [];
  21704. var currentVertexDataIndex = 0;
  21705. var extractDecalVector3 = function (indexId) {
  21706. var vertexId = indices[indexId];
  21707. var result = new BABYLON.PositionNormalVertex();
  21708. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  21709. // Send vector to decal local world
  21710. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  21711. // Get normal
  21712. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  21713. return result;
  21714. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  21715. var clip = function (vertices, axis) {
  21716. if (vertices.length === 0) {
  21717. return vertices;
  21718. }
  21719. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  21720. var clipVertices = function (v0, v1) {
  21721. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  21722. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  21723. };
  21724. var result = new Array();
  21725. for (var index = 0; index < vertices.length; index += 3) {
  21726. var v1Out;
  21727. var v2Out;
  21728. var v3Out;
  21729. var total = 0;
  21730. var nV1, nV2, nV3, nV4;
  21731. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  21732. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  21733. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  21734. v1Out = d1 > 0;
  21735. v2Out = d2 > 0;
  21736. v3Out = d3 > 0;
  21737. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  21738. switch (total) {
  21739. case 0:
  21740. result.push(vertices[index]);
  21741. result.push(vertices[index + 1]);
  21742. result.push(vertices[index + 2]);
  21743. break;
  21744. case 1:
  21745. if (v1Out) {
  21746. nV1 = vertices[index + 1];
  21747. nV2 = vertices[index + 2];
  21748. nV3 = clipVertices(vertices[index], nV1);
  21749. nV4 = clipVertices(vertices[index], nV2);
  21750. }
  21751. if (v2Out) {
  21752. nV1 = vertices[index];
  21753. nV2 = vertices[index + 2];
  21754. nV3 = clipVertices(vertices[index + 1], nV1);
  21755. nV4 = clipVertices(vertices[index + 1], nV2);
  21756. result.push(nV3);
  21757. result.push(nV2.clone());
  21758. result.push(nV1.clone());
  21759. result.push(nV2.clone());
  21760. result.push(nV3.clone());
  21761. result.push(nV4);
  21762. break;
  21763. }
  21764. if (v3Out) {
  21765. nV1 = vertices[index];
  21766. nV2 = vertices[index + 1];
  21767. nV3 = clipVertices(vertices[index + 2], nV1);
  21768. nV4 = clipVertices(vertices[index + 2], nV2);
  21769. }
  21770. result.push(nV1.clone());
  21771. result.push(nV2.clone());
  21772. result.push(nV3);
  21773. result.push(nV4);
  21774. result.push(nV3.clone());
  21775. result.push(nV2.clone());
  21776. break;
  21777. case 2:
  21778. if (!v1Out) {
  21779. nV1 = vertices[index].clone();
  21780. nV2 = clipVertices(nV1, vertices[index + 1]);
  21781. nV3 = clipVertices(nV1, vertices[index + 2]);
  21782. result.push(nV1);
  21783. result.push(nV2);
  21784. result.push(nV3);
  21785. }
  21786. if (!v2Out) {
  21787. nV1 = vertices[index + 1].clone();
  21788. nV2 = clipVertices(nV1, vertices[index + 2]);
  21789. nV3 = clipVertices(nV1, vertices[index]);
  21790. result.push(nV1);
  21791. result.push(nV2);
  21792. result.push(nV3);
  21793. }
  21794. if (!v3Out) {
  21795. nV1 = vertices[index + 2].clone();
  21796. nV2 = clipVertices(nV1, vertices[index]);
  21797. nV3 = clipVertices(nV1, vertices[index + 1]);
  21798. result.push(nV1);
  21799. result.push(nV2);
  21800. result.push(nV3);
  21801. }
  21802. break;
  21803. case 3:
  21804. break;
  21805. }
  21806. }
  21807. return result;
  21808. };
  21809. for (var index = 0; index < indices.length; index += 3) {
  21810. var faceVertices = new Array();
  21811. faceVertices.push(extractDecalVector3(index));
  21812. faceVertices.push(extractDecalVector3(index + 1));
  21813. faceVertices.push(extractDecalVector3(index + 2));
  21814. // Clip
  21815. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  21816. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  21817. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  21818. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  21819. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  21820. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  21821. if (faceVertices.length === 0) {
  21822. continue;
  21823. }
  21824. // Add UVs and get back to world
  21825. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  21826. var vertex = faceVertices[vIndex];
  21827. //TODO check for Int32Array
  21828. vertexData.indices.push(currentVertexDataIndex);
  21829. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  21830. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  21831. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  21832. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  21833. currentVertexDataIndex++;
  21834. }
  21835. }
  21836. // Return mesh
  21837. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  21838. vertexData.applyToMesh(decal);
  21839. decal.position = position.clone();
  21840. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  21841. return decal;
  21842. };
  21843. // Privates
  21844. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  21845. // extrusion geometry
  21846. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  21847. var tangents = path3D.getTangents();
  21848. var normals = path3D.getNormals();
  21849. var binormals = path3D.getBinormals();
  21850. var distances = path3D.getDistances();
  21851. var angle = 0;
  21852. var returnScale = function () { return scale; };
  21853. var returnRotation = function () { return rotation; };
  21854. var rotate = custom ? rotateFunction : returnRotation;
  21855. var scl = custom ? scaleFunction : returnScale;
  21856. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  21857. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  21858. for (var i = 0; i < curve.length; i++) {
  21859. var shapePath = new Array();
  21860. var angleStep = rotate(i, distances[i]);
  21861. var scaleRatio = scl(i, distances[i]);
  21862. for (var p = 0; p < shape.length; p++) {
  21863. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  21864. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  21865. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  21866. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  21867. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  21868. shapePath[p] = rotated;
  21869. }
  21870. shapePaths[index] = shapePath;
  21871. angle += angleStep;
  21872. index++;
  21873. }
  21874. // cap
  21875. var capPath = function (shapePath) {
  21876. var pointCap = Array();
  21877. var barycenter = BABYLON.Vector3.Zero();
  21878. var i;
  21879. for (i = 0; i < shapePath.length; i++) {
  21880. barycenter.addInPlace(shapePath[i]);
  21881. }
  21882. barycenter.scaleInPlace(1 / shapePath.length);
  21883. for (i = 0; i < shapePath.length; i++) {
  21884. pointCap.push(barycenter);
  21885. }
  21886. return pointCap;
  21887. };
  21888. switch (cap) {
  21889. case BABYLON.Mesh.NO_CAP:
  21890. break;
  21891. case BABYLON.Mesh.CAP_START:
  21892. shapePaths[0] = capPath(shapePaths[2]);
  21893. shapePaths[1] = shapePaths[2].slice(0);
  21894. break;
  21895. case BABYLON.Mesh.CAP_END:
  21896. shapePaths[index] = shapePaths[index - 1];
  21897. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  21898. break;
  21899. case BABYLON.Mesh.CAP_ALL:
  21900. shapePaths[0] = capPath(shapePaths[2]);
  21901. shapePaths[1] = shapePaths[2].slice(0);
  21902. shapePaths[index] = shapePaths[index - 1];
  21903. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  21904. break;
  21905. default:
  21906. break;
  21907. }
  21908. return shapePaths;
  21909. };
  21910. var path3D;
  21911. var pathArray;
  21912. if (instance) {
  21913. path3D = (instance.path3D).update(curve);
  21914. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  21915. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  21916. return instance;
  21917. }
  21918. // extruded shape creation
  21919. path3D = new BABYLON.Path3D(curve);
  21920. var newShapePaths = new Array();
  21921. cap = (cap < 0 || cap > 3) ? 0 : cap;
  21922. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  21923. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  21924. extrudedGeneric.pathArray = pathArray;
  21925. extrudedGeneric.path3D = path3D;
  21926. extrudedGeneric.cap = cap;
  21927. return extrudedGeneric;
  21928. };
  21929. return MeshBuilder;
  21930. })();
  21931. BABYLON.MeshBuilder = MeshBuilder;
  21932. })(BABYLON || (BABYLON = {}));
  21933. var BABYLON;
  21934. (function (BABYLON) {
  21935. var BaseTexture = (function () {
  21936. function BaseTexture(scene) {
  21937. this.hasAlpha = false;
  21938. this.getAlphaFromRGB = false;
  21939. this.level = 1;
  21940. this.coordinatesIndex = 0;
  21941. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  21942. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21943. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21944. this.anisotropicFilteringLevel = 4;
  21945. this.isCube = false;
  21946. this.isRenderTarget = false;
  21947. this.animations = new Array();
  21948. /**
  21949. * An event triggered when the texture is disposed.
  21950. * @type {BABYLON.Observable}
  21951. */
  21952. this.onDisposeObservable = new BABYLON.Observable();
  21953. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21954. this._scene = scene;
  21955. this._scene.textures.push(this);
  21956. }
  21957. BaseTexture.prototype.toString = function () {
  21958. return this.name;
  21959. };
  21960. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  21961. set: function (callback) {
  21962. if (this._onDisposeObserver) {
  21963. this.onDisposeObservable.remove(this._onDisposeObserver);
  21964. }
  21965. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21966. },
  21967. enumerable: true,
  21968. configurable: true
  21969. });
  21970. BaseTexture.prototype.getScene = function () {
  21971. return this._scene;
  21972. };
  21973. BaseTexture.prototype.getTextureMatrix = function () {
  21974. return null;
  21975. };
  21976. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  21977. return null;
  21978. };
  21979. BaseTexture.prototype.getInternalTexture = function () {
  21980. return this._texture;
  21981. };
  21982. BaseTexture.prototype.isReady = function () {
  21983. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21984. return true;
  21985. }
  21986. if (this._texture) {
  21987. return this._texture.isReady;
  21988. }
  21989. return false;
  21990. };
  21991. BaseTexture.prototype.getSize = function () {
  21992. if (this._texture._width) {
  21993. return new BABYLON.Size(this._texture._width, this._texture._height);
  21994. }
  21995. if (this._texture._size) {
  21996. return new BABYLON.Size(this._texture._size, this._texture._size);
  21997. }
  21998. return BABYLON.Size.Zero();
  21999. };
  22000. BaseTexture.prototype.getBaseSize = function () {
  22001. if (!this.isReady() || !this._texture)
  22002. return BABYLON.Size.Zero();
  22003. if (this._texture._size) {
  22004. return new BABYLON.Size(this._texture._size, this._texture._size);
  22005. }
  22006. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  22007. };
  22008. BaseTexture.prototype.scale = function (ratio) {
  22009. };
  22010. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22011. get: function () {
  22012. return false;
  22013. },
  22014. enumerable: true,
  22015. configurable: true
  22016. });
  22017. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  22018. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22019. for (var index = 0; index < texturesCache.length; index++) {
  22020. var texturesCacheEntry = texturesCache[index];
  22021. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22022. texturesCache.splice(index, 1);
  22023. return;
  22024. }
  22025. }
  22026. };
  22027. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22028. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22029. for (var index = 0; index < texturesCache.length; index++) {
  22030. var texturesCacheEntry = texturesCache[index];
  22031. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22032. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22033. texturesCacheEntry.references++;
  22034. return texturesCacheEntry;
  22035. }
  22036. }
  22037. }
  22038. return null;
  22039. };
  22040. BaseTexture.prototype.delayLoad = function () {
  22041. };
  22042. BaseTexture.prototype.clone = function () {
  22043. return null;
  22044. };
  22045. BaseTexture.prototype.releaseInternalTexture = function () {
  22046. if (this._texture) {
  22047. this._scene.getEngine().releaseInternalTexture(this._texture);
  22048. delete this._texture;
  22049. }
  22050. };
  22051. BaseTexture.prototype.dispose = function () {
  22052. // Animations
  22053. this.getScene().stopAnimation(this);
  22054. // Remove from scene
  22055. var index = this._scene.textures.indexOf(this);
  22056. if (index >= 0) {
  22057. this._scene.textures.splice(index, 1);
  22058. }
  22059. if (this._texture === undefined) {
  22060. return;
  22061. }
  22062. // Release
  22063. this.releaseInternalTexture();
  22064. // Callback
  22065. this.onDisposeObservable.notifyObservers(this);
  22066. this.onDisposeObservable.clear();
  22067. };
  22068. BaseTexture.prototype.serialize = function () {
  22069. if (!this.name) {
  22070. return null;
  22071. }
  22072. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22073. // Animations
  22074. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22075. return serializationObject;
  22076. };
  22077. __decorate([
  22078. BABYLON.serialize()
  22079. ], BaseTexture.prototype, "name", void 0);
  22080. __decorate([
  22081. BABYLON.serialize()
  22082. ], BaseTexture.prototype, "hasAlpha", void 0);
  22083. __decorate([
  22084. BABYLON.serialize()
  22085. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  22086. __decorate([
  22087. BABYLON.serialize()
  22088. ], BaseTexture.prototype, "level", void 0);
  22089. __decorate([
  22090. BABYLON.serialize()
  22091. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  22092. __decorate([
  22093. BABYLON.serialize()
  22094. ], BaseTexture.prototype, "coordinatesMode", void 0);
  22095. __decorate([
  22096. BABYLON.serialize()
  22097. ], BaseTexture.prototype, "wrapU", void 0);
  22098. __decorate([
  22099. BABYLON.serialize()
  22100. ], BaseTexture.prototype, "wrapV", void 0);
  22101. __decorate([
  22102. BABYLON.serialize()
  22103. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  22104. __decorate([
  22105. BABYLON.serialize()
  22106. ], BaseTexture.prototype, "isCube", void 0);
  22107. __decorate([
  22108. BABYLON.serialize()
  22109. ], BaseTexture.prototype, "isRenderTarget", void 0);
  22110. return BaseTexture;
  22111. })();
  22112. BABYLON.BaseTexture = BaseTexture;
  22113. })(BABYLON || (BABYLON = {}));
  22114. var BABYLON;
  22115. (function (BABYLON) {
  22116. var Texture = (function (_super) {
  22117. __extends(Texture, _super);
  22118. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  22119. var _this = this;
  22120. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22121. if (onLoad === void 0) { onLoad = null; }
  22122. if (onError === void 0) { onError = null; }
  22123. if (buffer === void 0) { buffer = null; }
  22124. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22125. _super.call(this, scene);
  22126. this.uOffset = 0;
  22127. this.vOffset = 0;
  22128. this.uScale = 1.0;
  22129. this.vScale = 1.0;
  22130. this.uAng = 0;
  22131. this.vAng = 0;
  22132. this.wAng = 0;
  22133. this.name = url;
  22134. this.url = url;
  22135. this._noMipmap = noMipmap;
  22136. this._invertY = invertY;
  22137. this._samplingMode = samplingMode;
  22138. this._buffer = buffer;
  22139. this._deleteBuffer = deleteBuffer;
  22140. if (!url) {
  22141. return;
  22142. }
  22143. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  22144. var load = function () {
  22145. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  22146. _this.onLoadObservable.notifyObservers(true);
  22147. }
  22148. if (onLoad) {
  22149. onLoad();
  22150. }
  22151. };
  22152. if (!this._texture) {
  22153. if (!scene.useDelayedTextureLoading) {
  22154. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, load, onError, this._buffer);
  22155. if (deleteBuffer) {
  22156. delete this._buffer;
  22157. }
  22158. }
  22159. else {
  22160. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22161. this._delayedOnLoad = load;
  22162. this._delayedOnError = onError;
  22163. }
  22164. }
  22165. else {
  22166. BABYLON.Tools.SetImmediate(function () { return load(); });
  22167. }
  22168. }
  22169. Object.defineProperty(Texture.prototype, "noMipmap", {
  22170. get: function () {
  22171. return this._noMipmap;
  22172. },
  22173. enumerable: true,
  22174. configurable: true
  22175. });
  22176. Texture.prototype.delayLoad = function () {
  22177. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22178. return;
  22179. }
  22180. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22181. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22182. if (!this._texture) {
  22183. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  22184. if (this._deleteBuffer) {
  22185. delete this._buffer;
  22186. }
  22187. }
  22188. };
  22189. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22190. if (!this._texture) {
  22191. return;
  22192. }
  22193. this._samplingMode = samplingMode;
  22194. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22195. };
  22196. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22197. x *= this.uScale;
  22198. y *= this.vScale;
  22199. x -= 0.5 * this.uScale;
  22200. y -= 0.5 * this.vScale;
  22201. z -= 0.5;
  22202. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22203. t.x += 0.5 * this.uScale + this.uOffset;
  22204. t.y += 0.5 * this.vScale + this.vOffset;
  22205. t.z += 0.5;
  22206. };
  22207. Texture.prototype.getTextureMatrix = function () {
  22208. if (this.uOffset === this._cachedUOffset &&
  22209. this.vOffset === this._cachedVOffset &&
  22210. this.uScale === this._cachedUScale &&
  22211. this.vScale === this._cachedVScale &&
  22212. this.uAng === this._cachedUAng &&
  22213. this.vAng === this._cachedVAng &&
  22214. this.wAng === this._cachedWAng) {
  22215. return this._cachedTextureMatrix;
  22216. }
  22217. this._cachedUOffset = this.uOffset;
  22218. this._cachedVOffset = this.vOffset;
  22219. this._cachedUScale = this.uScale;
  22220. this._cachedVScale = this.vScale;
  22221. this._cachedUAng = this.uAng;
  22222. this._cachedVAng = this.vAng;
  22223. this._cachedWAng = this.wAng;
  22224. if (!this._cachedTextureMatrix) {
  22225. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22226. this._rowGenerationMatrix = new BABYLON.Matrix();
  22227. this._t0 = BABYLON.Vector3.Zero();
  22228. this._t1 = BABYLON.Vector3.Zero();
  22229. this._t2 = BABYLON.Vector3.Zero();
  22230. }
  22231. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22232. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22233. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22234. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22235. this._t1.subtractInPlace(this._t0);
  22236. this._t2.subtractInPlace(this._t0);
  22237. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22238. this._cachedTextureMatrix.m[0] = this._t1.x;
  22239. this._cachedTextureMatrix.m[1] = this._t1.y;
  22240. this._cachedTextureMatrix.m[2] = this._t1.z;
  22241. this._cachedTextureMatrix.m[4] = this._t2.x;
  22242. this._cachedTextureMatrix.m[5] = this._t2.y;
  22243. this._cachedTextureMatrix.m[6] = this._t2.z;
  22244. this._cachedTextureMatrix.m[8] = this._t0.x;
  22245. this._cachedTextureMatrix.m[9] = this._t0.y;
  22246. this._cachedTextureMatrix.m[10] = this._t0.z;
  22247. return this._cachedTextureMatrix;
  22248. };
  22249. Texture.prototype.getReflectionTextureMatrix = function () {
  22250. if (this.uOffset === this._cachedUOffset &&
  22251. this.vOffset === this._cachedVOffset &&
  22252. this.uScale === this._cachedUScale &&
  22253. this.vScale === this._cachedVScale &&
  22254. this.coordinatesMode === this._cachedCoordinatesMode) {
  22255. return this._cachedTextureMatrix;
  22256. }
  22257. if (!this._cachedTextureMatrix) {
  22258. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22259. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22260. }
  22261. this._cachedCoordinatesMode = this.coordinatesMode;
  22262. switch (this.coordinatesMode) {
  22263. case Texture.PLANAR_MODE:
  22264. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22265. this._cachedTextureMatrix[0] = this.uScale;
  22266. this._cachedTextureMatrix[5] = this.vScale;
  22267. this._cachedTextureMatrix[12] = this.uOffset;
  22268. this._cachedTextureMatrix[13] = this.vOffset;
  22269. break;
  22270. case Texture.PROJECTION_MODE:
  22271. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22272. this._projectionModeMatrix.m[0] = 0.5;
  22273. this._projectionModeMatrix.m[5] = -0.5;
  22274. this._projectionModeMatrix.m[10] = 0.0;
  22275. this._projectionModeMatrix.m[12] = 0.5;
  22276. this._projectionModeMatrix.m[13] = 0.5;
  22277. this._projectionModeMatrix.m[14] = 1.0;
  22278. this._projectionModeMatrix.m[15] = 1.0;
  22279. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22280. break;
  22281. default:
  22282. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22283. break;
  22284. }
  22285. return this._cachedTextureMatrix;
  22286. };
  22287. Texture.prototype.clone = function () {
  22288. var _this = this;
  22289. return BABYLON.SerializationHelper.Clone(function () {
  22290. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22291. }, this);
  22292. };
  22293. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22294. get: function () {
  22295. if (!this._onLoadObservarble) {
  22296. this._onLoadObservarble = new BABYLON.Observable();
  22297. }
  22298. return this._onLoadObservarble;
  22299. },
  22300. enumerable: true,
  22301. configurable: true
  22302. });
  22303. // Statics
  22304. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  22305. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22306. if (onLoad === void 0) { onLoad = null; }
  22307. if (onError === void 0) { onError = null; }
  22308. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  22309. };
  22310. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22311. if (parsedTexture.isCube) {
  22312. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22313. }
  22314. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22315. return null;
  22316. }
  22317. var texture = BABYLON.SerializationHelper.Parse(function () {
  22318. if (parsedTexture.customType) {
  22319. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22320. return customTexture.Parse(parsedTexture, scene, rootUrl);
  22321. }
  22322. else if (parsedTexture.mirrorPlane) {
  22323. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22324. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22325. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22326. return mirrorTexture;
  22327. }
  22328. else if (parsedTexture.isRenderTarget) {
  22329. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22330. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22331. return renderTargetTexture;
  22332. }
  22333. else {
  22334. var texture;
  22335. if (parsedTexture.base64String) {
  22336. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  22337. }
  22338. else {
  22339. texture = new Texture(rootUrl + parsedTexture.name, scene);
  22340. }
  22341. return texture;
  22342. }
  22343. }, parsedTexture, scene);
  22344. // Animations
  22345. if (parsedTexture.animations) {
  22346. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22347. var parsedAnimation = parsedTexture.animations[animationIndex];
  22348. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22349. }
  22350. }
  22351. return texture;
  22352. };
  22353. // Constants
  22354. Texture.NEAREST_SAMPLINGMODE = 1;
  22355. Texture.BILINEAR_SAMPLINGMODE = 2;
  22356. Texture.TRILINEAR_SAMPLINGMODE = 3;
  22357. Texture.EXPLICIT_MODE = 0;
  22358. Texture.SPHERICAL_MODE = 1;
  22359. Texture.PLANAR_MODE = 2;
  22360. Texture.CUBIC_MODE = 3;
  22361. Texture.PROJECTION_MODE = 4;
  22362. Texture.SKYBOX_MODE = 5;
  22363. Texture.INVCUBIC_MODE = 6;
  22364. Texture.EQUIRECTANGULAR_MODE = 7;
  22365. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22366. Texture.CLAMP_ADDRESSMODE = 0;
  22367. Texture.WRAP_ADDRESSMODE = 1;
  22368. Texture.MIRROR_ADDRESSMODE = 2;
  22369. __decorate([
  22370. BABYLON.serialize()
  22371. ], Texture.prototype, "url", void 0);
  22372. __decorate([
  22373. BABYLON.serialize()
  22374. ], Texture.prototype, "uOffset", void 0);
  22375. __decorate([
  22376. BABYLON.serialize()
  22377. ], Texture.prototype, "vOffset", void 0);
  22378. __decorate([
  22379. BABYLON.serialize()
  22380. ], Texture.prototype, "uScale", void 0);
  22381. __decorate([
  22382. BABYLON.serialize()
  22383. ], Texture.prototype, "vScale", void 0);
  22384. __decorate([
  22385. BABYLON.serialize()
  22386. ], Texture.prototype, "uAng", void 0);
  22387. __decorate([
  22388. BABYLON.serialize()
  22389. ], Texture.prototype, "vAng", void 0);
  22390. __decorate([
  22391. BABYLON.serialize()
  22392. ], Texture.prototype, "wAng", void 0);
  22393. return Texture;
  22394. })(BABYLON.BaseTexture);
  22395. BABYLON.Texture = Texture;
  22396. })(BABYLON || (BABYLON = {}));
  22397. var BABYLON;
  22398. (function (BABYLON) {
  22399. var CubeTexture = (function (_super) {
  22400. __extends(CubeTexture, _super);
  22401. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  22402. _super.call(this, scene);
  22403. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  22404. this.name = rootUrl;
  22405. this.url = rootUrl;
  22406. this._noMipmap = noMipmap;
  22407. this.hasAlpha = false;
  22408. if (!rootUrl && !files) {
  22409. return;
  22410. }
  22411. this._texture = this._getFromCache(rootUrl, noMipmap);
  22412. if (!files) {
  22413. if (!extensions) {
  22414. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  22415. }
  22416. files = [];
  22417. for (var index = 0; index < extensions.length; index++) {
  22418. files.push(rootUrl + extensions[index]);
  22419. }
  22420. this._extensions = extensions;
  22421. }
  22422. this._files = files;
  22423. if (!this._texture) {
  22424. if (!scene.useDelayedTextureLoading) {
  22425. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  22426. }
  22427. else {
  22428. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22429. }
  22430. }
  22431. this.isCube = true;
  22432. this._textureMatrix = BABYLON.Matrix.Identity();
  22433. }
  22434. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  22435. return new CubeTexture("", scene, null, noMipmap, files);
  22436. };
  22437. // Methods
  22438. CubeTexture.prototype.delayLoad = function () {
  22439. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22440. return;
  22441. }
  22442. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22443. this._texture = this._getFromCache(this.url, this._noMipmap);
  22444. if (!this._texture) {
  22445. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  22446. }
  22447. };
  22448. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  22449. return this._textureMatrix;
  22450. };
  22451. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  22452. var texture = BABYLON.SerializationHelper.Parse(function () {
  22453. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  22454. }, parsedTexture, scene);
  22455. // Animations
  22456. if (parsedTexture.animations) {
  22457. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22458. var parsedAnimation = parsedTexture.animations[animationIndex];
  22459. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22460. }
  22461. }
  22462. return texture;
  22463. };
  22464. CubeTexture.prototype.clone = function () {
  22465. var _this = this;
  22466. return BABYLON.SerializationHelper.Clone(function () {
  22467. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  22468. }, this);
  22469. };
  22470. return CubeTexture;
  22471. })(BABYLON.BaseTexture);
  22472. BABYLON.CubeTexture = CubeTexture;
  22473. })(BABYLON || (BABYLON = {}));
  22474. var BABYLON;
  22475. (function (BABYLON) {
  22476. var RenderTargetTexture = (function (_super) {
  22477. __extends(RenderTargetTexture, _super);
  22478. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  22479. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  22480. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22481. if (isCube === void 0) { isCube = false; }
  22482. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22483. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  22484. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  22485. _super.call(this, null, scene, !generateMipMaps);
  22486. this.isCube = isCube;
  22487. /**
  22488. * Use this list to define the list of mesh you want to render.
  22489. */
  22490. this.renderList = new Array();
  22491. this.renderParticles = true;
  22492. this.renderSprites = false;
  22493. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  22494. // Events
  22495. /**
  22496. * An event triggered when the texture is unbind.
  22497. * @type {BABYLON.Observable}
  22498. */
  22499. this.onAfterUnbindObservable = new BABYLON.Observable();
  22500. /**
  22501. * An event triggered before rendering the texture
  22502. * @type {BABYLON.Observable}
  22503. */
  22504. this.onBeforeRenderObservable = new BABYLON.Observable();
  22505. /**
  22506. * An event triggered after rendering the texture
  22507. * @type {BABYLON.Observable}
  22508. */
  22509. this.onAfterRenderObservable = new BABYLON.Observable();
  22510. /**
  22511. * An event triggered after the texture clear
  22512. * @type {BABYLON.Observable}
  22513. */
  22514. this.onClearObservable = new BABYLON.Observable();
  22515. this._currentRefreshId = -1;
  22516. this._refreshRate = 1;
  22517. this.name = name;
  22518. this.isRenderTarget = true;
  22519. this._size = size;
  22520. this._generateMipMaps = generateMipMaps;
  22521. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  22522. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  22523. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22524. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22525. }
  22526. if (isCube) {
  22527. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, {
  22528. generateMipMaps: generateMipMaps,
  22529. samplingMode: samplingMode,
  22530. generateDepthBuffer: generateDepthBuffer,
  22531. generateStencilBuffer: generateStencilBuffer
  22532. });
  22533. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  22534. this._textureMatrix = BABYLON.Matrix.Identity();
  22535. }
  22536. else {
  22537. this._texture = scene.getEngine().createRenderTargetTexture(size, {
  22538. generateMipMaps: generateMipMaps,
  22539. type: type,
  22540. samplingMode: samplingMode,
  22541. generateDepthBuffer: generateDepthBuffer,
  22542. generateStencilBuffer: generateStencilBuffer
  22543. });
  22544. }
  22545. // Rendering groups
  22546. this._renderingManager = new BABYLON.RenderingManager(scene);
  22547. }
  22548. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  22549. get: function () {
  22550. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  22551. },
  22552. enumerable: true,
  22553. configurable: true
  22554. });
  22555. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  22556. get: function () {
  22557. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  22558. },
  22559. enumerable: true,
  22560. configurable: true
  22561. });
  22562. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  22563. get: function () {
  22564. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  22565. },
  22566. enumerable: true,
  22567. configurable: true
  22568. });
  22569. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  22570. set: function (callback) {
  22571. if (this._onAfterUnbindObserver) {
  22572. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  22573. }
  22574. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  22575. },
  22576. enumerable: true,
  22577. configurable: true
  22578. });
  22579. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  22580. set: function (callback) {
  22581. if (this._onBeforeRenderObserver) {
  22582. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22583. }
  22584. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22585. },
  22586. enumerable: true,
  22587. configurable: true
  22588. });
  22589. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  22590. set: function (callback) {
  22591. if (this._onAfterRenderObserver) {
  22592. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22593. }
  22594. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22595. },
  22596. enumerable: true,
  22597. configurable: true
  22598. });
  22599. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  22600. set: function (callback) {
  22601. if (this._onClearObserver) {
  22602. this.onClearObservable.remove(this._onClearObserver);
  22603. }
  22604. this._onClearObserver = this.onClearObservable.add(callback);
  22605. },
  22606. enumerable: true,
  22607. configurable: true
  22608. });
  22609. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  22610. this._currentRefreshId = -1;
  22611. };
  22612. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  22613. get: function () {
  22614. return this._refreshRate;
  22615. },
  22616. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  22617. set: function (value) {
  22618. this._refreshRate = value;
  22619. this.resetRefreshCounter();
  22620. },
  22621. enumerable: true,
  22622. configurable: true
  22623. });
  22624. RenderTargetTexture.prototype._shouldRender = function () {
  22625. if (this._currentRefreshId === -1) {
  22626. this._currentRefreshId = 1;
  22627. return true;
  22628. }
  22629. if (this.refreshRate === this._currentRefreshId) {
  22630. this._currentRefreshId = 1;
  22631. return true;
  22632. }
  22633. this._currentRefreshId++;
  22634. return false;
  22635. };
  22636. RenderTargetTexture.prototype.isReady = function () {
  22637. if (!this.getScene().renderTargetsEnabled) {
  22638. return false;
  22639. }
  22640. return _super.prototype.isReady.call(this);
  22641. };
  22642. RenderTargetTexture.prototype.getRenderSize = function () {
  22643. return this._size;
  22644. };
  22645. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  22646. get: function () {
  22647. return true;
  22648. },
  22649. enumerable: true,
  22650. configurable: true
  22651. });
  22652. RenderTargetTexture.prototype.scale = function (ratio) {
  22653. var newSize = this._size * ratio;
  22654. this.resize(newSize, this._generateMipMaps);
  22655. };
  22656. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  22657. if (this.isCube) {
  22658. return this._textureMatrix;
  22659. }
  22660. return _super.prototype.getReflectionTextureMatrix.call(this);
  22661. };
  22662. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  22663. this.releaseInternalTexture();
  22664. if (this.isCube) {
  22665. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  22666. }
  22667. else {
  22668. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  22669. }
  22670. };
  22671. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  22672. var scene = this.getScene();
  22673. if (this.useCameraPostProcesses !== undefined) {
  22674. useCameraPostProcess = this.useCameraPostProcesses;
  22675. }
  22676. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  22677. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  22678. }
  22679. if (this._waitingRenderList) {
  22680. this.renderList = [];
  22681. for (var index = 0; index < this._waitingRenderList.length; index++) {
  22682. var id = this._waitingRenderList[index];
  22683. this.renderList.push(scene.getMeshByID(id));
  22684. }
  22685. delete this._waitingRenderList;
  22686. }
  22687. // Is predicate defined?
  22688. if (this.renderListPredicate) {
  22689. this.renderList.splice(0); // Clear previous renderList
  22690. var sceneMeshes = this.getScene().meshes;
  22691. for (var index = 0; index < sceneMeshes.length; index++) {
  22692. var mesh = sceneMeshes[index];
  22693. if (this.renderListPredicate(mesh)) {
  22694. this.renderList.push(mesh);
  22695. }
  22696. }
  22697. }
  22698. if (this.renderList && this.renderList.length === 0) {
  22699. return;
  22700. }
  22701. // Prepare renderingManager
  22702. this._renderingManager.reset();
  22703. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  22704. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  22705. var sceneRenderId = scene.getRenderId();
  22706. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  22707. var mesh = currentRenderList[meshIndex];
  22708. if (mesh) {
  22709. if (!mesh.isReady()) {
  22710. // Reset _currentRefreshId
  22711. this.resetRefreshCounter();
  22712. continue;
  22713. }
  22714. mesh._preActivateForIntermediateRendering(sceneRenderId);
  22715. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  22716. mesh._activate(sceneRenderId);
  22717. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  22718. var subMesh = mesh.subMeshes[subIndex];
  22719. scene._activeIndices.addCount(subMesh.indexCount, false);
  22720. this._renderingManager.dispatch(subMesh);
  22721. }
  22722. }
  22723. }
  22724. }
  22725. if (this.isCube) {
  22726. for (var face = 0; face < 6; face++) {
  22727. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  22728. scene.incrementRenderId();
  22729. scene.resetCachedMaterial();
  22730. }
  22731. }
  22732. else {
  22733. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  22734. }
  22735. this.onAfterUnbindObservable.notifyObservers(this);
  22736. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  22737. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  22738. }
  22739. scene.resetCachedMaterial();
  22740. };
  22741. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  22742. var scene = this.getScene();
  22743. var engine = scene.getEngine();
  22744. // Bind
  22745. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  22746. if (this.isCube) {
  22747. engine.bindFramebuffer(this._texture, faceIndex);
  22748. }
  22749. else {
  22750. engine.bindFramebuffer(this._texture);
  22751. }
  22752. }
  22753. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  22754. // Clear
  22755. if (this.onClearObservable.hasObservers()) {
  22756. this.onClearObservable.notifyObservers(engine);
  22757. }
  22758. else {
  22759. engine.clear(scene.clearColor, true, true, true);
  22760. }
  22761. if (!this._doNotChangeAspectRatio) {
  22762. scene.updateTransformMatrix(true);
  22763. }
  22764. // Render
  22765. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  22766. if (useCameraPostProcess) {
  22767. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  22768. }
  22769. if (!this._doNotChangeAspectRatio) {
  22770. scene.updateTransformMatrix(true);
  22771. }
  22772. this.onAfterRenderObservable.notifyObservers(faceIndex);
  22773. // Dump ?
  22774. if (dumpForDebug) {
  22775. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  22776. }
  22777. // Unbind
  22778. if (!this.isCube || faceIndex === 5) {
  22779. if (this.isCube) {
  22780. if (faceIndex === 5) {
  22781. engine.generateMipMapsForCubemap(this._texture);
  22782. }
  22783. }
  22784. engine.unBindFramebuffer(this._texture, this.isCube);
  22785. }
  22786. };
  22787. /**
  22788. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22789. * This allowed control for front to back rendering or reversly depending of the special needs.
  22790. *
  22791. * @param renderingGroupId The rendering group id corresponding to its index
  22792. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22793. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22794. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22795. */
  22796. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22797. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22798. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22799. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22800. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  22801. };
  22802. /**
  22803. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22804. *
  22805. * @param renderingGroupId The rendering group id corresponding to its index
  22806. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22807. */
  22808. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  22809. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  22810. };
  22811. RenderTargetTexture.prototype.clone = function () {
  22812. var textureSize = this.getSize();
  22813. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22814. // Base texture
  22815. newTexture.hasAlpha = this.hasAlpha;
  22816. newTexture.level = this.level;
  22817. // RenderTarget Texture
  22818. newTexture.coordinatesMode = this.coordinatesMode;
  22819. newTexture.renderList = this.renderList.slice(0);
  22820. return newTexture;
  22821. };
  22822. RenderTargetTexture.prototype.serialize = function () {
  22823. if (!this.name) {
  22824. return null;
  22825. }
  22826. var serializationObject = _super.prototype.serialize.call(this);
  22827. serializationObject.renderTargetSize = this.getRenderSize();
  22828. serializationObject.renderList = [];
  22829. for (var index = 0; index < this.renderList.length; index++) {
  22830. serializationObject.renderList.push(this.renderList[index].id);
  22831. }
  22832. return serializationObject;
  22833. };
  22834. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  22835. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  22836. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  22837. return RenderTargetTexture;
  22838. })(BABYLON.Texture);
  22839. BABYLON.RenderTargetTexture = RenderTargetTexture;
  22840. })(BABYLON || (BABYLON = {}));
  22841. var BABYLON;
  22842. (function (BABYLON) {
  22843. var ProceduralTexture = (function (_super) {
  22844. __extends(ProceduralTexture, _super);
  22845. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  22846. if (generateMipMaps === void 0) { generateMipMaps = true; }
  22847. if (isCube === void 0) { isCube = false; }
  22848. _super.call(this, null, scene, !generateMipMaps);
  22849. this.isCube = isCube;
  22850. this.isEnabled = true;
  22851. this._currentRefreshId = -1;
  22852. this._refreshRate = 1;
  22853. this._vertexBuffers = {};
  22854. this._uniforms = new Array();
  22855. this._samplers = new Array();
  22856. this._textures = new Array();
  22857. this._floats = new Array();
  22858. this._floatsArrays = {};
  22859. this._colors3 = new Array();
  22860. this._colors4 = new Array();
  22861. this._vectors2 = new Array();
  22862. this._vectors3 = new Array();
  22863. this._matrices = new Array();
  22864. this._fallbackTextureUsed = false;
  22865. scene._proceduralTextures.push(this);
  22866. this.name = name;
  22867. this.isRenderTarget = true;
  22868. this._size = size;
  22869. this._generateMipMaps = generateMipMaps;
  22870. this.setFragment(fragment);
  22871. this._fallbackTexture = fallbackTexture;
  22872. var engine = scene.getEngine();
  22873. if (isCube) {
  22874. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  22875. this.setFloat("face", 0);
  22876. }
  22877. else {
  22878. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  22879. }
  22880. // VBO
  22881. var vertices = [];
  22882. vertices.push(1, 1);
  22883. vertices.push(-1, 1);
  22884. vertices.push(-1, -1);
  22885. vertices.push(1, -1);
  22886. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  22887. // Indices
  22888. var indices = [];
  22889. indices.push(0);
  22890. indices.push(1);
  22891. indices.push(2);
  22892. indices.push(0);
  22893. indices.push(2);
  22894. indices.push(3);
  22895. this._indexBuffer = engine.createIndexBuffer(indices);
  22896. }
  22897. ProceduralTexture.prototype.reset = function () {
  22898. if (this._effect === undefined) {
  22899. return;
  22900. }
  22901. var engine = this.getScene().getEngine();
  22902. engine._releaseEffect(this._effect);
  22903. };
  22904. ProceduralTexture.prototype.isReady = function () {
  22905. var _this = this;
  22906. var engine = this.getScene().getEngine();
  22907. var shaders;
  22908. if (!this._fragment) {
  22909. return false;
  22910. }
  22911. if (this._fallbackTextureUsed) {
  22912. return true;
  22913. }
  22914. if (this._fragment.fragmentElement !== undefined) {
  22915. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  22916. }
  22917. else {
  22918. shaders = { vertex: "procedural", fragment: this._fragment };
  22919. }
  22920. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  22921. _this.releaseInternalTexture();
  22922. if (_this._fallbackTexture) {
  22923. _this._texture = _this._fallbackTexture._texture;
  22924. _this._texture.references++;
  22925. }
  22926. _this._fallbackTextureUsed = true;
  22927. });
  22928. return this._effect.isReady();
  22929. };
  22930. ProceduralTexture.prototype.resetRefreshCounter = function () {
  22931. this._currentRefreshId = -1;
  22932. };
  22933. ProceduralTexture.prototype.setFragment = function (fragment) {
  22934. this._fragment = fragment;
  22935. };
  22936. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  22937. get: function () {
  22938. return this._refreshRate;
  22939. },
  22940. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  22941. set: function (value) {
  22942. this._refreshRate = value;
  22943. this.resetRefreshCounter();
  22944. },
  22945. enumerable: true,
  22946. configurable: true
  22947. });
  22948. ProceduralTexture.prototype._shouldRender = function () {
  22949. if (!this.isEnabled || !this.isReady() || !this._texture) {
  22950. return false;
  22951. }
  22952. if (this._fallbackTextureUsed) {
  22953. return false;
  22954. }
  22955. if (this._currentRefreshId === -1) {
  22956. this._currentRefreshId = 1;
  22957. return true;
  22958. }
  22959. if (this.refreshRate === this._currentRefreshId) {
  22960. this._currentRefreshId = 1;
  22961. return true;
  22962. }
  22963. this._currentRefreshId++;
  22964. return false;
  22965. };
  22966. ProceduralTexture.prototype.getRenderSize = function () {
  22967. return this._size;
  22968. };
  22969. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  22970. if (this._fallbackTextureUsed) {
  22971. return;
  22972. }
  22973. this.releaseInternalTexture();
  22974. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  22975. };
  22976. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  22977. if (this._uniforms.indexOf(uniformName) === -1) {
  22978. this._uniforms.push(uniformName);
  22979. }
  22980. };
  22981. ProceduralTexture.prototype.setTexture = function (name, texture) {
  22982. if (this._samplers.indexOf(name) === -1) {
  22983. this._samplers.push(name);
  22984. }
  22985. this._textures[name] = texture;
  22986. return this;
  22987. };
  22988. ProceduralTexture.prototype.setFloat = function (name, value) {
  22989. this._checkUniform(name);
  22990. this._floats[name] = value;
  22991. return this;
  22992. };
  22993. ProceduralTexture.prototype.setFloats = function (name, value) {
  22994. this._checkUniform(name);
  22995. this._floatsArrays[name] = value;
  22996. return this;
  22997. };
  22998. ProceduralTexture.prototype.setColor3 = function (name, value) {
  22999. this._checkUniform(name);
  23000. this._colors3[name] = value;
  23001. return this;
  23002. };
  23003. ProceduralTexture.prototype.setColor4 = function (name, value) {
  23004. this._checkUniform(name);
  23005. this._colors4[name] = value;
  23006. return this;
  23007. };
  23008. ProceduralTexture.prototype.setVector2 = function (name, value) {
  23009. this._checkUniform(name);
  23010. this._vectors2[name] = value;
  23011. return this;
  23012. };
  23013. ProceduralTexture.prototype.setVector3 = function (name, value) {
  23014. this._checkUniform(name);
  23015. this._vectors3[name] = value;
  23016. return this;
  23017. };
  23018. ProceduralTexture.prototype.setMatrix = function (name, value) {
  23019. this._checkUniform(name);
  23020. this._matrices[name] = value;
  23021. return this;
  23022. };
  23023. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  23024. var scene = this.getScene();
  23025. var engine = scene.getEngine();
  23026. // Render
  23027. engine.enableEffect(this._effect);
  23028. engine.setState(false);
  23029. // Texture
  23030. for (var name in this._textures) {
  23031. this._effect.setTexture(name, this._textures[name]);
  23032. }
  23033. // Float
  23034. for (name in this._floats) {
  23035. this._effect.setFloat(name, this._floats[name]);
  23036. }
  23037. // Floats
  23038. for (name in this._floatsArrays) {
  23039. this._effect.setArray(name, this._floatsArrays[name]);
  23040. }
  23041. // Color3
  23042. for (name in this._colors3) {
  23043. this._effect.setColor3(name, this._colors3[name]);
  23044. }
  23045. // Color4
  23046. for (name in this._colors4) {
  23047. var color = this._colors4[name];
  23048. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  23049. }
  23050. // Vector2
  23051. for (name in this._vectors2) {
  23052. this._effect.setVector2(name, this._vectors2[name]);
  23053. }
  23054. // Vector3
  23055. for (name in this._vectors3) {
  23056. this._effect.setVector3(name, this._vectors3[name]);
  23057. }
  23058. // Matrix
  23059. for (name in this._matrices) {
  23060. this._effect.setMatrix(name, this._matrices[name]);
  23061. }
  23062. // VBOs
  23063. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  23064. if (this.isCube) {
  23065. for (var face = 0; face < 6; face++) {
  23066. engine.bindFramebuffer(this._texture, face);
  23067. this._effect.setFloat("face", face);
  23068. // Clear
  23069. engine.clear(scene.clearColor, true, true, true);
  23070. // Draw order
  23071. engine.draw(true, 0, 6);
  23072. // Mipmaps
  23073. if (face === 5) {
  23074. engine.generateMipMapsForCubemap(this._texture);
  23075. }
  23076. }
  23077. }
  23078. else {
  23079. engine.bindFramebuffer(this._texture);
  23080. // Clear
  23081. engine.clear(scene.clearColor, true, true, true);
  23082. // Draw order
  23083. engine.draw(true, 0, 6);
  23084. }
  23085. // Unbind
  23086. engine.unBindFramebuffer(this._texture, this.isCube);
  23087. if (this.onGenerated) {
  23088. this.onGenerated();
  23089. }
  23090. };
  23091. ProceduralTexture.prototype.clone = function () {
  23092. var textureSize = this.getSize();
  23093. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  23094. // Base texture
  23095. newTexture.hasAlpha = this.hasAlpha;
  23096. newTexture.level = this.level;
  23097. // RenderTarget Texture
  23098. newTexture.coordinatesMode = this.coordinatesMode;
  23099. return newTexture;
  23100. };
  23101. ProceduralTexture.prototype.dispose = function () {
  23102. var index = this.getScene()._proceduralTextures.indexOf(this);
  23103. if (index >= 0) {
  23104. this.getScene()._proceduralTextures.splice(index, 1);
  23105. }
  23106. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  23107. if (vertexBuffer) {
  23108. vertexBuffer.dispose();
  23109. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  23110. }
  23111. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  23112. this._indexBuffer = null;
  23113. }
  23114. _super.prototype.dispose.call(this);
  23115. };
  23116. return ProceduralTexture;
  23117. })(BABYLON.Texture);
  23118. BABYLON.ProceduralTexture = ProceduralTexture;
  23119. })(BABYLON || (BABYLON = {}));
  23120. var BABYLON;
  23121. (function (BABYLON) {
  23122. var MirrorTexture = (function (_super) {
  23123. __extends(MirrorTexture, _super);
  23124. function MirrorTexture(name, size, scene, generateMipMaps) {
  23125. var _this = this;
  23126. _super.call(this, name, size, scene, generateMipMaps, true);
  23127. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  23128. this._transformMatrix = BABYLON.Matrix.Zero();
  23129. this._mirrorMatrix = BABYLON.Matrix.Zero();
  23130. this.onBeforeRenderObservable.add(function () {
  23131. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  23132. _this._savedViewMatrix = scene.getViewMatrix();
  23133. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  23134. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  23135. scene.clipPlane = _this.mirrorPlane;
  23136. scene.getEngine().cullBackFaces = false;
  23137. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  23138. });
  23139. this.onAfterRenderObservable.add(function () {
  23140. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  23141. scene.getEngine().cullBackFaces = true;
  23142. scene._mirroredCameraPosition = null;
  23143. delete scene.clipPlane;
  23144. });
  23145. }
  23146. MirrorTexture.prototype.clone = function () {
  23147. var textureSize = this.getSize();
  23148. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23149. // Base texture
  23150. newTexture.hasAlpha = this.hasAlpha;
  23151. newTexture.level = this.level;
  23152. // Mirror Texture
  23153. newTexture.mirrorPlane = this.mirrorPlane.clone();
  23154. newTexture.renderList = this.renderList.slice(0);
  23155. return newTexture;
  23156. };
  23157. MirrorTexture.prototype.serialize = function () {
  23158. if (!this.name) {
  23159. return null;
  23160. }
  23161. var serializationObject = _super.prototype.serialize.call(this);
  23162. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  23163. return serializationObject;
  23164. };
  23165. return MirrorTexture;
  23166. })(BABYLON.RenderTargetTexture);
  23167. BABYLON.MirrorTexture = MirrorTexture;
  23168. })(BABYLON || (BABYLON = {}));
  23169. var BABYLON;
  23170. (function (BABYLON) {
  23171. /**
  23172. * Creates a refraction texture used by refraction channel of the standard material.
  23173. * @param name the texture name
  23174. * @param size size of the underlying texture
  23175. * @param scene root scene
  23176. */
  23177. var RefractionTexture = (function (_super) {
  23178. __extends(RefractionTexture, _super);
  23179. function RefractionTexture(name, size, scene, generateMipMaps) {
  23180. var _this = this;
  23181. _super.call(this, name, size, scene, generateMipMaps, true);
  23182. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  23183. this.depth = 2.0;
  23184. this.onBeforeRenderObservable.add(function () {
  23185. scene.clipPlane = _this.refractionPlane;
  23186. });
  23187. this.onAfterRenderObservable.add(function () {
  23188. delete scene.clipPlane;
  23189. });
  23190. }
  23191. RefractionTexture.prototype.clone = function () {
  23192. var textureSize = this.getSize();
  23193. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23194. // Base texture
  23195. newTexture.hasAlpha = this.hasAlpha;
  23196. newTexture.level = this.level;
  23197. // Refraction Texture
  23198. newTexture.refractionPlane = this.refractionPlane.clone();
  23199. newTexture.renderList = this.renderList.slice(0);
  23200. newTexture.depth = this.depth;
  23201. return newTexture;
  23202. };
  23203. RefractionTexture.prototype.serialize = function () {
  23204. if (!this.name) {
  23205. return null;
  23206. }
  23207. var serializationObject = _super.prototype.serialize.call(this);
  23208. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  23209. serializationObject.depth = this.depth;
  23210. return serializationObject;
  23211. };
  23212. return RefractionTexture;
  23213. })(BABYLON.RenderTargetTexture);
  23214. BABYLON.RefractionTexture = RefractionTexture;
  23215. })(BABYLON || (BABYLON = {}));
  23216. var BABYLON;
  23217. (function (BABYLON) {
  23218. var DynamicTexture = (function (_super) {
  23219. __extends(DynamicTexture, _super);
  23220. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  23221. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23222. _super.call(this, null, scene, !generateMipMaps);
  23223. this.name = name;
  23224. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23225. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23226. this._generateMipMaps = generateMipMaps;
  23227. if (options.getContext) {
  23228. this._canvas = options;
  23229. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  23230. }
  23231. else {
  23232. this._canvas = document.createElement("canvas");
  23233. if (options.width) {
  23234. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  23235. }
  23236. else {
  23237. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  23238. }
  23239. }
  23240. var textureSize = this.getSize();
  23241. this._canvas.width = textureSize.width;
  23242. this._canvas.height = textureSize.height;
  23243. this._context = this._canvas.getContext("2d");
  23244. }
  23245. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  23246. get: function () {
  23247. return true;
  23248. },
  23249. enumerable: true,
  23250. configurable: true
  23251. });
  23252. DynamicTexture.prototype.scale = function (ratio) {
  23253. var textureSize = this.getSize();
  23254. textureSize.width *= ratio;
  23255. textureSize.height *= ratio;
  23256. this._canvas.width = textureSize.width;
  23257. this._canvas.height = textureSize.height;
  23258. this.releaseInternalTexture();
  23259. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  23260. };
  23261. DynamicTexture.prototype.getContext = function () {
  23262. return this._context;
  23263. };
  23264. DynamicTexture.prototype.clear = function () {
  23265. var size = this.getSize();
  23266. this._context.fillRect(0, 0, size.width, size.height);
  23267. };
  23268. DynamicTexture.prototype.update = function (invertY) {
  23269. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  23270. };
  23271. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  23272. if (update === void 0) { update = true; }
  23273. var size = this.getSize();
  23274. if (clearColor) {
  23275. this._context.fillStyle = clearColor;
  23276. this._context.fillRect(0, 0, size.width, size.height);
  23277. }
  23278. this._context.font = font;
  23279. if (x === null) {
  23280. var textSize = this._context.measureText(text);
  23281. x = (size.width - textSize.width) / 2;
  23282. }
  23283. this._context.fillStyle = color;
  23284. this._context.fillText(text, x, y);
  23285. if (update) {
  23286. this.update(invertY);
  23287. }
  23288. };
  23289. DynamicTexture.prototype.clone = function () {
  23290. var textureSize = this.getSize();
  23291. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  23292. // Base texture
  23293. newTexture.hasAlpha = this.hasAlpha;
  23294. newTexture.level = this.level;
  23295. // Dynamic Texture
  23296. newTexture.wrapU = this.wrapU;
  23297. newTexture.wrapV = this.wrapV;
  23298. return newTexture;
  23299. };
  23300. return DynamicTexture;
  23301. })(BABYLON.Texture);
  23302. BABYLON.DynamicTexture = DynamicTexture;
  23303. })(BABYLON || (BABYLON = {}));
  23304. var BABYLON;
  23305. (function (BABYLON) {
  23306. var VideoTexture = (function (_super) {
  23307. __extends(VideoTexture, _super);
  23308. /**
  23309. * Creates a video texture.
  23310. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  23311. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  23312. * @param {BABYLON.Scene} scene is obviously the current scene.
  23313. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  23314. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  23315. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  23316. */
  23317. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  23318. var _this = this;
  23319. if (generateMipMaps === void 0) { generateMipMaps = false; }
  23320. if (invertY === void 0) { invertY = false; }
  23321. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23322. _super.call(this, null, scene, !generateMipMaps, invertY);
  23323. this._autoLaunch = true;
  23324. var urls;
  23325. this.name = name;
  23326. if (urlsOrVideo instanceof HTMLVideoElement) {
  23327. this.video = urlsOrVideo;
  23328. }
  23329. else {
  23330. urls = urlsOrVideo;
  23331. this.video = document.createElement("video");
  23332. this.video.autoplay = false;
  23333. this.video.loop = true;
  23334. }
  23335. this._generateMipMaps = generateMipMaps;
  23336. this._samplingMode = samplingMode;
  23337. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  23338. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23339. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23340. }
  23341. else {
  23342. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23343. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23344. this._generateMipMaps = false;
  23345. }
  23346. if (urls) {
  23347. this.video.addEventListener("canplaythrough", function () {
  23348. _this._createTexture();
  23349. });
  23350. urls.forEach(function (url) {
  23351. var source = document.createElement("source");
  23352. source.src = url;
  23353. _this.video.appendChild(source);
  23354. });
  23355. }
  23356. else {
  23357. this._createTexture();
  23358. }
  23359. this._lastUpdate = BABYLON.Tools.Now;
  23360. }
  23361. VideoTexture.prototype._createTexture = function () {
  23362. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  23363. this._texture.isReady = true;
  23364. };
  23365. VideoTexture.prototype.update = function () {
  23366. if (this._autoLaunch) {
  23367. this._autoLaunch = false;
  23368. this.video.play();
  23369. }
  23370. var now = BABYLON.Tools.Now;
  23371. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  23372. return false;
  23373. }
  23374. this._lastUpdate = now;
  23375. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  23376. return true;
  23377. };
  23378. return VideoTexture;
  23379. })(BABYLON.Texture);
  23380. BABYLON.VideoTexture = VideoTexture;
  23381. })(BABYLON || (BABYLON = {}));
  23382. var BABYLON;
  23383. (function (BABYLON) {
  23384. var CustomProceduralTexture = (function (_super) {
  23385. __extends(CustomProceduralTexture, _super);
  23386. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  23387. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  23388. this._animate = true;
  23389. this._time = 0;
  23390. this._texturePath = texturePath;
  23391. //Try to load json
  23392. this.loadJson(texturePath);
  23393. this.refreshRate = 1;
  23394. }
  23395. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  23396. var _this = this;
  23397. var that = this;
  23398. function noConfigFile() {
  23399. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  23400. try {
  23401. that.setFragment(that._texturePath);
  23402. }
  23403. catch (ex) {
  23404. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  23405. }
  23406. }
  23407. var configFileUrl = jsonUrl + "/config.json";
  23408. var xhr = new XMLHttpRequest();
  23409. xhr.open("GET", configFileUrl, true);
  23410. xhr.addEventListener("load", function () {
  23411. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  23412. try {
  23413. _this._config = JSON.parse(xhr.response);
  23414. _this.updateShaderUniforms();
  23415. _this.updateTextures();
  23416. _this.setFragment(_this._texturePath + "/custom");
  23417. _this._animate = _this._config.animate;
  23418. _this.refreshRate = _this._config.refreshrate;
  23419. }
  23420. catch (ex) {
  23421. noConfigFile();
  23422. }
  23423. }
  23424. else {
  23425. noConfigFile();
  23426. }
  23427. }, false);
  23428. xhr.addEventListener("error", function () {
  23429. noConfigFile();
  23430. }, false);
  23431. try {
  23432. xhr.send();
  23433. }
  23434. catch (ex) {
  23435. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  23436. }
  23437. };
  23438. CustomProceduralTexture.prototype.isReady = function () {
  23439. if (!_super.prototype.isReady.call(this)) {
  23440. return false;
  23441. }
  23442. for (var name in this._textures) {
  23443. var texture = this._textures[name];
  23444. if (!texture.isReady()) {
  23445. return false;
  23446. }
  23447. }
  23448. return true;
  23449. };
  23450. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  23451. if (this._animate) {
  23452. this._time += this.getScene().getAnimationRatio() * 0.03;
  23453. this.updateShaderUniforms();
  23454. }
  23455. _super.prototype.render.call(this, useCameraPostProcess);
  23456. };
  23457. CustomProceduralTexture.prototype.updateTextures = function () {
  23458. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  23459. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  23460. }
  23461. };
  23462. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  23463. if (this._config) {
  23464. for (var j = 0; j < this._config.uniforms.length; j++) {
  23465. var uniform = this._config.uniforms[j];
  23466. switch (uniform.type) {
  23467. case "float":
  23468. this.setFloat(uniform.name, uniform.value);
  23469. break;
  23470. case "color3":
  23471. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  23472. break;
  23473. case "color4":
  23474. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  23475. break;
  23476. case "vector2":
  23477. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  23478. break;
  23479. case "vector3":
  23480. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  23481. break;
  23482. }
  23483. }
  23484. }
  23485. this.setFloat("time", this._time);
  23486. };
  23487. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  23488. get: function () {
  23489. return this._animate;
  23490. },
  23491. set: function (value) {
  23492. this._animate = value;
  23493. },
  23494. enumerable: true,
  23495. configurable: true
  23496. });
  23497. return CustomProceduralTexture;
  23498. })(BABYLON.ProceduralTexture);
  23499. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  23500. })(BABYLON || (BABYLON = {}));
  23501. var BABYLON;
  23502. (function (BABYLON) {
  23503. var EffectFallbacks = (function () {
  23504. function EffectFallbacks() {
  23505. this._defines = {};
  23506. this._currentRank = 32;
  23507. this._maxRank = -1;
  23508. }
  23509. EffectFallbacks.prototype.addFallback = function (rank, define) {
  23510. if (!this._defines[rank]) {
  23511. if (rank < this._currentRank) {
  23512. this._currentRank = rank;
  23513. }
  23514. if (rank > this._maxRank) {
  23515. this._maxRank = rank;
  23516. }
  23517. this._defines[rank] = new Array();
  23518. }
  23519. this._defines[rank].push(define);
  23520. };
  23521. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  23522. this._meshRank = rank;
  23523. this._mesh = mesh;
  23524. if (rank > this._maxRank) {
  23525. this._maxRank = rank;
  23526. }
  23527. };
  23528. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  23529. get: function () {
  23530. return this._currentRank <= this._maxRank;
  23531. },
  23532. enumerable: true,
  23533. configurable: true
  23534. });
  23535. EffectFallbacks.prototype.reduce = function (currentDefines) {
  23536. var currentFallbacks = this._defines[this._currentRank];
  23537. for (var index = 0; index < currentFallbacks.length; index++) {
  23538. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  23539. }
  23540. if (this._mesh && this._currentRank === this._meshRank) {
  23541. this._mesh.computeBonesUsingShaders = false;
  23542. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  23543. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  23544. }
  23545. this._currentRank++;
  23546. return currentDefines;
  23547. };
  23548. return EffectFallbacks;
  23549. })();
  23550. BABYLON.EffectFallbacks = EffectFallbacks;
  23551. var Effect = (function () {
  23552. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  23553. var _this = this;
  23554. this._isReady = false;
  23555. this._compilationError = "";
  23556. this._valueCache = {};
  23557. this._engine = engine;
  23558. this.name = baseName;
  23559. this.defines = defines;
  23560. this._uniformsNames = uniformsNames.concat(samplers);
  23561. this._samplers = samplers;
  23562. this._attributesNames = attributesNames;
  23563. this.onError = onError;
  23564. this.onCompiled = onCompiled;
  23565. this._indexParameters = indexParameters;
  23566. var vertexSource;
  23567. var fragmentSource;
  23568. if (baseName.vertexElement) {
  23569. vertexSource = document.getElementById(baseName.vertexElement);
  23570. if (!vertexSource) {
  23571. vertexSource = baseName.vertexElement;
  23572. }
  23573. }
  23574. else {
  23575. vertexSource = baseName.vertex || baseName;
  23576. }
  23577. if (baseName.fragmentElement) {
  23578. fragmentSource = document.getElementById(baseName.fragmentElement);
  23579. if (!fragmentSource) {
  23580. fragmentSource = baseName.fragmentElement;
  23581. }
  23582. }
  23583. else {
  23584. fragmentSource = baseName.fragment || baseName;
  23585. }
  23586. this._loadVertexShader(vertexSource, function (vertexCode) {
  23587. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  23588. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  23589. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  23590. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  23591. });
  23592. });
  23593. });
  23594. });
  23595. }
  23596. // Properties
  23597. Effect.prototype.isReady = function () {
  23598. return this._isReady;
  23599. };
  23600. Effect.prototype.getProgram = function () {
  23601. return this._program;
  23602. };
  23603. Effect.prototype.getAttributesNames = function () {
  23604. return this._attributesNames;
  23605. };
  23606. Effect.prototype.getAttributeLocation = function (index) {
  23607. return this._attributes[index];
  23608. };
  23609. Effect.prototype.getAttributeLocationByName = function (name) {
  23610. var index = this._attributesNames.indexOf(name);
  23611. return this._attributes[index];
  23612. };
  23613. Effect.prototype.getAttributesCount = function () {
  23614. return this._attributes.length;
  23615. };
  23616. Effect.prototype.getUniformIndex = function (uniformName) {
  23617. return this._uniformsNames.indexOf(uniformName);
  23618. };
  23619. Effect.prototype.getUniform = function (uniformName) {
  23620. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  23621. };
  23622. Effect.prototype.getSamplers = function () {
  23623. return this._samplers;
  23624. };
  23625. Effect.prototype.getCompilationError = function () {
  23626. return this._compilationError;
  23627. };
  23628. // Methods
  23629. Effect.prototype._loadVertexShader = function (vertex, callback) {
  23630. // DOM element ?
  23631. if (vertex instanceof HTMLElement) {
  23632. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  23633. callback(vertexCode);
  23634. return;
  23635. }
  23636. // Is in local store ?
  23637. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  23638. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  23639. return;
  23640. }
  23641. var vertexShaderUrl;
  23642. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  23643. vertexShaderUrl = vertex;
  23644. }
  23645. else {
  23646. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  23647. }
  23648. // Vertex shader
  23649. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  23650. };
  23651. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  23652. // DOM element ?
  23653. if (fragment instanceof HTMLElement) {
  23654. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  23655. callback(fragmentCode);
  23656. return;
  23657. }
  23658. // Is in local store ?
  23659. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  23660. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  23661. return;
  23662. }
  23663. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  23664. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  23665. return;
  23666. }
  23667. var fragmentShaderUrl;
  23668. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  23669. fragmentShaderUrl = fragment;
  23670. }
  23671. else {
  23672. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  23673. }
  23674. // Fragment shader
  23675. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  23676. };
  23677. Effect.prototype._dumpShadersName = function () {
  23678. if (this.name.vertexElement) {
  23679. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  23680. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  23681. }
  23682. else if (this.name.vertex) {
  23683. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  23684. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  23685. }
  23686. else {
  23687. BABYLON.Tools.Error("Vertex shader:" + this.name);
  23688. BABYLON.Tools.Error("Fragment shader:" + this.name);
  23689. }
  23690. };
  23691. Effect.prototype._processIncludes = function (sourceCode, callback) {
  23692. var _this = this;
  23693. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  23694. var match = regex.exec(sourceCode);
  23695. var returnValue = new String(sourceCode);
  23696. while (match != null) {
  23697. var includeFile = match[1];
  23698. if (Effect.IncludesShadersStore[includeFile]) {
  23699. // Substitution
  23700. var includeContent = Effect.IncludesShadersStore[includeFile];
  23701. if (match[2]) {
  23702. var splits = match[3].split(",");
  23703. for (var index = 0; index < splits.length; index += 2) {
  23704. var source = new RegExp(splits[index], "g");
  23705. var dest = splits[index + 1];
  23706. includeContent = includeContent.replace(source, dest);
  23707. }
  23708. }
  23709. if (match[4]) {
  23710. var indexString = match[5];
  23711. if (indexString.indexOf("..") !== -1) {
  23712. var indexSplits = indexString.split("..");
  23713. var minIndex = parseInt(indexSplits[0]);
  23714. var maxIndex = parseInt(indexSplits[1]);
  23715. var sourceIncludeContent = includeContent.slice(0);
  23716. includeContent = "";
  23717. if (isNaN(maxIndex)) {
  23718. maxIndex = this._indexParameters[indexSplits[1]];
  23719. }
  23720. for (var i = minIndex; i <= maxIndex; i++) {
  23721. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  23722. }
  23723. }
  23724. else {
  23725. includeContent = includeContent.replace(/\{X\}/g, indexString);
  23726. }
  23727. }
  23728. // Replace
  23729. returnValue = returnValue.replace(match[0], includeContent);
  23730. }
  23731. else {
  23732. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  23733. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  23734. Effect.IncludesShadersStore[includeFile] = fileContent;
  23735. _this._processIncludes(returnValue, callback);
  23736. });
  23737. return;
  23738. }
  23739. match = regex.exec(sourceCode);
  23740. }
  23741. callback(returnValue);
  23742. };
  23743. Effect.prototype._processPrecision = function (source) {
  23744. if (source.indexOf("precision highp float") === -1) {
  23745. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23746. source = "precision mediump float;\n" + source;
  23747. }
  23748. else {
  23749. source = "precision highp float;\n" + source;
  23750. }
  23751. }
  23752. else {
  23753. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23754. source = source.replace("precision highp float", "precision mediump float");
  23755. }
  23756. }
  23757. return source;
  23758. };
  23759. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  23760. try {
  23761. var engine = this._engine;
  23762. // Precision
  23763. vertexSourceCode = this._processPrecision(vertexSourceCode);
  23764. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  23765. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  23766. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  23767. this._attributes = engine.getAttributes(this._program, attributesNames);
  23768. var index;
  23769. for (index = 0; index < this._samplers.length; index++) {
  23770. var sampler = this.getUniform(this._samplers[index]);
  23771. if (sampler == null) {
  23772. this._samplers.splice(index, 1);
  23773. index--;
  23774. }
  23775. }
  23776. engine.bindSamplers(this);
  23777. this._isReady = true;
  23778. if (this.onCompiled) {
  23779. this.onCompiled(this);
  23780. }
  23781. }
  23782. catch (e) {
  23783. // Let's go through fallbacks then
  23784. if (fallbacks && fallbacks.isMoreFallbacks) {
  23785. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  23786. this._dumpShadersName();
  23787. defines = fallbacks.reduce(defines);
  23788. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  23789. }
  23790. else {
  23791. BABYLON.Tools.Error("Unable to compile effect: ");
  23792. this._dumpShadersName();
  23793. BABYLON.Tools.Error("Defines: " + defines);
  23794. BABYLON.Tools.Error("Error: " + e.message);
  23795. this._compilationError = e.message;
  23796. if (this.onError) {
  23797. this.onError(this, this._compilationError);
  23798. }
  23799. }
  23800. }
  23801. };
  23802. Object.defineProperty(Effect.prototype, "isSupported", {
  23803. get: function () {
  23804. return this._compilationError === "";
  23805. },
  23806. enumerable: true,
  23807. configurable: true
  23808. });
  23809. Effect.prototype._bindTexture = function (channel, texture) {
  23810. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  23811. };
  23812. Effect.prototype.setTexture = function (channel, texture) {
  23813. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  23814. };
  23815. Effect.prototype.setTextureArray = function (channel, textures) {
  23816. if (this._samplers.indexOf(channel + "Ex") === -1) {
  23817. var initialPos = this._samplers.indexOf(channel);
  23818. for (var index = 1; index < textures.length; index++) {
  23819. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  23820. }
  23821. }
  23822. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  23823. };
  23824. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  23825. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  23826. };
  23827. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  23828. var changed = false;
  23829. var cache = this._valueCache[uniformName];
  23830. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  23831. changed = true;
  23832. cache = new BABYLON.Matrix();
  23833. }
  23834. var tm = cache.m;
  23835. var om = matrix.m;
  23836. for (var index = 0; index < 16; index++) {
  23837. if (tm[index] !== om[index]) {
  23838. tm[index] = om[index];
  23839. changed = true;
  23840. }
  23841. }
  23842. this._valueCache[uniformName] = cache;
  23843. return changed;
  23844. };
  23845. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  23846. var cache = this._valueCache[uniformName];
  23847. if (!cache) {
  23848. cache = [x, y];
  23849. this._valueCache[uniformName] = cache;
  23850. return true;
  23851. }
  23852. var changed = false;
  23853. if (cache[0] !== x) {
  23854. cache[0] = x;
  23855. changed = true;
  23856. }
  23857. if (cache[1] !== y) {
  23858. cache[1] = y;
  23859. changed = true;
  23860. }
  23861. return changed;
  23862. };
  23863. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  23864. var cache = this._valueCache[uniformName];
  23865. if (!cache) {
  23866. cache = [x, y, z];
  23867. this._valueCache[uniformName] = cache;
  23868. return true;
  23869. }
  23870. var changed = false;
  23871. if (cache[0] !== x) {
  23872. cache[0] = x;
  23873. changed = true;
  23874. }
  23875. if (cache[1] !== y) {
  23876. cache[1] = y;
  23877. changed = true;
  23878. }
  23879. if (cache[2] !== z) {
  23880. cache[2] = z;
  23881. changed = true;
  23882. }
  23883. return changed;
  23884. };
  23885. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  23886. var cache = this._valueCache[uniformName];
  23887. if (!cache) {
  23888. cache = [x, y, z, w];
  23889. this._valueCache[uniformName] = cache;
  23890. return true;
  23891. }
  23892. var changed = false;
  23893. if (cache[0] !== x) {
  23894. cache[0] = x;
  23895. changed = true;
  23896. }
  23897. if (cache[1] !== y) {
  23898. cache[1] = y;
  23899. changed = true;
  23900. }
  23901. if (cache[2] !== z) {
  23902. cache[2] = z;
  23903. changed = true;
  23904. }
  23905. if (cache[3] !== w) {
  23906. cache[3] = w;
  23907. changed = true;
  23908. }
  23909. return changed;
  23910. };
  23911. Effect.prototype.setIntArray = function (uniformName, array) {
  23912. this._valueCache[uniformName] = null;
  23913. this._engine.setIntArray(this.getUniform(uniformName), array);
  23914. return this;
  23915. };
  23916. Effect.prototype.setIntArray2 = function (uniformName, array) {
  23917. this._valueCache[uniformName] = null;
  23918. this._engine.setIntArray2(this.getUniform(uniformName), array);
  23919. return this;
  23920. };
  23921. Effect.prototype.setIntArray3 = function (uniformName, array) {
  23922. this._valueCache[uniformName] = null;
  23923. this._engine.setIntArray3(this.getUniform(uniformName), array);
  23924. return this;
  23925. };
  23926. Effect.prototype.setIntArray4 = function (uniformName, array) {
  23927. this._valueCache[uniformName] = null;
  23928. this._engine.setIntArray4(this.getUniform(uniformName), array);
  23929. return this;
  23930. };
  23931. Effect.prototype.setFloatArray = function (uniformName, array) {
  23932. this._valueCache[uniformName] = null;
  23933. this._engine.setFloatArray(this.getUniform(uniformName), array);
  23934. return this;
  23935. };
  23936. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  23937. this._valueCache[uniformName] = null;
  23938. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  23939. return this;
  23940. };
  23941. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  23942. this._valueCache[uniformName] = null;
  23943. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  23944. return this;
  23945. };
  23946. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  23947. this._valueCache[uniformName] = null;
  23948. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  23949. return this;
  23950. };
  23951. Effect.prototype.setArray = function (uniformName, array) {
  23952. this._valueCache[uniformName] = null;
  23953. this._engine.setArray(this.getUniform(uniformName), array);
  23954. return this;
  23955. };
  23956. Effect.prototype.setArray2 = function (uniformName, array) {
  23957. this._valueCache[uniformName] = null;
  23958. this._engine.setArray2(this.getUniform(uniformName), array);
  23959. return this;
  23960. };
  23961. Effect.prototype.setArray3 = function (uniformName, array) {
  23962. this._valueCache[uniformName] = null;
  23963. this._engine.setArray3(this.getUniform(uniformName), array);
  23964. return this;
  23965. };
  23966. Effect.prototype.setArray4 = function (uniformName, array) {
  23967. this._valueCache[uniformName] = null;
  23968. this._engine.setArray4(this.getUniform(uniformName), array);
  23969. return this;
  23970. };
  23971. Effect.prototype.setMatrices = function (uniformName, matrices) {
  23972. this._valueCache[uniformName] = null;
  23973. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  23974. return this;
  23975. };
  23976. Effect.prototype.setMatrix = function (uniformName, matrix) {
  23977. if (this._cacheMatrix(uniformName, matrix)) {
  23978. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  23979. }
  23980. return this;
  23981. };
  23982. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  23983. this._valueCache[uniformName] = null;
  23984. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  23985. return this;
  23986. };
  23987. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  23988. this._valueCache[uniformName] = null;
  23989. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  23990. return this;
  23991. };
  23992. Effect.prototype.setFloat = function (uniformName, value) {
  23993. var cache = this._valueCache[uniformName];
  23994. if (cache !== undefined && cache === value)
  23995. return this;
  23996. this._valueCache[uniformName] = value;
  23997. this._engine.setFloat(this.getUniform(uniformName), value);
  23998. return this;
  23999. };
  24000. Effect.prototype.setBool = function (uniformName, bool) {
  24001. var cache = this._valueCache[uniformName];
  24002. if (cache !== undefined && cache === bool)
  24003. return this;
  24004. this._valueCache[uniformName] = bool;
  24005. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24006. return this;
  24007. };
  24008. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24009. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24010. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24011. }
  24012. return this;
  24013. };
  24014. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24015. if (this._cacheFloat2(uniformName, x, y)) {
  24016. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24017. }
  24018. return this;
  24019. };
  24020. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24021. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24022. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24023. }
  24024. return this;
  24025. };
  24026. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24027. if (this._cacheFloat3(uniformName, x, y, z)) {
  24028. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24029. }
  24030. return this;
  24031. };
  24032. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24033. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24034. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24035. }
  24036. return this;
  24037. };
  24038. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24039. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24040. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24041. }
  24042. return this;
  24043. };
  24044. Effect.prototype.setColor3 = function (uniformName, color3) {
  24045. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24046. this._engine.setColor3(this.getUniform(uniformName), color3);
  24047. }
  24048. return this;
  24049. };
  24050. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24051. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24052. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24053. }
  24054. return this;
  24055. };
  24056. // Statics
  24057. Effect.ShadersStore = {};
  24058. Effect.IncludesShadersStore = {};
  24059. return Effect;
  24060. })();
  24061. BABYLON.Effect = Effect;
  24062. })(BABYLON || (BABYLON = {}));
  24063. var BABYLON;
  24064. (function (BABYLON) {
  24065. var MaterialHelper = (function () {
  24066. function MaterialHelper() {
  24067. }
  24068. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  24069. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24070. var lightIndex = 0;
  24071. var needNormals = false;
  24072. var needRebuild = false;
  24073. var needShadows = false;
  24074. for (var index = 0; index < scene.lights.length; index++) {
  24075. var light = scene.lights[index];
  24076. if (!light.isEnabled()) {
  24077. continue;
  24078. }
  24079. // Excluded check
  24080. if (light._excludedMeshesIds.length > 0) {
  24081. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  24082. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  24083. if (excludedMesh) {
  24084. light.excludedMeshes.push(excludedMesh);
  24085. }
  24086. }
  24087. light._excludedMeshesIds = [];
  24088. }
  24089. // Included check
  24090. if (light._includedOnlyMeshesIds.length > 0) {
  24091. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  24092. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  24093. if (includedOnlyMesh) {
  24094. light.includedOnlyMeshes.push(includedOnlyMesh);
  24095. }
  24096. }
  24097. light._includedOnlyMeshesIds = [];
  24098. }
  24099. if (!light.canAffectMesh(mesh)) {
  24100. continue;
  24101. }
  24102. needNormals = true;
  24103. if (defines["LIGHT" + lightIndex] === undefined) {
  24104. needRebuild = true;
  24105. }
  24106. defines["LIGHT" + lightIndex] = true;
  24107. var type;
  24108. if (light instanceof BABYLON.SpotLight) {
  24109. type = "SPOTLIGHT" + lightIndex;
  24110. }
  24111. else if (light instanceof BABYLON.HemisphericLight) {
  24112. type = "HEMILIGHT" + lightIndex;
  24113. }
  24114. else if (light instanceof BABYLON.PointLight) {
  24115. type = "POINTLIGHT" + lightIndex;
  24116. }
  24117. else {
  24118. type = "DIRLIGHT" + lightIndex;
  24119. }
  24120. if (defines[type] === undefined) {
  24121. needRebuild = true;
  24122. }
  24123. defines[type] = true;
  24124. // Specular
  24125. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  24126. defines["SPECULARTERM"] = true;
  24127. }
  24128. // Shadows
  24129. if (scene.shadowsEnabled) {
  24130. var shadowGenerator = light.getShadowGenerator();
  24131. if (mesh && mesh.receiveShadows && shadowGenerator) {
  24132. if (defines["SHADOW" + lightIndex] === undefined) {
  24133. needRebuild = true;
  24134. }
  24135. defines["SHADOW" + lightIndex] = true;
  24136. defines["SHADOWS"] = true;
  24137. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  24138. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  24139. needRebuild = true;
  24140. }
  24141. defines["SHADOWVSM" + lightIndex] = true;
  24142. }
  24143. if (shadowGenerator.usePoissonSampling) {
  24144. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  24145. needRebuild = true;
  24146. }
  24147. defines["SHADOWPCF" + lightIndex] = true;
  24148. }
  24149. needShadows = true;
  24150. }
  24151. }
  24152. lightIndex++;
  24153. if (lightIndex === maxSimultaneousLights)
  24154. break;
  24155. }
  24156. var caps = scene.getEngine().getCaps();
  24157. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  24158. if (defines["SHADOWFULLFLOAT"] === undefined) {
  24159. needRebuild = true;
  24160. }
  24161. defines["SHADOWFULLFLOAT"] = true;
  24162. }
  24163. if (needRebuild) {
  24164. defines.rebuild();
  24165. }
  24166. return needNormals;
  24167. };
  24168. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  24169. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24170. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24171. if (!defines["LIGHT" + lightIndex]) {
  24172. break;
  24173. }
  24174. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  24175. samplersList.push("shadowSampler" + lightIndex);
  24176. }
  24177. };
  24178. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  24179. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24180. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24181. if (!defines["LIGHT" + lightIndex]) {
  24182. break;
  24183. }
  24184. if (lightIndex > 0) {
  24185. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  24186. }
  24187. if (defines["SHADOW" + lightIndex]) {
  24188. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  24189. }
  24190. if (defines["SHADOWPCF" + lightIndex]) {
  24191. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  24192. }
  24193. if (defines["SHADOWVSM" + lightIndex]) {
  24194. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  24195. }
  24196. }
  24197. };
  24198. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  24199. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  24200. fallbacks.addCPUSkinningFallback(0, mesh);
  24201. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24202. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24203. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  24204. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  24205. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  24206. }
  24207. }
  24208. };
  24209. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  24210. if (defines["INSTANCES"]) {
  24211. attribs.push("world0");
  24212. attribs.push("world1");
  24213. attribs.push("world2");
  24214. attribs.push("world3");
  24215. }
  24216. };
  24217. // Bindings
  24218. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  24219. var shadowGenerator = light.getShadowGenerator();
  24220. if (mesh.receiveShadows && shadowGenerator) {
  24221. if (!light.needCube()) {
  24222. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  24223. }
  24224. else {
  24225. if (!depthValuesAlreadySet) {
  24226. depthValuesAlreadySet = true;
  24227. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  24228. }
  24229. }
  24230. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  24231. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  24232. }
  24233. return depthValuesAlreadySet;
  24234. };
  24235. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  24236. if (light instanceof BABYLON.PointLight) {
  24237. // Point Light
  24238. light.transferToEffect(effect, "vLightData" + lightIndex);
  24239. }
  24240. else if (light instanceof BABYLON.DirectionalLight) {
  24241. // Directional Light
  24242. light.transferToEffect(effect, "vLightData" + lightIndex);
  24243. }
  24244. else if (light instanceof BABYLON.SpotLight) {
  24245. // Spot Light
  24246. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  24247. }
  24248. else if (light instanceof BABYLON.HemisphericLight) {
  24249. // Hemispheric Light
  24250. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  24251. }
  24252. };
  24253. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  24254. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24255. var lightIndex = 0;
  24256. var depthValuesAlreadySet = false;
  24257. for (var index = 0; index < scene.lights.length; index++) {
  24258. var light = scene.lights[index];
  24259. if (!light.isEnabled()) {
  24260. continue;
  24261. }
  24262. if (!light.canAffectMesh(mesh)) {
  24263. continue;
  24264. }
  24265. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  24266. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  24267. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  24268. if (defines["SPECULARTERM"]) {
  24269. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  24270. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  24271. }
  24272. // Shadows
  24273. if (scene.shadowsEnabled) {
  24274. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  24275. }
  24276. lightIndex++;
  24277. if (lightIndex === maxSimultaneousLights)
  24278. break;
  24279. }
  24280. };
  24281. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  24282. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  24283. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  24284. effect.setColor3("vFogColor", scene.fogColor);
  24285. }
  24286. };
  24287. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  24288. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  24289. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  24290. }
  24291. };
  24292. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  24293. if (defines["LOGARITHMICDEPTH"]) {
  24294. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  24295. }
  24296. };
  24297. MaterialHelper.BindClipPlane = function (effect, scene) {
  24298. if (scene.clipPlane) {
  24299. var clipPlane = scene.clipPlane;
  24300. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  24301. }
  24302. };
  24303. return MaterialHelper;
  24304. })();
  24305. BABYLON.MaterialHelper = MaterialHelper;
  24306. })(BABYLON || (BABYLON = {}));
  24307. var BABYLON;
  24308. (function (BABYLON) {
  24309. var FresnelParameters = (function () {
  24310. function FresnelParameters() {
  24311. this.isEnabled = true;
  24312. this.leftColor = BABYLON.Color3.White();
  24313. this.rightColor = BABYLON.Color3.Black();
  24314. this.bias = 0;
  24315. this.power = 1;
  24316. }
  24317. FresnelParameters.prototype.clone = function () {
  24318. var newFresnelParameters = new FresnelParameters();
  24319. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  24320. return new FresnelParameters;
  24321. };
  24322. FresnelParameters.prototype.serialize = function () {
  24323. var serializationObject = {};
  24324. serializationObject.isEnabled = this.isEnabled;
  24325. serializationObject.leftColor = this.leftColor;
  24326. serializationObject.rightColor = this.rightColor;
  24327. serializationObject.bias = this.bias;
  24328. serializationObject.power = this.power;
  24329. return serializationObject;
  24330. };
  24331. FresnelParameters.Parse = function (parsedFresnelParameters) {
  24332. var fresnelParameters = new FresnelParameters();
  24333. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  24334. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  24335. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  24336. fresnelParameters.bias = parsedFresnelParameters.bias;
  24337. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  24338. return fresnelParameters;
  24339. };
  24340. return FresnelParameters;
  24341. })();
  24342. BABYLON.FresnelParameters = FresnelParameters;
  24343. })(BABYLON || (BABYLON = {}));
  24344. var BABYLON;
  24345. (function (BABYLON) {
  24346. var MaterialDefines = (function () {
  24347. function MaterialDefines() {
  24348. }
  24349. MaterialDefines.prototype.rebuild = function () {
  24350. if (this._keys) {
  24351. delete this._keys;
  24352. }
  24353. this._keys = Object.keys(this);
  24354. };
  24355. MaterialDefines.prototype.isEqual = function (other) {
  24356. if (this._keys.length !== other._keys.length) {
  24357. return false;
  24358. }
  24359. for (var index = 0; index < this._keys.length; index++) {
  24360. var prop = this._keys[index];
  24361. if (this[prop] !== other[prop]) {
  24362. return false;
  24363. }
  24364. }
  24365. return true;
  24366. };
  24367. MaterialDefines.prototype.cloneTo = function (other) {
  24368. if (this._keys.length !== other._keys.length) {
  24369. other._keys = this._keys.slice(0);
  24370. }
  24371. for (var index = 0; index < this._keys.length; index++) {
  24372. var prop = this._keys[index];
  24373. other[prop] = this[prop];
  24374. }
  24375. };
  24376. MaterialDefines.prototype.reset = function () {
  24377. for (var index = 0; index < this._keys.length; index++) {
  24378. var prop = this._keys[index];
  24379. if (typeof (this[prop]) === "number") {
  24380. this[prop] = 0;
  24381. }
  24382. else {
  24383. this[prop] = false;
  24384. }
  24385. }
  24386. };
  24387. MaterialDefines.prototype.toString = function () {
  24388. var result = "";
  24389. for (var index = 0; index < this._keys.length; index++) {
  24390. var prop = this._keys[index];
  24391. if (typeof (this[prop]) === "number") {
  24392. result += "#define " + prop + " " + this[prop] + "\n";
  24393. }
  24394. else if (this[prop]) {
  24395. result += "#define " + prop + "\n";
  24396. }
  24397. }
  24398. return result;
  24399. };
  24400. return MaterialDefines;
  24401. })();
  24402. BABYLON.MaterialDefines = MaterialDefines;
  24403. var Material = (function () {
  24404. function Material(name, scene, doNotAdd) {
  24405. this.name = name;
  24406. this.checkReadyOnEveryCall = false;
  24407. this.checkReadyOnlyOnce = false;
  24408. this.state = "";
  24409. this.alpha = 1.0;
  24410. this.backFaceCulling = true;
  24411. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  24412. /**
  24413. * An event triggered when the material is disposed.
  24414. * @type {BABYLON.Observable}
  24415. */
  24416. this.onDisposeObservable = new BABYLON.Observable();
  24417. /**
  24418. * An event triggered when the material is bound.
  24419. * @type {BABYLON.Observable}
  24420. */
  24421. this.onBindObservable = new BABYLON.Observable();
  24422. /**
  24423. * An event triggered when the material is unbound.
  24424. * @type {BABYLON.Observable}
  24425. */
  24426. this.onUnBindObservable = new BABYLON.Observable();
  24427. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  24428. this.disableDepthWrite = false;
  24429. this.fogEnabled = true;
  24430. this.pointSize = 1.0;
  24431. this.zOffset = 0;
  24432. this._wasPreviouslyReady = false;
  24433. this._fillMode = Material.TriangleFillMode;
  24434. this.id = name;
  24435. this._scene = scene;
  24436. if (!doNotAdd) {
  24437. scene.materials.push(this);
  24438. }
  24439. }
  24440. Object.defineProperty(Material, "TriangleFillMode", {
  24441. get: function () {
  24442. return Material._TriangleFillMode;
  24443. },
  24444. enumerable: true,
  24445. configurable: true
  24446. });
  24447. Object.defineProperty(Material, "WireFrameFillMode", {
  24448. get: function () {
  24449. return Material._WireFrameFillMode;
  24450. },
  24451. enumerable: true,
  24452. configurable: true
  24453. });
  24454. Object.defineProperty(Material, "PointFillMode", {
  24455. get: function () {
  24456. return Material._PointFillMode;
  24457. },
  24458. enumerable: true,
  24459. configurable: true
  24460. });
  24461. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  24462. get: function () {
  24463. return Material._ClockWiseSideOrientation;
  24464. },
  24465. enumerable: true,
  24466. configurable: true
  24467. });
  24468. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  24469. get: function () {
  24470. return Material._CounterClockWiseSideOrientation;
  24471. },
  24472. enumerable: true,
  24473. configurable: true
  24474. });
  24475. Object.defineProperty(Material.prototype, "onDispose", {
  24476. set: function (callback) {
  24477. if (this._onDisposeObserver) {
  24478. this.onDisposeObservable.remove(this._onDisposeObserver);
  24479. }
  24480. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24481. },
  24482. enumerable: true,
  24483. configurable: true
  24484. });
  24485. Object.defineProperty(Material.prototype, "onBind", {
  24486. set: function (callback) {
  24487. if (this._onBindObserver) {
  24488. this.onBindObservable.remove(this._onBindObserver);
  24489. }
  24490. this._onBindObserver = this.onBindObservable.add(callback);
  24491. },
  24492. enumerable: true,
  24493. configurable: true
  24494. });
  24495. Object.defineProperty(Material.prototype, "wireframe", {
  24496. get: function () {
  24497. return this._fillMode === Material.WireFrameFillMode;
  24498. },
  24499. set: function (value) {
  24500. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  24501. },
  24502. enumerable: true,
  24503. configurable: true
  24504. });
  24505. Object.defineProperty(Material.prototype, "pointsCloud", {
  24506. get: function () {
  24507. return this._fillMode === Material.PointFillMode;
  24508. },
  24509. set: function (value) {
  24510. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  24511. },
  24512. enumerable: true,
  24513. configurable: true
  24514. });
  24515. Object.defineProperty(Material.prototype, "fillMode", {
  24516. get: function () {
  24517. return this._fillMode;
  24518. },
  24519. set: function (value) {
  24520. this._fillMode = value;
  24521. },
  24522. enumerable: true,
  24523. configurable: true
  24524. });
  24525. /**
  24526. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24527. * subclasses should override adding information pertainent to themselves
  24528. */
  24529. Material.prototype.toString = function (fullDetails) {
  24530. var ret = "Name: " + this.name;
  24531. if (fullDetails) {
  24532. }
  24533. return ret;
  24534. };
  24535. Object.defineProperty(Material.prototype, "isFrozen", {
  24536. get: function () {
  24537. return this.checkReadyOnlyOnce;
  24538. },
  24539. enumerable: true,
  24540. configurable: true
  24541. });
  24542. Material.prototype.freeze = function () {
  24543. this.checkReadyOnlyOnce = true;
  24544. };
  24545. Material.prototype.unfreeze = function () {
  24546. this.checkReadyOnlyOnce = false;
  24547. };
  24548. Material.prototype.isReady = function (mesh, useInstances) {
  24549. return true;
  24550. };
  24551. Material.prototype.getEffect = function () {
  24552. return this._effect;
  24553. };
  24554. Material.prototype.getScene = function () {
  24555. return this._scene;
  24556. };
  24557. Material.prototype.needAlphaBlending = function () {
  24558. return (this.alpha < 1.0);
  24559. };
  24560. Material.prototype.needAlphaTesting = function () {
  24561. return false;
  24562. };
  24563. Material.prototype.getAlphaTestTexture = function () {
  24564. return null;
  24565. };
  24566. Material.prototype.markDirty = function () {
  24567. this._wasPreviouslyReady = false;
  24568. };
  24569. Material.prototype._preBind = function () {
  24570. var engine = this._scene.getEngine();
  24571. engine.enableEffect(this._effect);
  24572. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  24573. };
  24574. Material.prototype.bind = function (world, mesh) {
  24575. this._scene._cachedMaterial = this;
  24576. this.onBindObservable.notifyObservers(mesh);
  24577. if (this.disableDepthWrite) {
  24578. var engine = this._scene.getEngine();
  24579. this._cachedDepthWriteState = engine.getDepthWrite();
  24580. engine.setDepthWrite(false);
  24581. }
  24582. };
  24583. Material.prototype.bindOnlyWorldMatrix = function (world) {
  24584. };
  24585. Material.prototype.unbind = function () {
  24586. this.onUnBindObservable.notifyObservers(this);
  24587. if (this.disableDepthWrite) {
  24588. var engine = this._scene.getEngine();
  24589. engine.setDepthWrite(this._cachedDepthWriteState);
  24590. }
  24591. };
  24592. Material.prototype.clone = function (name) {
  24593. return null;
  24594. };
  24595. Material.prototype.getBindedMeshes = function () {
  24596. var result = new Array();
  24597. for (var index = 0; index < this._scene.meshes.length; index++) {
  24598. var mesh = this._scene.meshes[index];
  24599. if (mesh.material === this) {
  24600. result.push(mesh);
  24601. }
  24602. }
  24603. return result;
  24604. };
  24605. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24606. // Animations
  24607. this.getScene().stopAnimation(this);
  24608. // Remove from scene
  24609. var index = this._scene.materials.indexOf(this);
  24610. if (index >= 0) {
  24611. this._scene.materials.splice(index, 1);
  24612. }
  24613. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  24614. if (forceDisposeEffect && this._effect) {
  24615. this._scene.getEngine()._releaseEffect(this._effect);
  24616. this._effect = null;
  24617. }
  24618. // Remove from meshes
  24619. for (index = 0; index < this._scene.meshes.length; index++) {
  24620. var mesh = this._scene.meshes[index];
  24621. if (mesh.material === this) {
  24622. mesh.material = null;
  24623. }
  24624. }
  24625. // Callback
  24626. this.onDisposeObservable.notifyObservers(this);
  24627. this.onDisposeObservable.clear();
  24628. this.onBindObservable.clear();
  24629. };
  24630. Material.prototype.serialize = function () {
  24631. return BABYLON.SerializationHelper.Serialize(this);
  24632. };
  24633. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  24634. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  24635. multiMaterial.id = parsedMultiMaterial.id;
  24636. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  24637. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  24638. var subMatId = parsedMultiMaterial.materials[matIndex];
  24639. if (subMatId) {
  24640. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  24641. }
  24642. else {
  24643. multiMaterial.subMaterials.push(null);
  24644. }
  24645. }
  24646. return multiMaterial;
  24647. };
  24648. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  24649. if (!parsedMaterial.customType) {
  24650. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  24651. }
  24652. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  24653. return materialType.Parse(parsedMaterial, scene, rootUrl);
  24654. ;
  24655. };
  24656. Material._TriangleFillMode = 0;
  24657. Material._WireFrameFillMode = 1;
  24658. Material._PointFillMode = 2;
  24659. Material._ClockWiseSideOrientation = 0;
  24660. Material._CounterClockWiseSideOrientation = 1;
  24661. __decorate([
  24662. BABYLON.serialize()
  24663. ], Material.prototype, "id", void 0);
  24664. __decorate([
  24665. BABYLON.serialize()
  24666. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  24667. __decorate([
  24668. BABYLON.serialize()
  24669. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  24670. __decorate([
  24671. BABYLON.serialize()
  24672. ], Material.prototype, "state", void 0);
  24673. __decorate([
  24674. BABYLON.serialize()
  24675. ], Material.prototype, "alpha", void 0);
  24676. __decorate([
  24677. BABYLON.serialize()
  24678. ], Material.prototype, "backFaceCulling", void 0);
  24679. __decorate([
  24680. BABYLON.serialize()
  24681. ], Material.prototype, "sideOrientation", void 0);
  24682. __decorate([
  24683. BABYLON.serialize()
  24684. ], Material.prototype, "alphaMode", void 0);
  24685. __decorate([
  24686. BABYLON.serialize()
  24687. ], Material.prototype, "disableDepthWrite", void 0);
  24688. __decorate([
  24689. BABYLON.serialize()
  24690. ], Material.prototype, "fogEnabled", void 0);
  24691. __decorate([
  24692. BABYLON.serialize()
  24693. ], Material.prototype, "pointSize", void 0);
  24694. __decorate([
  24695. BABYLON.serialize()
  24696. ], Material.prototype, "zOffset", void 0);
  24697. __decorate([
  24698. BABYLON.serialize()
  24699. ], Material.prototype, "wireframe", null);
  24700. __decorate([
  24701. BABYLON.serialize()
  24702. ], Material.prototype, "pointsCloud", null);
  24703. __decorate([
  24704. BABYLON.serialize()
  24705. ], Material.prototype, "fillMode", null);
  24706. return Material;
  24707. })();
  24708. BABYLON.Material = Material;
  24709. })(BABYLON || (BABYLON = {}));
  24710. var BABYLON;
  24711. (function (BABYLON) {
  24712. var StandardMaterialDefines = (function (_super) {
  24713. __extends(StandardMaterialDefines, _super);
  24714. function StandardMaterialDefines() {
  24715. _super.call(this);
  24716. this.DIFFUSE = false;
  24717. this.AMBIENT = false;
  24718. this.OPACITY = false;
  24719. this.OPACITYRGB = false;
  24720. this.REFLECTION = false;
  24721. this.EMISSIVE = false;
  24722. this.SPECULAR = false;
  24723. this.BUMP = false;
  24724. this.PARALLAX = false;
  24725. this.PARALLAXOCCLUSION = false;
  24726. this.SPECULAROVERALPHA = false;
  24727. this.CLIPPLANE = false;
  24728. this.ALPHATEST = false;
  24729. this.ALPHAFROMDIFFUSE = false;
  24730. this.POINTSIZE = false;
  24731. this.FOG = false;
  24732. this.SPECULARTERM = false;
  24733. this.DIFFUSEFRESNEL = false;
  24734. this.OPACITYFRESNEL = false;
  24735. this.REFLECTIONFRESNEL = false;
  24736. this.REFRACTIONFRESNEL = false;
  24737. this.EMISSIVEFRESNEL = false;
  24738. this.FRESNEL = false;
  24739. this.NORMAL = false;
  24740. this.UV1 = false;
  24741. this.UV2 = false;
  24742. this.VERTEXCOLOR = false;
  24743. this.VERTEXALPHA = false;
  24744. this.NUM_BONE_INFLUENCERS = 0;
  24745. this.BonesPerMesh = 0;
  24746. this.INSTANCES = false;
  24747. this.GLOSSINESS = false;
  24748. this.ROUGHNESS = false;
  24749. this.EMISSIVEASILLUMINATION = false;
  24750. this.LINKEMISSIVEWITHDIFFUSE = false;
  24751. this.REFLECTIONFRESNELFROMSPECULAR = false;
  24752. this.LIGHTMAP = false;
  24753. this.USELIGHTMAPASSHADOWMAP = false;
  24754. this.REFLECTIONMAP_3D = false;
  24755. this.REFLECTIONMAP_SPHERICAL = false;
  24756. this.REFLECTIONMAP_PLANAR = false;
  24757. this.REFLECTIONMAP_CUBIC = false;
  24758. this.REFLECTIONMAP_PROJECTION = false;
  24759. this.REFLECTIONMAP_SKYBOX = false;
  24760. this.REFLECTIONMAP_EXPLICIT = false;
  24761. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  24762. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  24763. this.INVERTCUBICMAP = false;
  24764. this.LOGARITHMICDEPTH = false;
  24765. this.REFRACTION = false;
  24766. this.REFRACTIONMAP_3D = false;
  24767. this.REFLECTIONOVERALPHA = false;
  24768. this.INVERTNORMALMAPX = false;
  24769. this.INVERTNORMALMAPY = false;
  24770. this.SHADOWFULLFLOAT = false;
  24771. this.CAMERACOLORGRADING = false;
  24772. this.CAMERACOLORCURVES = false;
  24773. this.rebuild();
  24774. }
  24775. return StandardMaterialDefines;
  24776. })(BABYLON.MaterialDefines);
  24777. var StandardMaterial = (function (_super) {
  24778. __extends(StandardMaterial, _super);
  24779. function StandardMaterial(name, scene) {
  24780. var _this = this;
  24781. _super.call(this, name, scene);
  24782. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24783. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  24784. this.specularColor = new BABYLON.Color3(1, 1, 1);
  24785. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  24786. this.specularPower = 64;
  24787. this.useAlphaFromDiffuseTexture = false;
  24788. this.useEmissiveAsIllumination = false;
  24789. this.linkEmissiveWithDiffuse = false;
  24790. this.useReflectionFresnelFromSpecular = false;
  24791. this.useSpecularOverAlpha = false;
  24792. this.useReflectionOverAlpha = false;
  24793. this.disableLighting = false;
  24794. this.useParallax = false;
  24795. this.useParallaxOcclusion = false;
  24796. this.parallaxScaleBias = 0.05;
  24797. this.roughness = 0;
  24798. this.indexOfRefraction = 0.98;
  24799. this.invertRefractionY = true;
  24800. this.useLightmapAsShadowmap = false;
  24801. this.useGlossinessFromSpecularMapAlpha = false;
  24802. this.maxSimultaneousLights = 4;
  24803. /**
  24804. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  24805. */
  24806. this.invertNormalMapX = false;
  24807. /**
  24808. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  24809. */
  24810. this.invertNormalMapY = false;
  24811. /**
  24812. * Color Grading 2D Lookup Texture.
  24813. * This allows special effects like sepia, black and white to sixties rendering style.
  24814. */
  24815. this.cameraColorGradingTexture = null;
  24816. /**
  24817. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  24818. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  24819. * 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;
  24820. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  24821. */
  24822. this.cameraColorCurves = null;
  24823. this._renderTargets = new BABYLON.SmartArray(16);
  24824. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  24825. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  24826. this._defines = new StandardMaterialDefines();
  24827. this._cachedDefines = new StandardMaterialDefines();
  24828. this._cachedDefines.BonesPerMesh = -1;
  24829. this.getRenderTargetTextures = function () {
  24830. _this._renderTargets.reset();
  24831. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  24832. _this._renderTargets.push(_this.reflectionTexture);
  24833. }
  24834. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  24835. _this._renderTargets.push(_this.refractionTexture);
  24836. }
  24837. return _this._renderTargets;
  24838. };
  24839. }
  24840. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  24841. get: function () {
  24842. return this._useLogarithmicDepth;
  24843. },
  24844. set: function (value) {
  24845. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  24846. },
  24847. enumerable: true,
  24848. configurable: true
  24849. });
  24850. StandardMaterial.prototype.needAlphaBlending = function () {
  24851. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  24852. };
  24853. StandardMaterial.prototype.needAlphaTesting = function () {
  24854. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  24855. };
  24856. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  24857. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  24858. };
  24859. StandardMaterial.prototype.getAlphaTestTexture = function () {
  24860. return this.diffuseTexture;
  24861. };
  24862. // Methods
  24863. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  24864. if (!mesh) {
  24865. return true;
  24866. }
  24867. if (this._defines.INSTANCES !== useInstances) {
  24868. return false;
  24869. }
  24870. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  24871. return true;
  24872. }
  24873. return false;
  24874. };
  24875. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  24876. if (this.isFrozen) {
  24877. if (this._wasPreviouslyReady) {
  24878. return true;
  24879. }
  24880. }
  24881. var scene = this.getScene();
  24882. if (!this.checkReadyOnEveryCall) {
  24883. if (this._renderId === scene.getRenderId()) {
  24884. if (this._checkCache(scene, mesh, useInstances)) {
  24885. return true;
  24886. }
  24887. }
  24888. }
  24889. var engine = scene.getEngine();
  24890. var needNormals = false;
  24891. var needUVs = false;
  24892. this._defines.reset();
  24893. // Textures
  24894. if (scene.texturesEnabled) {
  24895. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  24896. if (!this.diffuseTexture.isReady()) {
  24897. return false;
  24898. }
  24899. else {
  24900. needUVs = true;
  24901. this._defines.DIFFUSE = true;
  24902. }
  24903. }
  24904. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  24905. if (!this.ambientTexture.isReady()) {
  24906. return false;
  24907. }
  24908. else {
  24909. needUVs = true;
  24910. this._defines.AMBIENT = true;
  24911. }
  24912. }
  24913. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  24914. if (!this.opacityTexture.isReady()) {
  24915. return false;
  24916. }
  24917. else {
  24918. needUVs = true;
  24919. this._defines.OPACITY = true;
  24920. if (this.opacityTexture.getAlphaFromRGB) {
  24921. this._defines.OPACITYRGB = true;
  24922. }
  24923. }
  24924. }
  24925. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  24926. if (!this.reflectionTexture.isReady()) {
  24927. return false;
  24928. }
  24929. else {
  24930. needNormals = true;
  24931. this._defines.REFLECTION = true;
  24932. if (this.roughness > 0) {
  24933. this._defines.ROUGHNESS = true;
  24934. }
  24935. if (this.useReflectionOverAlpha) {
  24936. this._defines.REFLECTIONOVERALPHA = true;
  24937. }
  24938. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  24939. this._defines.INVERTCUBICMAP = true;
  24940. }
  24941. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  24942. switch (this.reflectionTexture.coordinatesMode) {
  24943. case BABYLON.Texture.CUBIC_MODE:
  24944. case BABYLON.Texture.INVCUBIC_MODE:
  24945. this._defines.REFLECTIONMAP_CUBIC = true;
  24946. break;
  24947. case BABYLON.Texture.EXPLICIT_MODE:
  24948. this._defines.REFLECTIONMAP_EXPLICIT = true;
  24949. break;
  24950. case BABYLON.Texture.PLANAR_MODE:
  24951. this._defines.REFLECTIONMAP_PLANAR = true;
  24952. break;
  24953. case BABYLON.Texture.PROJECTION_MODE:
  24954. this._defines.REFLECTIONMAP_PROJECTION = true;
  24955. break;
  24956. case BABYLON.Texture.SKYBOX_MODE:
  24957. this._defines.REFLECTIONMAP_SKYBOX = true;
  24958. break;
  24959. case BABYLON.Texture.SPHERICAL_MODE:
  24960. this._defines.REFLECTIONMAP_SPHERICAL = true;
  24961. break;
  24962. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  24963. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  24964. break;
  24965. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  24966. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  24967. break;
  24968. }
  24969. }
  24970. }
  24971. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  24972. if (!this.emissiveTexture.isReady()) {
  24973. return false;
  24974. }
  24975. else {
  24976. needUVs = true;
  24977. this._defines.EMISSIVE = true;
  24978. }
  24979. }
  24980. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  24981. if (!this.lightmapTexture.isReady()) {
  24982. return false;
  24983. }
  24984. else {
  24985. needUVs = true;
  24986. this._defines.LIGHTMAP = true;
  24987. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  24988. }
  24989. }
  24990. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  24991. if (!this.specularTexture.isReady()) {
  24992. return false;
  24993. }
  24994. else {
  24995. needUVs = true;
  24996. this._defines.SPECULAR = true;
  24997. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  24998. }
  24999. }
  25000. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  25001. if (!this.bumpTexture.isReady()) {
  25002. return false;
  25003. }
  25004. else {
  25005. needUVs = true;
  25006. this._defines.BUMP = true;
  25007. if (this.useParallax) {
  25008. this._defines.PARALLAX = true;
  25009. if (this.useParallaxOcclusion) {
  25010. this._defines.PARALLAXOCCLUSION = true;
  25011. }
  25012. }
  25013. if (this.invertNormalMapX) {
  25014. this._defines.INVERTNORMALMAPX = true;
  25015. }
  25016. if (this.invertNormalMapY) {
  25017. this._defines.INVERTNORMALMAPY = true;
  25018. }
  25019. }
  25020. }
  25021. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  25022. if (!this.refractionTexture.isReady()) {
  25023. return false;
  25024. }
  25025. else {
  25026. needUVs = true;
  25027. this._defines.REFRACTION = true;
  25028. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  25029. }
  25030. }
  25031. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  25032. if (!this.cameraColorGradingTexture.isReady()) {
  25033. return false;
  25034. }
  25035. else {
  25036. this._defines.CAMERACOLORGRADING = true;
  25037. }
  25038. }
  25039. }
  25040. // Effect
  25041. if (scene.clipPlane) {
  25042. this._defines.CLIPPLANE = true;
  25043. }
  25044. if (engine.getAlphaTesting()) {
  25045. this._defines.ALPHATEST = true;
  25046. }
  25047. if (this._shouldUseAlphaFromDiffuseTexture()) {
  25048. this._defines.ALPHAFROMDIFFUSE = true;
  25049. }
  25050. if (this.useEmissiveAsIllumination) {
  25051. this._defines.EMISSIVEASILLUMINATION = true;
  25052. }
  25053. if (this.linkEmissiveWithDiffuse) {
  25054. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  25055. }
  25056. if (this.useLogarithmicDepth) {
  25057. this._defines.LOGARITHMICDEPTH = true;
  25058. }
  25059. if (this.cameraColorCurves) {
  25060. this._defines.CAMERACOLORCURVES = true;
  25061. }
  25062. // Point size
  25063. if (this.pointsCloud || scene.forcePointsCloud) {
  25064. this._defines.POINTSIZE = true;
  25065. }
  25066. // Fog
  25067. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25068. this._defines.FOG = true;
  25069. }
  25070. if (scene.lightsEnabled && !this.disableLighting) {
  25071. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  25072. }
  25073. if (StandardMaterial.FresnelEnabled) {
  25074. // Fresnel
  25075. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  25076. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  25077. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  25078. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  25079. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25080. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  25081. this._defines.DIFFUSEFRESNEL = true;
  25082. }
  25083. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  25084. this._defines.OPACITYFRESNEL = true;
  25085. }
  25086. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25087. this._defines.REFLECTIONFRESNEL = true;
  25088. if (this.useReflectionFresnelFromSpecular) {
  25089. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  25090. }
  25091. }
  25092. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  25093. this._defines.REFRACTIONFRESNEL = true;
  25094. }
  25095. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  25096. this._defines.EMISSIVEFRESNEL = true;
  25097. }
  25098. needNormals = true;
  25099. this._defines.FRESNEL = true;
  25100. }
  25101. }
  25102. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  25103. this._defines.SPECULAROVERALPHA = true;
  25104. }
  25105. // Attribs
  25106. if (mesh) {
  25107. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25108. this._defines.NORMAL = true;
  25109. }
  25110. if (needUVs) {
  25111. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25112. this._defines.UV1 = true;
  25113. }
  25114. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25115. this._defines.UV2 = true;
  25116. }
  25117. }
  25118. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25119. this._defines.VERTEXCOLOR = true;
  25120. if (mesh.hasVertexAlpha) {
  25121. this._defines.VERTEXALPHA = true;
  25122. }
  25123. }
  25124. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  25125. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  25126. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  25127. }
  25128. // Instances
  25129. if (useInstances) {
  25130. this._defines.INSTANCES = true;
  25131. }
  25132. }
  25133. // Get correct effect
  25134. if (!this._defines.isEqual(this._cachedDefines)) {
  25135. this._defines.cloneTo(this._cachedDefines);
  25136. scene.resetCachedMaterial();
  25137. // Fallbacks
  25138. var fallbacks = new BABYLON.EffectFallbacks();
  25139. if (this._defines.REFLECTION) {
  25140. fallbacks.addFallback(0, "REFLECTION");
  25141. }
  25142. if (this._defines.SPECULAR) {
  25143. fallbacks.addFallback(0, "SPECULAR");
  25144. }
  25145. if (this._defines.BUMP) {
  25146. fallbacks.addFallback(0, "BUMP");
  25147. }
  25148. if (this._defines.PARALLAX) {
  25149. fallbacks.addFallback(1, "PARALLAX");
  25150. }
  25151. if (this._defines.PARALLAXOCCLUSION) {
  25152. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  25153. }
  25154. if (this._defines.SPECULAROVERALPHA) {
  25155. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  25156. }
  25157. if (this._defines.FOG) {
  25158. fallbacks.addFallback(1, "FOG");
  25159. }
  25160. if (this._defines.POINTSIZE) {
  25161. fallbacks.addFallback(0, "POINTSIZE");
  25162. }
  25163. if (this._defines.LOGARITHMICDEPTH) {
  25164. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  25165. }
  25166. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  25167. if (this._defines.SPECULARTERM) {
  25168. fallbacks.addFallback(0, "SPECULARTERM");
  25169. }
  25170. if (this._defines.DIFFUSEFRESNEL) {
  25171. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  25172. }
  25173. if (this._defines.OPACITYFRESNEL) {
  25174. fallbacks.addFallback(2, "OPACITYFRESNEL");
  25175. }
  25176. if (this._defines.REFLECTIONFRESNEL) {
  25177. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  25178. }
  25179. if (this._defines.EMISSIVEFRESNEL) {
  25180. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  25181. }
  25182. if (this._defines.FRESNEL) {
  25183. fallbacks.addFallback(4, "FRESNEL");
  25184. }
  25185. //Attributes
  25186. var attribs = [BABYLON.VertexBuffer.PositionKind];
  25187. if (this._defines.NORMAL) {
  25188. attribs.push(BABYLON.VertexBuffer.NormalKind);
  25189. }
  25190. if (this._defines.UV1) {
  25191. attribs.push(BABYLON.VertexBuffer.UVKind);
  25192. }
  25193. if (this._defines.UV2) {
  25194. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  25195. }
  25196. if (this._defines.VERTEXCOLOR) {
  25197. attribs.push(BABYLON.VertexBuffer.ColorKind);
  25198. }
  25199. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  25200. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  25201. var shaderName = "default";
  25202. var join = this._defines.toString();
  25203. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  25204. "vFogInfos", "vFogColor", "pointSize",
  25205. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  25206. "mBones",
  25207. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  25208. "depthValues",
  25209. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  25210. "logarithmicDepthConstant"
  25211. ];
  25212. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  25213. if (this._defines.CAMERACOLORCURVES) {
  25214. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  25215. }
  25216. if (this._defines.CAMERACOLORGRADING) {
  25217. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  25218. }
  25219. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  25220. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  25221. }
  25222. if (!this._effect.isReady()) {
  25223. return false;
  25224. }
  25225. this._renderId = scene.getRenderId();
  25226. this._wasPreviouslyReady = true;
  25227. if (mesh) {
  25228. if (!mesh._materialDefines) {
  25229. mesh._materialDefines = new StandardMaterialDefines();
  25230. }
  25231. this._defines.cloneTo(mesh._materialDefines);
  25232. }
  25233. return true;
  25234. };
  25235. StandardMaterial.prototype.unbind = function () {
  25236. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  25237. this._effect.setTexture("reflection2DSampler", null);
  25238. }
  25239. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  25240. this._effect.setTexture("refraction2DSampler", null);
  25241. }
  25242. _super.prototype.unbind.call(this);
  25243. };
  25244. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25245. this._effect.setMatrix("world", world);
  25246. };
  25247. StandardMaterial.prototype.bind = function (world, mesh) {
  25248. var scene = this.getScene();
  25249. // Matrices
  25250. this.bindOnlyWorldMatrix(world);
  25251. // Bones
  25252. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  25253. if (scene.getCachedMaterial() !== this) {
  25254. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  25255. if (StandardMaterial.FresnelEnabled) {
  25256. // Fresnel
  25257. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  25258. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  25259. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  25260. }
  25261. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  25262. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  25263. }
  25264. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25265. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  25266. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  25267. }
  25268. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  25269. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  25270. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  25271. }
  25272. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  25273. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  25274. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  25275. }
  25276. }
  25277. // Textures
  25278. if (scene.texturesEnabled) {
  25279. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  25280. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  25281. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  25282. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  25283. }
  25284. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  25285. this._effect.setTexture("ambientSampler", this.ambientTexture);
  25286. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  25287. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  25288. }
  25289. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  25290. this._effect.setTexture("opacitySampler", this.opacityTexture);
  25291. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  25292. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  25293. }
  25294. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  25295. if (this.reflectionTexture.isCube) {
  25296. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  25297. }
  25298. else {
  25299. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  25300. }
  25301. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  25302. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  25303. }
  25304. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  25305. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  25306. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  25307. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  25308. }
  25309. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  25310. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  25311. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  25312. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  25313. }
  25314. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  25315. this._effect.setTexture("specularSampler", this.specularTexture);
  25316. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  25317. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  25318. }
  25319. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  25320. this._effect.setTexture("bumpSampler", this.bumpTexture);
  25321. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  25322. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  25323. }
  25324. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  25325. var depth = 1.0;
  25326. if (this.refractionTexture.isCube) {
  25327. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  25328. }
  25329. else {
  25330. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  25331. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  25332. if (this.refractionTexture.depth) {
  25333. depth = this.refractionTexture.depth;
  25334. }
  25335. }
  25336. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  25337. }
  25338. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  25339. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  25340. }
  25341. }
  25342. // Clip plane
  25343. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  25344. // Point size
  25345. if (this.pointsCloud) {
  25346. this._effect.setFloat("pointSize", this.pointSize);
  25347. }
  25348. // Colors
  25349. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  25350. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  25351. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  25352. if (this._defines.SPECULARTERM) {
  25353. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  25354. }
  25355. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  25356. }
  25357. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  25358. // Diffuse
  25359. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  25360. // Lights
  25361. if (scene.lightsEnabled && !this.disableLighting) {
  25362. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  25363. }
  25364. // View
  25365. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  25366. this._effect.setMatrix("view", scene.getViewMatrix());
  25367. }
  25368. // Fog
  25369. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  25370. // Log. depth
  25371. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  25372. // Color Curves
  25373. if (this.cameraColorCurves) {
  25374. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  25375. }
  25376. }
  25377. _super.prototype.bind.call(this, world, mesh);
  25378. };
  25379. StandardMaterial.prototype.getAnimatables = function () {
  25380. var results = [];
  25381. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  25382. results.push(this.diffuseTexture);
  25383. }
  25384. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  25385. results.push(this.ambientTexture);
  25386. }
  25387. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  25388. results.push(this.opacityTexture);
  25389. }
  25390. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  25391. results.push(this.reflectionTexture);
  25392. }
  25393. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  25394. results.push(this.emissiveTexture);
  25395. }
  25396. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  25397. results.push(this.specularTexture);
  25398. }
  25399. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  25400. results.push(this.bumpTexture);
  25401. }
  25402. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  25403. results.push(this.lightmapTexture);
  25404. }
  25405. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  25406. results.push(this.refractionTexture);
  25407. }
  25408. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  25409. results.push(this.cameraColorGradingTexture);
  25410. }
  25411. return results;
  25412. };
  25413. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25414. if (forceDisposeTextures) {
  25415. if (this.diffuseTexture) {
  25416. this.diffuseTexture.dispose();
  25417. }
  25418. if (this.ambientTexture) {
  25419. this.ambientTexture.dispose();
  25420. }
  25421. if (this.opacityTexture) {
  25422. this.opacityTexture.dispose();
  25423. }
  25424. if (this.reflectionTexture) {
  25425. this.reflectionTexture.dispose();
  25426. }
  25427. if (this.emissiveTexture) {
  25428. this.emissiveTexture.dispose();
  25429. }
  25430. if (this.specularTexture) {
  25431. this.specularTexture.dispose();
  25432. }
  25433. if (this.bumpTexture) {
  25434. this.bumpTexture.dispose();
  25435. }
  25436. if (this.lightmapTexture) {
  25437. this.lightmapTexture.dispose();
  25438. }
  25439. if (this.refractionTexture) {
  25440. this.refractionTexture.dispose();
  25441. }
  25442. if (this.cameraColorGradingTexture) {
  25443. this.cameraColorGradingTexture.dispose();
  25444. }
  25445. }
  25446. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  25447. };
  25448. StandardMaterial.prototype.clone = function (name) {
  25449. var _this = this;
  25450. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  25451. };
  25452. StandardMaterial.prototype.serialize = function () {
  25453. return BABYLON.SerializationHelper.Serialize(this);
  25454. };
  25455. // Statics
  25456. StandardMaterial.Parse = function (source, scene, rootUrl) {
  25457. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  25458. };
  25459. // Flags used to enable or disable a type of texture for all Standard Materials
  25460. StandardMaterial.DiffuseTextureEnabled = true;
  25461. StandardMaterial.AmbientTextureEnabled = true;
  25462. StandardMaterial.OpacityTextureEnabled = true;
  25463. StandardMaterial.ReflectionTextureEnabled = true;
  25464. StandardMaterial.EmissiveTextureEnabled = true;
  25465. StandardMaterial.SpecularTextureEnabled = true;
  25466. StandardMaterial.BumpTextureEnabled = true;
  25467. StandardMaterial.FresnelEnabled = true;
  25468. StandardMaterial.LightmapTextureEnabled = true;
  25469. StandardMaterial.RefractionTextureEnabled = true;
  25470. StandardMaterial.ColorGradingTextureEnabled = true;
  25471. __decorate([
  25472. BABYLON.serializeAsTexture()
  25473. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  25474. __decorate([
  25475. BABYLON.serializeAsTexture()
  25476. ], StandardMaterial.prototype, "ambientTexture", void 0);
  25477. __decorate([
  25478. BABYLON.serializeAsTexture()
  25479. ], StandardMaterial.prototype, "opacityTexture", void 0);
  25480. __decorate([
  25481. BABYLON.serializeAsTexture()
  25482. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  25483. __decorate([
  25484. BABYLON.serializeAsTexture()
  25485. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  25486. __decorate([
  25487. BABYLON.serializeAsTexture()
  25488. ], StandardMaterial.prototype, "specularTexture", void 0);
  25489. __decorate([
  25490. BABYLON.serializeAsTexture()
  25491. ], StandardMaterial.prototype, "bumpTexture", void 0);
  25492. __decorate([
  25493. BABYLON.serializeAsTexture()
  25494. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  25495. __decorate([
  25496. BABYLON.serializeAsTexture()
  25497. ], StandardMaterial.prototype, "refractionTexture", void 0);
  25498. __decorate([
  25499. BABYLON.serializeAsColor3("ambient")
  25500. ], StandardMaterial.prototype, "ambientColor", void 0);
  25501. __decorate([
  25502. BABYLON.serializeAsColor3("diffuse")
  25503. ], StandardMaterial.prototype, "diffuseColor", void 0);
  25504. __decorate([
  25505. BABYLON.serializeAsColor3("specular")
  25506. ], StandardMaterial.prototype, "specularColor", void 0);
  25507. __decorate([
  25508. BABYLON.serializeAsColor3("emissive")
  25509. ], StandardMaterial.prototype, "emissiveColor", void 0);
  25510. __decorate([
  25511. BABYLON.serialize()
  25512. ], StandardMaterial.prototype, "specularPower", void 0);
  25513. __decorate([
  25514. BABYLON.serialize()
  25515. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  25516. __decorate([
  25517. BABYLON.serialize()
  25518. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  25519. __decorate([
  25520. BABYLON.serialize()
  25521. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  25522. __decorate([
  25523. BABYLON.serialize()
  25524. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  25525. __decorate([
  25526. BABYLON.serialize()
  25527. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  25528. __decorate([
  25529. BABYLON.serialize()
  25530. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  25531. __decorate([
  25532. BABYLON.serialize()
  25533. ], StandardMaterial.prototype, "disableLighting", void 0);
  25534. __decorate([
  25535. BABYLON.serialize()
  25536. ], StandardMaterial.prototype, "useParallax", void 0);
  25537. __decorate([
  25538. BABYLON.serialize()
  25539. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  25540. __decorate([
  25541. BABYLON.serialize()
  25542. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  25543. __decorate([
  25544. BABYLON.serialize()
  25545. ], StandardMaterial.prototype, "roughness", void 0);
  25546. __decorate([
  25547. BABYLON.serialize()
  25548. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  25549. __decorate([
  25550. BABYLON.serialize()
  25551. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  25552. __decorate([
  25553. BABYLON.serialize()
  25554. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  25555. __decorate([
  25556. BABYLON.serializeAsFresnelParameters()
  25557. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  25558. __decorate([
  25559. BABYLON.serializeAsFresnelParameters()
  25560. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  25561. __decorate([
  25562. BABYLON.serializeAsFresnelParameters()
  25563. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  25564. __decorate([
  25565. BABYLON.serializeAsFresnelParameters()
  25566. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  25567. __decorate([
  25568. BABYLON.serializeAsFresnelParameters()
  25569. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  25570. __decorate([
  25571. BABYLON.serialize()
  25572. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  25573. __decorate([
  25574. BABYLON.serialize()
  25575. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  25576. __decorate([
  25577. BABYLON.serialize()
  25578. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  25579. __decorate([
  25580. BABYLON.serialize()
  25581. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  25582. __decorate([
  25583. BABYLON.serializeAsTexture()
  25584. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  25585. __decorate([
  25586. BABYLON.serializeAsColorCurves()
  25587. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  25588. __decorate([
  25589. BABYLON.serialize()
  25590. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  25591. return StandardMaterial;
  25592. })(BABYLON.Material);
  25593. BABYLON.StandardMaterial = StandardMaterial;
  25594. })(BABYLON || (BABYLON = {}));
  25595. var BABYLON;
  25596. (function (BABYLON) {
  25597. var MultiMaterial = (function (_super) {
  25598. __extends(MultiMaterial, _super);
  25599. function MultiMaterial(name, scene) {
  25600. _super.call(this, name, scene, true);
  25601. this.subMaterials = new Array();
  25602. scene.multiMaterials.push(this);
  25603. }
  25604. // Properties
  25605. MultiMaterial.prototype.getSubMaterial = function (index) {
  25606. if (index < 0 || index >= this.subMaterials.length) {
  25607. return this.getScene().defaultMaterial;
  25608. }
  25609. return this.subMaterials[index];
  25610. };
  25611. // Methods
  25612. MultiMaterial.prototype.isReady = function (mesh) {
  25613. for (var index = 0; index < this.subMaterials.length; index++) {
  25614. var subMaterial = this.subMaterials[index];
  25615. if (subMaterial) {
  25616. if (!this.subMaterials[index].isReady(mesh)) {
  25617. return false;
  25618. }
  25619. }
  25620. }
  25621. return true;
  25622. };
  25623. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  25624. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  25625. for (var index = 0; index < this.subMaterials.length; index++) {
  25626. var subMaterial = null;
  25627. if (cloneChildren) {
  25628. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  25629. }
  25630. else {
  25631. subMaterial = this.subMaterials[index];
  25632. }
  25633. newMultiMaterial.subMaterials.push(subMaterial);
  25634. }
  25635. return newMultiMaterial;
  25636. };
  25637. MultiMaterial.prototype.serialize = function () {
  25638. var serializationObject = {};
  25639. serializationObject.name = this.name;
  25640. serializationObject.id = this.id;
  25641. serializationObject.tags = BABYLON.Tags.GetTags(this);
  25642. serializationObject.materials = [];
  25643. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  25644. var subMat = this.subMaterials[matIndex];
  25645. if (subMat) {
  25646. serializationObject.materials.push(subMat.id);
  25647. }
  25648. else {
  25649. serializationObject.materials.push(null);
  25650. }
  25651. }
  25652. return serializationObject;
  25653. };
  25654. return MultiMaterial;
  25655. })(BABYLON.Material);
  25656. BABYLON.MultiMaterial = MultiMaterial;
  25657. })(BABYLON || (BABYLON = {}));
  25658. var BABYLON;
  25659. (function (BABYLON) {
  25660. var SceneLoader = (function () {
  25661. function SceneLoader() {
  25662. }
  25663. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  25664. get: function () {
  25665. return 0;
  25666. },
  25667. enumerable: true,
  25668. configurable: true
  25669. });
  25670. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  25671. get: function () {
  25672. return 1;
  25673. },
  25674. enumerable: true,
  25675. configurable: true
  25676. });
  25677. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  25678. get: function () {
  25679. return 2;
  25680. },
  25681. enumerable: true,
  25682. configurable: true
  25683. });
  25684. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  25685. get: function () {
  25686. return 3;
  25687. },
  25688. enumerable: true,
  25689. configurable: true
  25690. });
  25691. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  25692. get: function () {
  25693. return SceneLoader._ForceFullSceneLoadingForIncremental;
  25694. },
  25695. set: function (value) {
  25696. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  25697. },
  25698. enumerable: true,
  25699. configurable: true
  25700. });
  25701. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  25702. get: function () {
  25703. return SceneLoader._ShowLoadingScreen;
  25704. },
  25705. set: function (value) {
  25706. SceneLoader._ShowLoadingScreen = value;
  25707. },
  25708. enumerable: true,
  25709. configurable: true
  25710. });
  25711. Object.defineProperty(SceneLoader, "loggingLevel", {
  25712. get: function () {
  25713. return SceneLoader._loggingLevel;
  25714. },
  25715. set: function (value) {
  25716. SceneLoader._loggingLevel = value;
  25717. },
  25718. enumerable: true,
  25719. configurable: true
  25720. });
  25721. SceneLoader._getPluginForFilename = function (sceneFilename) {
  25722. var dotPosition = sceneFilename.lastIndexOf(".");
  25723. var queryStringPosition = sceneFilename.indexOf("?");
  25724. if (queryStringPosition === -1) {
  25725. queryStringPosition = sceneFilename.length;
  25726. }
  25727. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  25728. for (var index = 0; index < this._registeredPlugins.length; index++) {
  25729. var plugin = this._registeredPlugins[index];
  25730. if (plugin.extensions.indexOf(extension) !== -1) {
  25731. return plugin;
  25732. }
  25733. }
  25734. return this._registeredPlugins[0];
  25735. };
  25736. // Public functions
  25737. SceneLoader.GetPluginForExtension = function (extension) {
  25738. for (var index = 0; index < this._registeredPlugins.length; index++) {
  25739. var plugin = this._registeredPlugins[index];
  25740. if (plugin.extensions.indexOf(extension) !== -1) {
  25741. return plugin;
  25742. }
  25743. }
  25744. return null;
  25745. };
  25746. SceneLoader.RegisterPlugin = function (plugin) {
  25747. plugin.extensions = plugin.extensions.toLowerCase();
  25748. SceneLoader._registeredPlugins.push(plugin);
  25749. };
  25750. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  25751. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25752. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25753. return;
  25754. }
  25755. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25756. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25757. return;
  25758. }
  25759. var loadingToken = {};
  25760. scene._addPendingData(loadingToken);
  25761. var manifestChecked = function (success) {
  25762. scene.database = database;
  25763. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  25764. var importMeshFromData = function (data) {
  25765. var meshes = [];
  25766. var particleSystems = [];
  25767. var skeletons = [];
  25768. try {
  25769. if (plugin.importMesh) {
  25770. var syncedPlugin = plugin;
  25771. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  25772. if (onerror) {
  25773. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  25774. }
  25775. scene._removePendingData(loadingToken);
  25776. return;
  25777. }
  25778. if (onsuccess) {
  25779. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  25780. onsuccess(meshes, particleSystems, skeletons);
  25781. scene._removePendingData(loadingToken);
  25782. }
  25783. }
  25784. else {
  25785. var asyncedPlugin = plugin;
  25786. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  25787. if (onsuccess) {
  25788. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  25789. onsuccess(meshes, particleSystems, skeletons);
  25790. scene._removePendingData(loadingToken);
  25791. }
  25792. }, function () {
  25793. if (onerror) {
  25794. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  25795. }
  25796. scene._removePendingData(loadingToken);
  25797. });
  25798. }
  25799. }
  25800. catch (e) {
  25801. if (onerror) {
  25802. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  25803. }
  25804. scene._removePendingData(loadingToken);
  25805. }
  25806. };
  25807. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  25808. // Direct load
  25809. importMeshFromData(sceneFilename.substr(5));
  25810. return;
  25811. }
  25812. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  25813. importMeshFromData(data);
  25814. }, progressCallBack, database);
  25815. };
  25816. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  25817. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  25818. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  25819. }
  25820. else {
  25821. // If the scene is a data stream or offline support is not enabled, it's a direct load
  25822. manifestChecked(true);
  25823. }
  25824. };
  25825. /**
  25826. * Load a scene
  25827. * @param rootUrl a string that defines the root url for scene and resources
  25828. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  25829. * @param engine is the instance of BABYLON.Engine to use to create the scene
  25830. */
  25831. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  25832. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  25833. };
  25834. /**
  25835. * Append a scene
  25836. * @param rootUrl a string that defines the root url for scene and resources
  25837. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  25838. * @param scene is the instance of BABYLON.Scene to append to
  25839. */
  25840. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  25841. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25842. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25843. return;
  25844. }
  25845. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  25846. var database;
  25847. var loadingToken = {};
  25848. scene._addPendingData(loadingToken);
  25849. if (SceneLoader.ShowLoadingScreen) {
  25850. scene.getEngine().displayLoadingUI();
  25851. }
  25852. var loadSceneFromData = function (data) {
  25853. scene.database = database;
  25854. if (plugin.load) {
  25855. var syncedPlugin = plugin;
  25856. if (!syncedPlugin.load(scene, data, rootUrl)) {
  25857. if (onerror) {
  25858. onerror(scene);
  25859. }
  25860. scene._removePendingData(loadingToken);
  25861. scene.getEngine().hideLoadingUI();
  25862. return;
  25863. }
  25864. if (onsuccess) {
  25865. onsuccess(scene);
  25866. }
  25867. scene._removePendingData(loadingToken);
  25868. }
  25869. else {
  25870. var asyncedPlugin = plugin;
  25871. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  25872. if (onsuccess) {
  25873. onsuccess(scene);
  25874. }
  25875. }, function () {
  25876. if (onerror) {
  25877. onerror(scene);
  25878. }
  25879. scene._removePendingData(loadingToken);
  25880. scene.getEngine().hideLoadingUI();
  25881. });
  25882. }
  25883. if (SceneLoader.ShowLoadingScreen) {
  25884. scene.executeWhenReady(function () {
  25885. scene.getEngine().hideLoadingUI();
  25886. });
  25887. }
  25888. };
  25889. var manifestChecked = function (success) {
  25890. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  25891. };
  25892. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  25893. // Direct load
  25894. loadSceneFromData(sceneFilename.substr(5));
  25895. return;
  25896. }
  25897. if (rootUrl.indexOf("file:") === -1) {
  25898. if (scene.getEngine().enableOfflineSupport) {
  25899. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  25900. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  25901. }
  25902. else {
  25903. manifestChecked(true);
  25904. }
  25905. }
  25906. else {
  25907. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  25908. }
  25909. };
  25910. // Flags
  25911. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  25912. SceneLoader._ShowLoadingScreen = true;
  25913. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  25914. // Members
  25915. SceneLoader._registeredPlugins = new Array();
  25916. return SceneLoader;
  25917. })();
  25918. BABYLON.SceneLoader = SceneLoader;
  25919. ;
  25920. })(BABYLON || (BABYLON = {}));
  25921. var BABYLON;
  25922. (function (BABYLON) {
  25923. var Internals;
  25924. (function (Internals) {
  25925. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  25926. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  25927. var parsedMaterial = parsedData.materials[index];
  25928. if (parsedMaterial.id === id) {
  25929. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  25930. }
  25931. }
  25932. return null;
  25933. };
  25934. var isDescendantOf = function (mesh, names, hierarchyIds) {
  25935. names = (names instanceof Array) ? names : [names];
  25936. for (var i in names) {
  25937. if (mesh.name === names[i]) {
  25938. hierarchyIds.push(mesh.id);
  25939. return true;
  25940. }
  25941. }
  25942. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  25943. hierarchyIds.push(mesh.id);
  25944. return true;
  25945. }
  25946. return false;
  25947. };
  25948. var logOperation = function (operation, producer) {
  25949. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  25950. };
  25951. BABYLON.SceneLoader.RegisterPlugin({
  25952. extensions: ".babylon",
  25953. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  25954. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  25955. // when SceneLoader.debugLogging = true (default), or exception encountered.
  25956. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  25957. // and avoid problems with multiple concurrent .babylon loads.
  25958. var log = "importMesh has failed JSON parse";
  25959. try {
  25960. var parsedData = JSON.parse(data);
  25961. log = "";
  25962. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  25963. var loadedSkeletonsIds = [];
  25964. var loadedMaterialsIds = [];
  25965. var hierarchyIds = [];
  25966. var index;
  25967. var cache;
  25968. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  25969. var parsedMesh = parsedData.meshes[index];
  25970. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  25971. if (meshesNames instanceof Array) {
  25972. // Remove found mesh name from list.
  25973. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  25974. }
  25975. //Geometry?
  25976. if (parsedMesh.geometryId) {
  25977. //does the file contain geometries?
  25978. if (parsedData.geometries) {
  25979. //find the correct geometry and add it to the scene
  25980. var found = false;
  25981. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  25982. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  25983. return;
  25984. }
  25985. else {
  25986. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  25987. if (parsedGeometryData.id === parsedMesh.geometryId) {
  25988. switch (geometryType) {
  25989. case "boxes":
  25990. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  25991. break;
  25992. case "spheres":
  25993. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  25994. break;
  25995. case "cylinders":
  25996. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  25997. break;
  25998. case "toruses":
  25999. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  26000. break;
  26001. case "grounds":
  26002. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  26003. break;
  26004. case "planes":
  26005. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  26006. break;
  26007. case "torusKnots":
  26008. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  26009. break;
  26010. case "vertexData":
  26011. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  26012. break;
  26013. }
  26014. found = true;
  26015. }
  26016. });
  26017. }
  26018. });
  26019. if (!found) {
  26020. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  26021. }
  26022. }
  26023. }
  26024. // Material ?
  26025. if (parsedMesh.materialId) {
  26026. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  26027. if (!materialFound && parsedData.multiMaterials) {
  26028. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  26029. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  26030. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  26031. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  26032. var subMatId = parsedMultiMaterial.materials[matIndex];
  26033. loadedMaterialsIds.push(subMatId);
  26034. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  26035. log += "\n\tMaterial " + mat.toString(fullDetails);
  26036. }
  26037. loadedMaterialsIds.push(parsedMultiMaterial.id);
  26038. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  26039. materialFound = true;
  26040. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  26041. break;
  26042. }
  26043. }
  26044. }
  26045. if (!materialFound) {
  26046. loadedMaterialsIds.push(parsedMesh.materialId);
  26047. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  26048. if (!mat) {
  26049. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  26050. }
  26051. else {
  26052. log += "\n\tMaterial " + mat.toString(fullDetails);
  26053. }
  26054. }
  26055. }
  26056. // Skeleton ?
  26057. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  26058. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  26059. if (!skeletonAlreadyLoaded) {
  26060. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  26061. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  26062. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  26063. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  26064. skeletons.push(skeleton);
  26065. loadedSkeletonsIds.push(parsedSkeleton.id);
  26066. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  26067. }
  26068. }
  26069. }
  26070. }
  26071. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  26072. meshes.push(mesh);
  26073. log += "\n\tMesh " + mesh.toString(fullDetails);
  26074. }
  26075. }
  26076. // Connecting parents
  26077. var currentMesh;
  26078. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26079. currentMesh = scene.meshes[index];
  26080. if (currentMesh._waitingParentId) {
  26081. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  26082. currentMesh._waitingParentId = undefined;
  26083. }
  26084. }
  26085. // freeze and compute world matrix application
  26086. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26087. currentMesh = scene.meshes[index];
  26088. if (currentMesh._waitingFreezeWorldMatrix) {
  26089. currentMesh.freezeWorldMatrix();
  26090. currentMesh._waitingFreezeWorldMatrix = undefined;
  26091. }
  26092. else {
  26093. currentMesh.computeWorldMatrix(true);
  26094. }
  26095. }
  26096. // Particles
  26097. if (parsedData.particleSystems) {
  26098. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  26099. var parsedParticleSystem = parsedData.particleSystems[index];
  26100. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  26101. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  26102. }
  26103. }
  26104. }
  26105. return true;
  26106. }
  26107. catch (err) {
  26108. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
  26109. log = null;
  26110. throw err;
  26111. }
  26112. finally {
  26113. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  26114. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  26115. }
  26116. }
  26117. },
  26118. load: function (scene, data, rootUrl) {
  26119. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  26120. // when SceneLoader.debugLogging = true (default), or exception encountered.
  26121. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  26122. // and avoid problems with multiple concurrent .babylon loads.
  26123. var log = "importScene has failed JSON parse";
  26124. try {
  26125. var parsedData = JSON.parse(data);
  26126. log = "";
  26127. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  26128. // Scene
  26129. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  26130. scene.autoClear = parsedData.autoClear;
  26131. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  26132. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  26133. if (parsedData.gravity) {
  26134. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  26135. }
  26136. // Fog
  26137. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  26138. scene.fogMode = parsedData.fogMode;
  26139. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  26140. scene.fogStart = parsedData.fogStart;
  26141. scene.fogEnd = parsedData.fogEnd;
  26142. scene.fogDensity = parsedData.fogDensity;
  26143. log += "\tFog mode for scene: ";
  26144. switch (scene.fogMode) {
  26145. // getters not compiling, so using hardcoded
  26146. case 1:
  26147. log += "exp\n";
  26148. break;
  26149. case 2:
  26150. log += "exp2\n";
  26151. break;
  26152. case 3:
  26153. log += "linear\n";
  26154. break;
  26155. }
  26156. }
  26157. //Physics
  26158. if (parsedData.physicsEnabled) {
  26159. var physicsPlugin;
  26160. if (parsedData.physicsEngine === "cannon") {
  26161. physicsPlugin = new BABYLON.CannonJSPlugin();
  26162. }
  26163. else if (parsedData.physicsEngine === "oimo") {
  26164. physicsPlugin = new BABYLON.OimoJSPlugin();
  26165. }
  26166. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  26167. //else - default engine, which is currently oimo
  26168. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  26169. scene.enablePhysics(physicsGravity, physicsPlugin);
  26170. }
  26171. //collisions, if defined. otherwise, default is true
  26172. if (parsedData.collisionsEnabled != undefined) {
  26173. scene.collisionsEnabled = parsedData.collisionsEnabled;
  26174. }
  26175. scene.workerCollisions = !!parsedData.workerCollisions;
  26176. var index;
  26177. var cache;
  26178. // Lights
  26179. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  26180. var parsedLight = parsedData.lights[index];
  26181. var light = BABYLON.Light.Parse(parsedLight, scene);
  26182. log += (index === 0 ? "\n\tLights:" : "");
  26183. log += "\n\t\t" + light.toString(fullDetails);
  26184. }
  26185. // Animations
  26186. if (parsedData.animations) {
  26187. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  26188. var parsedAnimation = parsedData.animations[index];
  26189. var animation = BABYLON.Animation.Parse(parsedAnimation);
  26190. scene.animations.push(animation);
  26191. log += (index === 0 ? "\n\tAnimations:" : "");
  26192. log += "\n\t\t" + animation.toString(fullDetails);
  26193. }
  26194. }
  26195. if (parsedData.autoAnimate) {
  26196. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  26197. }
  26198. // Materials
  26199. if (parsedData.materials) {
  26200. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  26201. var parsedMaterial = parsedData.materials[index];
  26202. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  26203. log += (index === 0 ? "\n\tMaterials:" : "");
  26204. log += "\n\t\t" + mat.toString(fullDetails);
  26205. }
  26206. }
  26207. if (parsedData.multiMaterials) {
  26208. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  26209. var parsedMultiMaterial = parsedData.multiMaterials[index];
  26210. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  26211. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  26212. log += "\n\t\t" + mmat.toString(fullDetails);
  26213. }
  26214. }
  26215. // Skeletons
  26216. if (parsedData.skeletons) {
  26217. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  26218. var parsedSkeleton = parsedData.skeletons[index];
  26219. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  26220. log += (index === 0 ? "\n\tSkeletons:" : "");
  26221. log += "\n\t\t" + skeleton.toString(fullDetails);
  26222. }
  26223. }
  26224. // Geometries
  26225. var geometries = parsedData.geometries;
  26226. if (geometries) {
  26227. // Boxes
  26228. var boxes = geometries.boxes;
  26229. if (boxes) {
  26230. for (index = 0, cache = boxes.length; index < cache; index++) {
  26231. var parsedBox = boxes[index];
  26232. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  26233. }
  26234. }
  26235. // Spheres
  26236. var spheres = geometries.spheres;
  26237. if (spheres) {
  26238. for (index = 0, cache = spheres.length; index < cache; index++) {
  26239. var parsedSphere = spheres[index];
  26240. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  26241. }
  26242. }
  26243. // Cylinders
  26244. var cylinders = geometries.cylinders;
  26245. if (cylinders) {
  26246. for (index = 0, cache = cylinders.length; index < cache; index++) {
  26247. var parsedCylinder = cylinders[index];
  26248. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  26249. }
  26250. }
  26251. // Toruses
  26252. var toruses = geometries.toruses;
  26253. if (toruses) {
  26254. for (index = 0, cache = toruses.length; index < cache; index++) {
  26255. var parsedTorus = toruses[index];
  26256. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  26257. }
  26258. }
  26259. // Grounds
  26260. var grounds = geometries.grounds;
  26261. if (grounds) {
  26262. for (index = 0, cache = grounds.length; index < cache; index++) {
  26263. var parsedGround = grounds[index];
  26264. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  26265. }
  26266. }
  26267. // Planes
  26268. var planes = geometries.planes;
  26269. if (planes) {
  26270. for (index = 0, cache = planes.length; index < cache; index++) {
  26271. var parsedPlane = planes[index];
  26272. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  26273. }
  26274. }
  26275. // TorusKnots
  26276. var torusKnots = geometries.torusKnots;
  26277. if (torusKnots) {
  26278. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  26279. var parsedTorusKnot = torusKnots[index];
  26280. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  26281. }
  26282. }
  26283. // VertexData
  26284. var vertexData = geometries.vertexData;
  26285. if (vertexData) {
  26286. for (index = 0, cache = vertexData.length; index < cache; index++) {
  26287. var parsedVertexData = vertexData[index];
  26288. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  26289. }
  26290. }
  26291. }
  26292. // Meshes
  26293. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  26294. var parsedMesh = parsedData.meshes[index];
  26295. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  26296. log += (index === 0 ? "\n\tMeshes:" : "");
  26297. log += "\n\t\t" + mesh.toString(fullDetails);
  26298. }
  26299. // Cameras
  26300. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  26301. var parsedCamera = parsedData.cameras[index];
  26302. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  26303. log += (index === 0 ? "\n\tCameras:" : "");
  26304. log += "\n\t\t" + camera.toString(fullDetails);
  26305. }
  26306. if (parsedData.activeCameraID) {
  26307. scene.setActiveCameraByID(parsedData.activeCameraID);
  26308. }
  26309. // Browsing all the graph to connect the dots
  26310. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  26311. var camera = scene.cameras[index];
  26312. if (camera._waitingParentId) {
  26313. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  26314. camera._waitingParentId = undefined;
  26315. }
  26316. }
  26317. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  26318. var light = scene.lights[index];
  26319. if (light._waitingParentId) {
  26320. light.parent = scene.getLastEntryByID(light._waitingParentId);
  26321. light._waitingParentId = undefined;
  26322. }
  26323. }
  26324. // Sounds
  26325. var loadedSounds = [];
  26326. var loadedSound;
  26327. if (BABYLON.AudioEngine && parsedData.sounds) {
  26328. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  26329. var parsedSound = parsedData.sounds[index];
  26330. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26331. if (!parsedSound.url)
  26332. parsedSound.url = parsedSound.name;
  26333. if (!loadedSounds[parsedSound.url]) {
  26334. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  26335. loadedSounds[parsedSound.url] = loadedSound;
  26336. }
  26337. else {
  26338. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  26339. }
  26340. }
  26341. else {
  26342. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  26343. }
  26344. }
  26345. }
  26346. loadedSounds = [];
  26347. // Connect parents & children and parse actions
  26348. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26349. var mesh = scene.meshes[index];
  26350. if (mesh._waitingParentId) {
  26351. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  26352. mesh._waitingParentId = undefined;
  26353. }
  26354. if (mesh._waitingActions) {
  26355. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  26356. mesh._waitingActions = undefined;
  26357. }
  26358. }
  26359. // freeze world matrix application
  26360. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26361. var currentMesh = scene.meshes[index];
  26362. if (currentMesh._waitingFreezeWorldMatrix) {
  26363. currentMesh.freezeWorldMatrix();
  26364. currentMesh._waitingFreezeWorldMatrix = undefined;
  26365. }
  26366. else {
  26367. currentMesh.computeWorldMatrix(true);
  26368. }
  26369. }
  26370. // Particles Systems
  26371. if (parsedData.particleSystems) {
  26372. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  26373. var parsedParticleSystem = parsedData.particleSystems[index];
  26374. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  26375. }
  26376. }
  26377. // Lens flares
  26378. if (parsedData.lensFlareSystems) {
  26379. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  26380. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  26381. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  26382. }
  26383. }
  26384. // Shadows
  26385. if (parsedData.shadowGenerators) {
  26386. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  26387. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  26388. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  26389. }
  26390. }
  26391. // Actions (scene)
  26392. if (parsedData.actions) {
  26393. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  26394. }
  26395. // Finish
  26396. return true;
  26397. }
  26398. catch (err) {
  26399. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
  26400. log = null;
  26401. throw err;
  26402. }
  26403. finally {
  26404. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  26405. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  26406. }
  26407. }
  26408. }
  26409. });
  26410. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26411. })(BABYLON || (BABYLON = {}));
  26412. var BABYLON;
  26413. (function (BABYLON) {
  26414. var SpriteManager = (function () {
  26415. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  26416. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26417. this.name = name;
  26418. this.sprites = new Array();
  26419. this.renderingGroupId = 0;
  26420. this.layerMask = 0x0FFFFFFF;
  26421. this.fogEnabled = true;
  26422. this.isPickable = false;
  26423. /**
  26424. * An event triggered when the manager is disposed.
  26425. * @type {BABYLON.Observable}
  26426. */
  26427. this.onDisposeObservable = new BABYLON.Observable();
  26428. this._vertexBuffers = {};
  26429. this._capacity = capacity;
  26430. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  26431. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26432. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26433. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  26434. if (cellSize.width) {
  26435. this.cellWidth = cellSize.width;
  26436. this.cellHeight = cellSize.height;
  26437. }
  26438. else {
  26439. this.cellWidth = cellSize;
  26440. this.cellHeight = cellSize;
  26441. }
  26442. this._scene = scene;
  26443. this._scene.spriteManagers.push(this);
  26444. var indices = [];
  26445. var index = 0;
  26446. for (var count = 0; count < capacity; count++) {
  26447. indices.push(index);
  26448. indices.push(index + 1);
  26449. indices.push(index + 2);
  26450. indices.push(index);
  26451. indices.push(index + 2);
  26452. indices.push(index + 3);
  26453. index += 4;
  26454. }
  26455. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  26456. // VBO
  26457. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  26458. this._vertexData = new Float32Array(capacity * 16 * 4);
  26459. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  26460. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  26461. var options = this._buffer.createVertexBuffer("options", 4, 4);
  26462. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  26463. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  26464. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  26465. this._vertexBuffers["options"] = options;
  26466. this._vertexBuffers["cellInfo"] = cellInfo;
  26467. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  26468. // Effects
  26469. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  26470. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  26471. }
  26472. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  26473. set: function (callback) {
  26474. if (this._onDisposeObserver) {
  26475. this.onDisposeObservable.remove(this._onDisposeObserver);
  26476. }
  26477. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26478. },
  26479. enumerable: true,
  26480. configurable: true
  26481. });
  26482. Object.defineProperty(SpriteManager.prototype, "texture", {
  26483. get: function () {
  26484. return this._spriteTexture;
  26485. },
  26486. set: function (value) {
  26487. this._spriteTexture = value;
  26488. },
  26489. enumerable: true,
  26490. configurable: true
  26491. });
  26492. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  26493. var arrayOffset = index * 16;
  26494. if (offsetX === 0)
  26495. offsetX = this._epsilon;
  26496. else if (offsetX === 1)
  26497. offsetX = 1 - this._epsilon;
  26498. if (offsetY === 0)
  26499. offsetY = this._epsilon;
  26500. else if (offsetY === 1)
  26501. offsetY = 1 - this._epsilon;
  26502. this._vertexData[arrayOffset] = sprite.position.x;
  26503. this._vertexData[arrayOffset + 1] = sprite.position.y;
  26504. this._vertexData[arrayOffset + 2] = sprite.position.z;
  26505. this._vertexData[arrayOffset + 3] = sprite.angle;
  26506. this._vertexData[arrayOffset + 4] = sprite.width;
  26507. this._vertexData[arrayOffset + 5] = sprite.height;
  26508. this._vertexData[arrayOffset + 6] = offsetX;
  26509. this._vertexData[arrayOffset + 7] = offsetY;
  26510. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  26511. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  26512. var offset = (sprite.cellIndex / rowSize) >> 0;
  26513. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  26514. this._vertexData[arrayOffset + 11] = offset;
  26515. // Color
  26516. this._vertexData[arrayOffset + 12] = sprite.color.r;
  26517. this._vertexData[arrayOffset + 13] = sprite.color.g;
  26518. this._vertexData[arrayOffset + 14] = sprite.color.b;
  26519. this._vertexData[arrayOffset + 15] = sprite.color.a;
  26520. };
  26521. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  26522. var count = Math.min(this._capacity, this.sprites.length);
  26523. var min = BABYLON.Vector3.Zero();
  26524. var max = BABYLON.Vector3.Zero();
  26525. var distance = Number.MAX_VALUE;
  26526. var currentSprite;
  26527. var cameraSpacePosition = BABYLON.Vector3.Zero();
  26528. var cameraView = camera.getViewMatrix();
  26529. for (var index = 0; index < count; index++) {
  26530. var sprite = this.sprites[index];
  26531. if (!sprite) {
  26532. continue;
  26533. }
  26534. if (predicate) {
  26535. if (!predicate(sprite)) {
  26536. continue;
  26537. }
  26538. }
  26539. else if (!sprite.isPickable) {
  26540. continue;
  26541. }
  26542. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  26543. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  26544. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  26545. if (ray.intersectsBoxMinMax(min, max)) {
  26546. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  26547. if (distance > currentDistance) {
  26548. distance = currentDistance;
  26549. currentSprite = sprite;
  26550. if (fastCheck) {
  26551. break;
  26552. }
  26553. }
  26554. }
  26555. }
  26556. if (currentSprite) {
  26557. var result = new BABYLON.PickingInfo();
  26558. result.hit = true;
  26559. result.pickedSprite = currentSprite;
  26560. result.distance = distance;
  26561. return result;
  26562. }
  26563. return null;
  26564. };
  26565. SpriteManager.prototype.render = function () {
  26566. // Check
  26567. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  26568. return;
  26569. var engine = this._scene.getEngine();
  26570. var baseSize = this._spriteTexture.getBaseSize();
  26571. // Sprites
  26572. var deltaTime = engine.getDeltaTime();
  26573. var max = Math.min(this._capacity, this.sprites.length);
  26574. var rowSize = baseSize.width / this.cellWidth;
  26575. var offset = 0;
  26576. for (var index = 0; index < max; index++) {
  26577. var sprite = this.sprites[index];
  26578. if (!sprite) {
  26579. continue;
  26580. }
  26581. sprite._animate(deltaTime);
  26582. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  26583. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  26584. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  26585. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  26586. }
  26587. this._buffer.update(this._vertexData);
  26588. // Render
  26589. var effect = this._effectBase;
  26590. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26591. effect = this._effectFog;
  26592. }
  26593. engine.enableEffect(effect);
  26594. var viewMatrix = this._scene.getViewMatrix();
  26595. effect.setTexture("diffuseSampler", this._spriteTexture);
  26596. effect.setMatrix("view", viewMatrix);
  26597. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  26598. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  26599. // Fog
  26600. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26601. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  26602. effect.setColor3("vFogColor", this._scene.fogColor);
  26603. }
  26604. // VBOs
  26605. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  26606. // Draw order
  26607. engine.setDepthFunctionToLessOrEqual();
  26608. effect.setBool("alphaTest", true);
  26609. engine.setColorWrite(false);
  26610. engine.draw(true, 0, max * 6);
  26611. engine.setColorWrite(true);
  26612. effect.setBool("alphaTest", false);
  26613. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26614. engine.draw(true, 0, max * 6);
  26615. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26616. };
  26617. SpriteManager.prototype.dispose = function () {
  26618. if (this._buffer) {
  26619. this._buffer.dispose();
  26620. this._buffer = null;
  26621. }
  26622. if (this._indexBuffer) {
  26623. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26624. this._indexBuffer = null;
  26625. }
  26626. if (this._spriteTexture) {
  26627. this._spriteTexture.dispose();
  26628. this._spriteTexture = null;
  26629. }
  26630. // Remove from scene
  26631. var index = this._scene.spriteManagers.indexOf(this);
  26632. this._scene.spriteManagers.splice(index, 1);
  26633. // Callback
  26634. this.onDisposeObservable.notifyObservers(this);
  26635. this.onDisposeObservable.clear();
  26636. };
  26637. return SpriteManager;
  26638. })();
  26639. BABYLON.SpriteManager = SpriteManager;
  26640. })(BABYLON || (BABYLON = {}));
  26641. var BABYLON;
  26642. (function (BABYLON) {
  26643. var Sprite = (function () {
  26644. function Sprite(name, manager) {
  26645. this.name = name;
  26646. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26647. this.width = 1.0;
  26648. this.height = 1.0;
  26649. this.angle = 0;
  26650. this.cellIndex = 0;
  26651. this.invertU = 0;
  26652. this.invertV = 0;
  26653. this.animations = new Array();
  26654. this.isPickable = false;
  26655. this._animationStarted = false;
  26656. this._loopAnimation = false;
  26657. this._fromIndex = 0;
  26658. this._toIndex = 0;
  26659. this._delay = 0;
  26660. this._direction = 1;
  26661. this._frameCount = 0;
  26662. this._time = 0;
  26663. this._manager = manager;
  26664. this._manager.sprites.push(this);
  26665. this.position = BABYLON.Vector3.Zero();
  26666. }
  26667. Object.defineProperty(Sprite.prototype, "size", {
  26668. get: function () {
  26669. return this.width;
  26670. },
  26671. set: function (value) {
  26672. this.width = value;
  26673. this.height = value;
  26674. },
  26675. enumerable: true,
  26676. configurable: true
  26677. });
  26678. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  26679. this._fromIndex = from;
  26680. this._toIndex = to;
  26681. this._loopAnimation = loop;
  26682. this._delay = delay;
  26683. this._animationStarted = true;
  26684. this._direction = from < to ? 1 : -1;
  26685. this.cellIndex = from;
  26686. this._time = 0;
  26687. };
  26688. Sprite.prototype.stopAnimation = function () {
  26689. this._animationStarted = false;
  26690. };
  26691. Sprite.prototype._animate = function (deltaTime) {
  26692. if (!this._animationStarted)
  26693. return;
  26694. this._time += deltaTime;
  26695. if (this._time > this._delay) {
  26696. this._time = this._time % this._delay;
  26697. this.cellIndex += this._direction;
  26698. if (this.cellIndex == this._toIndex) {
  26699. if (this._loopAnimation) {
  26700. this.cellIndex = this._fromIndex;
  26701. }
  26702. else {
  26703. this._animationStarted = false;
  26704. if (this.disposeWhenFinishedAnimating) {
  26705. this.dispose();
  26706. }
  26707. }
  26708. }
  26709. }
  26710. };
  26711. Sprite.prototype.dispose = function () {
  26712. for (var i = 0; i < this._manager.sprites.length; i++) {
  26713. if (this._manager.sprites[i] == this) {
  26714. this._manager.sprites.splice(i, 1);
  26715. }
  26716. }
  26717. };
  26718. return Sprite;
  26719. })();
  26720. BABYLON.Sprite = Sprite;
  26721. })(BABYLON || (BABYLON = {}));
  26722. var BABYLON;
  26723. (function (BABYLON) {
  26724. var Layer = (function () {
  26725. function Layer(name, imgUrl, scene, isBackground, color) {
  26726. this.name = name;
  26727. this.scale = new BABYLON.Vector2(1, 1);
  26728. this.offset = new BABYLON.Vector2(0, 0);
  26729. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  26730. this._vertexBuffers = {};
  26731. // Events
  26732. /**
  26733. * An event triggered when the layer is disposed.
  26734. * @type {BABYLON.Observable}
  26735. */
  26736. this.onDisposeObservable = new BABYLON.Observable();
  26737. /**
  26738. * An event triggered before rendering the scene
  26739. * @type {BABYLON.Observable}
  26740. */
  26741. this.onBeforeRenderObservable = new BABYLON.Observable();
  26742. /**
  26743. * An event triggered after rendering the scene
  26744. * @type {BABYLON.Observable}
  26745. */
  26746. this.onAfterRenderObservable = new BABYLON.Observable();
  26747. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  26748. this.isBackground = isBackground === undefined ? true : isBackground;
  26749. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  26750. this._scene = scene;
  26751. this._scene.layers.push(this);
  26752. var engine = scene.getEngine();
  26753. // VBO
  26754. var vertices = [];
  26755. vertices.push(1, 1);
  26756. vertices.push(-1, 1);
  26757. vertices.push(-1, -1);
  26758. vertices.push(1, -1);
  26759. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  26760. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  26761. // Indices
  26762. var indices = [];
  26763. indices.push(0);
  26764. indices.push(1);
  26765. indices.push(2);
  26766. indices.push(0);
  26767. indices.push(2);
  26768. indices.push(3);
  26769. this._indexBuffer = engine.createIndexBuffer(indices);
  26770. // Effects
  26771. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  26772. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  26773. }
  26774. Object.defineProperty(Layer.prototype, "onDispose", {
  26775. set: function (callback) {
  26776. if (this._onDisposeObserver) {
  26777. this.onDisposeObservable.remove(this._onDisposeObserver);
  26778. }
  26779. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26780. },
  26781. enumerable: true,
  26782. configurable: true
  26783. });
  26784. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  26785. set: function (callback) {
  26786. if (this._onBeforeRenderObserver) {
  26787. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  26788. }
  26789. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  26790. },
  26791. enumerable: true,
  26792. configurable: true
  26793. });
  26794. Object.defineProperty(Layer.prototype, "onAfterRender", {
  26795. set: function (callback) {
  26796. if (this._onAfterRenderObserver) {
  26797. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  26798. }
  26799. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  26800. },
  26801. enumerable: true,
  26802. configurable: true
  26803. });
  26804. Layer.prototype.render = function () {
  26805. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  26806. // Check
  26807. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  26808. return;
  26809. var engine = this._scene.getEngine();
  26810. this.onBeforeRenderObservable.notifyObservers(this);
  26811. // Render
  26812. engine.enableEffect(currentEffect);
  26813. engine.setState(false);
  26814. // Texture
  26815. currentEffect.setTexture("textureSampler", this.texture);
  26816. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  26817. // Color
  26818. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  26819. // Scale / offset
  26820. currentEffect.setVector2("offset", this.offset);
  26821. currentEffect.setVector2("scale", this.scale);
  26822. // VBOs
  26823. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  26824. // Draw order
  26825. if (!this._alphaTestEffect) {
  26826. engine.setAlphaMode(this.alphaBlendingMode);
  26827. engine.draw(true, 0, 6);
  26828. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26829. }
  26830. else {
  26831. engine.draw(true, 0, 6);
  26832. }
  26833. this.onAfterRenderObservable.notifyObservers(this);
  26834. };
  26835. Layer.prototype.dispose = function () {
  26836. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  26837. if (vertexBuffer) {
  26838. vertexBuffer.dispose();
  26839. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  26840. }
  26841. if (this._indexBuffer) {
  26842. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26843. this._indexBuffer = null;
  26844. }
  26845. if (this.texture) {
  26846. this.texture.dispose();
  26847. this.texture = null;
  26848. }
  26849. // Remove from scene
  26850. var index = this._scene.layers.indexOf(this);
  26851. this._scene.layers.splice(index, 1);
  26852. // Callback
  26853. this.onDisposeObservable.notifyObservers(this);
  26854. this.onDisposeObservable.clear();
  26855. this.onAfterRenderObservable.clear();
  26856. this.onBeforeRenderObservable.clear();
  26857. };
  26858. return Layer;
  26859. })();
  26860. BABYLON.Layer = Layer;
  26861. })(BABYLON || (BABYLON = {}));
  26862. var BABYLON;
  26863. (function (BABYLON) {
  26864. var Particle = (function () {
  26865. function Particle() {
  26866. this.position = BABYLON.Vector3.Zero();
  26867. this.direction = BABYLON.Vector3.Zero();
  26868. this.color = new BABYLON.Color4(0, 0, 0, 0);
  26869. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  26870. this.lifeTime = 1.0;
  26871. this.age = 0;
  26872. this.size = 0;
  26873. this.angle = 0;
  26874. this.angularSpeed = 0;
  26875. }
  26876. Particle.prototype.copyTo = function (other) {
  26877. other.position.copyFrom(this.position);
  26878. other.direction.copyFrom(this.direction);
  26879. other.color.copyFrom(this.color);
  26880. other.colorStep.copyFrom(this.colorStep);
  26881. other.lifeTime = this.lifeTime;
  26882. other.age = this.age;
  26883. other.size = this.size;
  26884. other.angle = this.angle;
  26885. other.angularSpeed = this.angularSpeed;
  26886. };
  26887. return Particle;
  26888. })();
  26889. BABYLON.Particle = Particle;
  26890. })(BABYLON || (BABYLON = {}));
  26891. var BABYLON;
  26892. (function (BABYLON) {
  26893. var randomNumber = function (min, max) {
  26894. if (min === max) {
  26895. return (min);
  26896. }
  26897. var random = Math.random();
  26898. return ((random * (max - min)) + min);
  26899. };
  26900. var ParticleSystem = (function () {
  26901. function ParticleSystem(name, capacity, scene, customEffect) {
  26902. var _this = this;
  26903. this.name = name;
  26904. // Members
  26905. this.animations = [];
  26906. this.renderingGroupId = 0;
  26907. this.emitter = null;
  26908. this.emitRate = 10;
  26909. this.manualEmitCount = -1;
  26910. this.updateSpeed = 0.01;
  26911. this.targetStopDuration = 0;
  26912. this.disposeOnStop = false;
  26913. this.minEmitPower = 1;
  26914. this.maxEmitPower = 1;
  26915. this.minLifeTime = 1;
  26916. this.maxLifeTime = 1;
  26917. this.minSize = 1;
  26918. this.maxSize = 1;
  26919. this.minAngularSpeed = 0;
  26920. this.maxAngularSpeed = 0;
  26921. this.layerMask = 0x0FFFFFFF;
  26922. /**
  26923. * An event triggered when the system is disposed.
  26924. * @type {BABYLON.Observable}
  26925. */
  26926. this.onDisposeObservable = new BABYLON.Observable();
  26927. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  26928. this.forceDepthWrite = false;
  26929. this.gravity = BABYLON.Vector3.Zero();
  26930. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  26931. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  26932. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  26933. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  26934. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26935. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26936. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  26937. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26938. this.particles = new Array();
  26939. this._stockParticles = new Array();
  26940. this._newPartsExcess = 0;
  26941. this._vertexBuffers = {};
  26942. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  26943. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  26944. this._scaledDirection = BABYLON.Vector3.Zero();
  26945. this._scaledGravity = BABYLON.Vector3.Zero();
  26946. this._currentRenderId = -1;
  26947. this._started = false;
  26948. this._stopped = false;
  26949. this._actualFrame = 0;
  26950. this.id = name;
  26951. this._capacity = capacity;
  26952. this._scene = scene;
  26953. this._customEffect = customEffect;
  26954. scene.particleSystems.push(this);
  26955. var indices = [];
  26956. var index = 0;
  26957. for (var count = 0; count < capacity; count++) {
  26958. indices.push(index);
  26959. indices.push(index + 1);
  26960. indices.push(index + 2);
  26961. indices.push(index);
  26962. indices.push(index + 2);
  26963. indices.push(index + 3);
  26964. index += 4;
  26965. }
  26966. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  26967. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  26968. this._vertexData = new Float32Array(capacity * 11 * 4);
  26969. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  26970. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  26971. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  26972. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  26973. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  26974. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  26975. this._vertexBuffers["options"] = options;
  26976. // Default behaviors
  26977. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  26978. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  26979. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  26980. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  26981. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  26982. };
  26983. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  26984. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  26985. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  26986. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  26987. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  26988. };
  26989. this.updateFunction = function (particles) {
  26990. for (var index = 0; index < particles.length; index++) {
  26991. var particle = particles[index];
  26992. particle.age += _this._scaledUpdateSpeed;
  26993. if (particle.age >= particle.lifeTime) {
  26994. _this.recycleParticle(particle);
  26995. index--;
  26996. continue;
  26997. }
  26998. else {
  26999. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  27000. particle.color.addInPlace(_this._scaledColorStep);
  27001. if (particle.color.a < 0)
  27002. particle.color.a = 0;
  27003. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  27004. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  27005. particle.position.addInPlace(_this._scaledDirection);
  27006. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  27007. particle.direction.addInPlace(_this._scaledGravity);
  27008. }
  27009. }
  27010. };
  27011. }
  27012. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  27013. set: function (callback) {
  27014. if (this._onDisposeObserver) {
  27015. this.onDisposeObservable.remove(this._onDisposeObserver);
  27016. }
  27017. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27018. },
  27019. enumerable: true,
  27020. configurable: true
  27021. });
  27022. ParticleSystem.prototype.recycleParticle = function (particle) {
  27023. var lastParticle = this.particles.pop();
  27024. if (lastParticle !== particle) {
  27025. lastParticle.copyTo(particle);
  27026. this._stockParticles.push(lastParticle);
  27027. }
  27028. };
  27029. ParticleSystem.prototype.getCapacity = function () {
  27030. return this._capacity;
  27031. };
  27032. ParticleSystem.prototype.isAlive = function () {
  27033. return this._alive;
  27034. };
  27035. ParticleSystem.prototype.isStarted = function () {
  27036. return this._started;
  27037. };
  27038. ParticleSystem.prototype.start = function () {
  27039. this._started = true;
  27040. this._stopped = false;
  27041. this._actualFrame = 0;
  27042. };
  27043. ParticleSystem.prototype.stop = function () {
  27044. this._stopped = true;
  27045. };
  27046. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  27047. var offset = index * 11;
  27048. this._vertexData[offset] = particle.position.x;
  27049. this._vertexData[offset + 1] = particle.position.y;
  27050. this._vertexData[offset + 2] = particle.position.z;
  27051. this._vertexData[offset + 3] = particle.color.r;
  27052. this._vertexData[offset + 4] = particle.color.g;
  27053. this._vertexData[offset + 5] = particle.color.b;
  27054. this._vertexData[offset + 6] = particle.color.a;
  27055. this._vertexData[offset + 7] = particle.angle;
  27056. this._vertexData[offset + 8] = particle.size;
  27057. this._vertexData[offset + 9] = offsetX;
  27058. this._vertexData[offset + 10] = offsetY;
  27059. };
  27060. ParticleSystem.prototype._update = function (newParticles) {
  27061. // Update current
  27062. this._alive = this.particles.length > 0;
  27063. this.updateFunction(this.particles);
  27064. // Add new ones
  27065. var worldMatrix;
  27066. if (this.emitter.position) {
  27067. worldMatrix = this.emitter.getWorldMatrix();
  27068. }
  27069. else {
  27070. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  27071. }
  27072. var particle;
  27073. for (var index = 0; index < newParticles; index++) {
  27074. if (this.particles.length === this._capacity) {
  27075. break;
  27076. }
  27077. if (this._stockParticles.length !== 0) {
  27078. particle = this._stockParticles.pop();
  27079. particle.age = 0;
  27080. }
  27081. else {
  27082. particle = new BABYLON.Particle();
  27083. }
  27084. this.particles.push(particle);
  27085. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  27086. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  27087. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  27088. particle.size = randomNumber(this.minSize, this.maxSize);
  27089. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  27090. this.startPositionFunction(worldMatrix, particle.position, particle);
  27091. var step = randomNumber(0, 1.0);
  27092. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  27093. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  27094. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  27095. }
  27096. };
  27097. ParticleSystem.prototype._getEffect = function () {
  27098. if (this._customEffect) {
  27099. return this._customEffect;
  27100. }
  27101. ;
  27102. var defines = [];
  27103. if (this._scene.clipPlane) {
  27104. defines.push("#define CLIPPLANE");
  27105. }
  27106. // Effect
  27107. var join = defines.join("\n");
  27108. if (this._cachedDefines !== join) {
  27109. this._cachedDefines = join;
  27110. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  27111. }
  27112. return this._effect;
  27113. };
  27114. ParticleSystem.prototype.animate = function () {
  27115. if (!this._started)
  27116. return;
  27117. var effect = this._getEffect();
  27118. // Check
  27119. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  27120. return;
  27121. if (this._currentRenderId === this._scene.getRenderId()) {
  27122. return;
  27123. }
  27124. this._currentRenderId = this._scene.getRenderId();
  27125. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  27126. // determine the number of particles we need to create
  27127. var newParticles;
  27128. if (this.manualEmitCount > -1) {
  27129. newParticles = this.manualEmitCount;
  27130. this._newPartsExcess = 0;
  27131. this.manualEmitCount = 0;
  27132. }
  27133. else {
  27134. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  27135. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  27136. }
  27137. if (this._newPartsExcess > 1.0) {
  27138. newParticles += this._newPartsExcess >> 0;
  27139. this._newPartsExcess -= this._newPartsExcess >> 0;
  27140. }
  27141. this._alive = false;
  27142. if (!this._stopped) {
  27143. this._actualFrame += this._scaledUpdateSpeed;
  27144. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  27145. this.stop();
  27146. }
  27147. else {
  27148. newParticles = 0;
  27149. }
  27150. this._update(newParticles);
  27151. // Stopped?
  27152. if (this._stopped) {
  27153. if (!this._alive) {
  27154. this._started = false;
  27155. if (this.disposeOnStop) {
  27156. this._scene._toBeDisposed.push(this);
  27157. }
  27158. }
  27159. }
  27160. // Update VBO
  27161. var offset = 0;
  27162. for (var index = 0; index < this.particles.length; index++) {
  27163. var particle = this.particles[index];
  27164. this._appendParticleVertex(offset++, particle, 0, 0);
  27165. this._appendParticleVertex(offset++, particle, 1, 0);
  27166. this._appendParticleVertex(offset++, particle, 1, 1);
  27167. this._appendParticleVertex(offset++, particle, 0, 1);
  27168. }
  27169. this._vertexBuffer.update(this._vertexData);
  27170. };
  27171. ParticleSystem.prototype.render = function () {
  27172. var effect = this._getEffect();
  27173. // Check
  27174. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  27175. return 0;
  27176. var engine = this._scene.getEngine();
  27177. // Render
  27178. engine.enableEffect(effect);
  27179. engine.setState(false);
  27180. var viewMatrix = this._scene.getViewMatrix();
  27181. effect.setTexture("diffuseSampler", this.particleTexture);
  27182. effect.setMatrix("view", viewMatrix);
  27183. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  27184. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  27185. if (this._scene.clipPlane) {
  27186. var clipPlane = this._scene.clipPlane;
  27187. var invView = viewMatrix.clone();
  27188. invView.invert();
  27189. effect.setMatrix("invView", invView);
  27190. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  27191. }
  27192. // VBOs
  27193. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27194. // Draw order
  27195. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  27196. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  27197. }
  27198. else {
  27199. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27200. }
  27201. if (this.forceDepthWrite) {
  27202. engine.setDepthWrite(true);
  27203. }
  27204. engine.draw(true, 0, this.particles.length * 6);
  27205. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27206. return this.particles.length;
  27207. };
  27208. ParticleSystem.prototype.dispose = function () {
  27209. if (this._vertexBuffer) {
  27210. this._vertexBuffer.dispose();
  27211. this._vertexBuffer = null;
  27212. }
  27213. if (this._indexBuffer) {
  27214. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27215. this._indexBuffer = null;
  27216. }
  27217. if (this.particleTexture) {
  27218. this.particleTexture.dispose();
  27219. this.particleTexture = null;
  27220. }
  27221. // Remove from scene
  27222. var index = this._scene.particleSystems.indexOf(this);
  27223. this._scene.particleSystems.splice(index, 1);
  27224. // Callback
  27225. this.onDisposeObservable.notifyObservers(this);
  27226. this.onDisposeObservable.clear();
  27227. };
  27228. // Clone
  27229. ParticleSystem.prototype.clone = function (name, newEmitter) {
  27230. var result = new ParticleSystem(name, this._capacity, this._scene);
  27231. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  27232. if (newEmitter === undefined) {
  27233. newEmitter = this.emitter;
  27234. }
  27235. result.emitter = newEmitter;
  27236. if (this.particleTexture) {
  27237. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  27238. }
  27239. result.start();
  27240. return result;
  27241. };
  27242. ParticleSystem.prototype.serialize = function () {
  27243. var serializationObject = {};
  27244. serializationObject.name = this.name;
  27245. serializationObject.id = this.id;
  27246. // Emitter
  27247. if (this.emitter.position) {
  27248. serializationObject.emitterId = this.emitter.id;
  27249. }
  27250. else {
  27251. serializationObject.emitter = this.emitter.asArray();
  27252. }
  27253. serializationObject.capacity = this.getCapacity();
  27254. if (this.particleTexture) {
  27255. serializationObject.textureName = this.particleTexture.name;
  27256. }
  27257. // Animations
  27258. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27259. // Particle system
  27260. serializationObject.minAngularSpeed = this.minAngularSpeed;
  27261. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  27262. serializationObject.minSize = this.minSize;
  27263. serializationObject.maxSize = this.maxSize;
  27264. serializationObject.minEmitPower = this.minEmitPower;
  27265. serializationObject.maxEmitPower = this.maxEmitPower;
  27266. serializationObject.minLifeTime = this.minLifeTime;
  27267. serializationObject.maxLifeTime = this.maxLifeTime;
  27268. serializationObject.emitRate = this.emitRate;
  27269. serializationObject.minEmitBox = this.minEmitBox.asArray();
  27270. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  27271. serializationObject.gravity = this.gravity.asArray();
  27272. serializationObject.direction1 = this.direction1.asArray();
  27273. serializationObject.direction2 = this.direction2.asArray();
  27274. serializationObject.color1 = this.color1.asArray();
  27275. serializationObject.color2 = this.color2.asArray();
  27276. serializationObject.colorDead = this.colorDead.asArray();
  27277. serializationObject.updateSpeed = this.updateSpeed;
  27278. serializationObject.targetStopDuration = this.targetStopDuration;
  27279. serializationObject.textureMask = this.textureMask.asArray();
  27280. serializationObject.blendMode = this.blendMode;
  27281. return serializationObject;
  27282. };
  27283. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  27284. var name = parsedParticleSystem.name;
  27285. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  27286. if (parsedParticleSystem.id) {
  27287. particleSystem.id = parsedParticleSystem.id;
  27288. }
  27289. // Texture
  27290. if (parsedParticleSystem.textureName) {
  27291. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  27292. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  27293. }
  27294. // Emitter
  27295. if (parsedParticleSystem.emitterId) {
  27296. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  27297. }
  27298. else {
  27299. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  27300. }
  27301. // Animations
  27302. if (parsedParticleSystem.animations) {
  27303. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  27304. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  27305. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27306. }
  27307. }
  27308. if (parsedParticleSystem.autoAnimate) {
  27309. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  27310. }
  27311. // Particle system
  27312. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  27313. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  27314. particleSystem.minSize = parsedParticleSystem.minSize;
  27315. particleSystem.maxSize = parsedParticleSystem.maxSize;
  27316. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  27317. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  27318. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  27319. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  27320. particleSystem.emitRate = parsedParticleSystem.emitRate;
  27321. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  27322. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  27323. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  27324. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  27325. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  27326. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  27327. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  27328. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  27329. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  27330. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  27331. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  27332. particleSystem.blendMode = parsedParticleSystem.blendMode;
  27333. if (!parsedParticleSystem.preventAutoStart) {
  27334. particleSystem.start();
  27335. }
  27336. return particleSystem;
  27337. };
  27338. // Statics
  27339. ParticleSystem.BLENDMODE_ONEONE = 0;
  27340. ParticleSystem.BLENDMODE_STANDARD = 1;
  27341. return ParticleSystem;
  27342. })();
  27343. BABYLON.ParticleSystem = ParticleSystem;
  27344. })(BABYLON || (BABYLON = {}));
  27345. var BABYLON;
  27346. (function (BABYLON) {
  27347. var AnimationRange = (function () {
  27348. function AnimationRange(name, from, to) {
  27349. this.name = name;
  27350. this.from = from;
  27351. this.to = to;
  27352. }
  27353. AnimationRange.prototype.clone = function () {
  27354. return new AnimationRange(this.name, this.from, this.to);
  27355. };
  27356. return AnimationRange;
  27357. })();
  27358. BABYLON.AnimationRange = AnimationRange;
  27359. /**
  27360. * Composed of a frame, and an action function
  27361. */
  27362. var AnimationEvent = (function () {
  27363. function AnimationEvent(frame, action, onlyOnce) {
  27364. this.frame = frame;
  27365. this.action = action;
  27366. this.onlyOnce = onlyOnce;
  27367. this.isDone = false;
  27368. }
  27369. return AnimationEvent;
  27370. })();
  27371. BABYLON.AnimationEvent = AnimationEvent;
  27372. var PathCursor = (function () {
  27373. function PathCursor(path) {
  27374. this.path = path;
  27375. this._onchange = new Array();
  27376. this.value = 0;
  27377. this.animations = new Array();
  27378. }
  27379. PathCursor.prototype.getPoint = function () {
  27380. var point = this.path.getPointAtLengthPosition(this.value);
  27381. return new BABYLON.Vector3(point.x, 0, point.y);
  27382. };
  27383. PathCursor.prototype.moveAhead = function (step) {
  27384. if (step === void 0) { step = 0.002; }
  27385. this.move(step);
  27386. return this;
  27387. };
  27388. PathCursor.prototype.moveBack = function (step) {
  27389. if (step === void 0) { step = 0.002; }
  27390. this.move(-step);
  27391. return this;
  27392. };
  27393. PathCursor.prototype.move = function (step) {
  27394. if (Math.abs(step) > 1) {
  27395. throw "step size should be less than 1.";
  27396. }
  27397. this.value += step;
  27398. this.ensureLimits();
  27399. this.raiseOnChange();
  27400. return this;
  27401. };
  27402. PathCursor.prototype.ensureLimits = function () {
  27403. while (this.value > 1) {
  27404. this.value -= 1;
  27405. }
  27406. while (this.value < 0) {
  27407. this.value += 1;
  27408. }
  27409. return this;
  27410. };
  27411. // used by animation engine
  27412. PathCursor.prototype.markAsDirty = function (propertyName) {
  27413. this.ensureLimits();
  27414. this.raiseOnChange();
  27415. return this;
  27416. };
  27417. PathCursor.prototype.raiseOnChange = function () {
  27418. var _this = this;
  27419. this._onchange.forEach(function (f) { return f(_this); });
  27420. return this;
  27421. };
  27422. PathCursor.prototype.onchange = function (f) {
  27423. this._onchange.push(f);
  27424. return this;
  27425. };
  27426. return PathCursor;
  27427. })();
  27428. BABYLON.PathCursor = PathCursor;
  27429. var Animation = (function () {
  27430. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  27431. this.name = name;
  27432. this.targetProperty = targetProperty;
  27433. this.framePerSecond = framePerSecond;
  27434. this.dataType = dataType;
  27435. this.loopMode = loopMode;
  27436. this.enableBlending = enableBlending;
  27437. this._offsetsCache = {};
  27438. this._highLimitsCache = {};
  27439. this._stopped = false;
  27440. this._blendingFactor = 0;
  27441. // The set of event that will be linked to this animation
  27442. this._events = new Array();
  27443. this.allowMatricesInterpolation = false;
  27444. this.blendingSpeed = 0.01;
  27445. this._ranges = {};
  27446. this.targetPropertyPath = targetProperty.split(".");
  27447. this.dataType = dataType;
  27448. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  27449. }
  27450. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  27451. var dataType = undefined;
  27452. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  27453. dataType = Animation.ANIMATIONTYPE_FLOAT;
  27454. }
  27455. else if (from instanceof BABYLON.Quaternion) {
  27456. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  27457. }
  27458. else if (from instanceof BABYLON.Vector3) {
  27459. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  27460. }
  27461. else if (from instanceof BABYLON.Vector2) {
  27462. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  27463. }
  27464. else if (from instanceof BABYLON.Color3) {
  27465. dataType = Animation.ANIMATIONTYPE_COLOR3;
  27466. }
  27467. else if (from instanceof BABYLON.Size) {
  27468. dataType = Animation.ANIMATIONTYPE_SIZE;
  27469. }
  27470. if (dataType == undefined) {
  27471. return null;
  27472. }
  27473. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  27474. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  27475. animation.setKeys(keys);
  27476. if (easingFunction !== undefined) {
  27477. animation.setEasingFunction(easingFunction);
  27478. }
  27479. return animation;
  27480. };
  27481. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  27482. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  27483. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  27484. };
  27485. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  27486. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  27487. node.animations.push(animation);
  27488. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  27489. };
  27490. // Methods
  27491. /**
  27492. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27493. */
  27494. Animation.prototype.toString = function (fullDetails) {
  27495. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  27496. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  27497. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  27498. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  27499. if (fullDetails) {
  27500. ret += ", Ranges: {";
  27501. var first = true;
  27502. for (var name in this._ranges) {
  27503. if (first) {
  27504. ret += ", ";
  27505. first = false;
  27506. }
  27507. ret += name;
  27508. }
  27509. ret += "}";
  27510. }
  27511. return ret;
  27512. };
  27513. /**
  27514. * Add an event to this animation.
  27515. */
  27516. Animation.prototype.addEvent = function (event) {
  27517. this._events.push(event);
  27518. };
  27519. /**
  27520. * Remove all events found at the given frame
  27521. * @param frame
  27522. */
  27523. Animation.prototype.removeEvents = function (frame) {
  27524. for (var index = 0; index < this._events.length; index++) {
  27525. if (this._events[index].frame === frame) {
  27526. this._events.splice(index, 1);
  27527. index--;
  27528. }
  27529. }
  27530. };
  27531. Animation.prototype.createRange = function (name, from, to) {
  27532. // check name not already in use; could happen for bones after serialized
  27533. if (!this._ranges[name]) {
  27534. this._ranges[name] = new AnimationRange(name, from, to);
  27535. }
  27536. };
  27537. Animation.prototype.deleteRange = function (name, deleteFrames) {
  27538. if (deleteFrames === void 0) { deleteFrames = true; }
  27539. if (this._ranges[name]) {
  27540. if (deleteFrames) {
  27541. var from = this._ranges[name].from;
  27542. var to = this._ranges[name].to;
  27543. // this loop MUST go high to low for multiple splices to work
  27544. for (var key = this._keys.length - 1; key >= 0; key--) {
  27545. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  27546. this._keys.splice(key, 1);
  27547. }
  27548. }
  27549. }
  27550. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  27551. }
  27552. };
  27553. Animation.prototype.getRange = function (name) {
  27554. return this._ranges[name];
  27555. };
  27556. Animation.prototype.reset = function () {
  27557. this._offsetsCache = {};
  27558. this._highLimitsCache = {};
  27559. this.currentFrame = 0;
  27560. this._blendingFactor = 0;
  27561. this._originalBlendValue = null;
  27562. };
  27563. Animation.prototype.isStopped = function () {
  27564. return this._stopped;
  27565. };
  27566. Animation.prototype.getKeys = function () {
  27567. return this._keys;
  27568. };
  27569. Animation.prototype.getHighestFrame = function () {
  27570. var ret = 0;
  27571. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  27572. if (ret < this._keys[key].frame) {
  27573. ret = this._keys[key].frame;
  27574. }
  27575. }
  27576. return ret;
  27577. };
  27578. Animation.prototype.getEasingFunction = function () {
  27579. return this._easingFunction;
  27580. };
  27581. Animation.prototype.setEasingFunction = function (easingFunction) {
  27582. this._easingFunction = easingFunction;
  27583. };
  27584. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  27585. return startValue + (endValue - startValue) * gradient;
  27586. };
  27587. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  27588. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  27589. };
  27590. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  27591. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  27592. };
  27593. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  27594. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  27595. };
  27596. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  27597. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  27598. };
  27599. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  27600. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  27601. };
  27602. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  27603. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  27604. };
  27605. Animation.prototype.clone = function () {
  27606. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  27607. if (this._keys) {
  27608. clone.setKeys(this._keys);
  27609. }
  27610. if (this._ranges) {
  27611. clone._ranges = {};
  27612. for (var name in this._ranges) {
  27613. clone._ranges[name] = this._ranges[name].clone();
  27614. }
  27615. }
  27616. return clone;
  27617. };
  27618. Animation.prototype.setKeys = function (values) {
  27619. this._keys = values.slice(0);
  27620. this._offsetsCache = {};
  27621. this._highLimitsCache = {};
  27622. };
  27623. Animation.prototype._getKeyValue = function (value) {
  27624. if (typeof value === "function") {
  27625. return value();
  27626. }
  27627. return value;
  27628. };
  27629. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  27630. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  27631. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  27632. }
  27633. this.currentFrame = currentFrame;
  27634. // Try to get a hash to find the right key
  27635. 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));
  27636. if (this._keys[startKey].frame >= currentFrame) {
  27637. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  27638. startKey--;
  27639. }
  27640. }
  27641. for (var key = startKey; key < this._keys.length; key++) {
  27642. if (this._keys[key + 1].frame >= currentFrame) {
  27643. var startValue = this._getKeyValue(this._keys[key].value);
  27644. var endValue = this._getKeyValue(this._keys[key + 1].value);
  27645. // gradient : percent of currentFrame between the frame inf and the frame sup
  27646. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  27647. // check for easingFunction and correction of gradient
  27648. if (this._easingFunction != null) {
  27649. gradient = this._easingFunction.ease(gradient);
  27650. }
  27651. switch (this.dataType) {
  27652. // Float
  27653. case Animation.ANIMATIONTYPE_FLOAT:
  27654. switch (loopMode) {
  27655. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27656. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27657. return this.floatInterpolateFunction(startValue, endValue, gradient);
  27658. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27659. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  27660. }
  27661. break;
  27662. // Quaternion
  27663. case Animation.ANIMATIONTYPE_QUATERNION:
  27664. var quaternion = null;
  27665. switch (loopMode) {
  27666. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27667. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27668. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  27669. break;
  27670. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27671. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27672. break;
  27673. }
  27674. return quaternion;
  27675. // Vector3
  27676. case Animation.ANIMATIONTYPE_VECTOR3:
  27677. switch (loopMode) {
  27678. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27679. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27680. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  27681. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27682. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27683. }
  27684. // Vector2
  27685. case Animation.ANIMATIONTYPE_VECTOR2:
  27686. switch (loopMode) {
  27687. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27688. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27689. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  27690. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27691. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27692. }
  27693. // Size
  27694. case Animation.ANIMATIONTYPE_SIZE:
  27695. switch (loopMode) {
  27696. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27697. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27698. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  27699. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27700. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27701. }
  27702. // Color3
  27703. case Animation.ANIMATIONTYPE_COLOR3:
  27704. switch (loopMode) {
  27705. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27706. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27707. return this.color3InterpolateFunction(startValue, endValue, gradient);
  27708. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27709. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27710. }
  27711. // Matrix
  27712. case Animation.ANIMATIONTYPE_MATRIX:
  27713. switch (loopMode) {
  27714. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27715. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27716. if (this.allowMatricesInterpolation) {
  27717. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  27718. }
  27719. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27720. return startValue;
  27721. }
  27722. default:
  27723. break;
  27724. }
  27725. break;
  27726. }
  27727. }
  27728. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  27729. };
  27730. Animation.prototype.setValue = function (currentValue, blend) {
  27731. if (blend === void 0) { blend = false; }
  27732. // Set value
  27733. var path;
  27734. var destination;
  27735. if (this.targetPropertyPath.length > 1) {
  27736. var property = this._target[this.targetPropertyPath[0]];
  27737. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  27738. property = property[this.targetPropertyPath[index]];
  27739. }
  27740. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  27741. destination = property;
  27742. }
  27743. else {
  27744. path = this.targetPropertyPath[0];
  27745. destination = this._target;
  27746. }
  27747. // Blending
  27748. if (this.enableBlending && this._blendingFactor <= 1.0) {
  27749. if (!this._originalBlendValue) {
  27750. if (destination[path].clone) {
  27751. this._originalBlendValue = destination[path].clone();
  27752. }
  27753. else {
  27754. this._originalBlendValue = destination[path];
  27755. }
  27756. }
  27757. if (this._originalBlendValue.prototype) {
  27758. if (this._originalBlendValue.prototype.Lerp) {
  27759. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  27760. }
  27761. else {
  27762. destination[path] = currentValue;
  27763. }
  27764. }
  27765. else if (this._originalBlendValue.m) {
  27766. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  27767. }
  27768. else {
  27769. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  27770. }
  27771. this._blendingFactor += this.blendingSpeed;
  27772. }
  27773. else {
  27774. destination[path] = currentValue;
  27775. }
  27776. if (this._target.markAsDirty) {
  27777. this._target.markAsDirty(this.targetProperty);
  27778. }
  27779. };
  27780. Animation.prototype.goToFrame = function (frame) {
  27781. if (frame < this._keys[0].frame) {
  27782. frame = this._keys[0].frame;
  27783. }
  27784. else if (frame > this._keys[this._keys.length - 1].frame) {
  27785. frame = this._keys[this._keys.length - 1].frame;
  27786. }
  27787. var currentValue = this._interpolate(frame, 0, this.loopMode);
  27788. this.setValue(currentValue);
  27789. };
  27790. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  27791. if (blend === void 0) { blend = false; }
  27792. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  27793. this._stopped = true;
  27794. return false;
  27795. }
  27796. var returnValue = true;
  27797. // Adding a start key at frame 0 if missing
  27798. if (this._keys[0].frame !== 0) {
  27799. var newKey = { frame: 0, value: this._keys[0].value };
  27800. this._keys.splice(0, 0, newKey);
  27801. }
  27802. // Check limits
  27803. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  27804. from = this._keys[0].frame;
  27805. }
  27806. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  27807. to = this._keys[this._keys.length - 1].frame;
  27808. }
  27809. // Compute ratio
  27810. var range = to - from;
  27811. var offsetValue;
  27812. // ratio represents the frame delta between from and to
  27813. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  27814. var highLimitValue = 0;
  27815. if (ratio > range && !loop) {
  27816. returnValue = false;
  27817. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  27818. }
  27819. else {
  27820. // Get max value if required
  27821. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  27822. var keyOffset = to.toString() + from.toString();
  27823. if (!this._offsetsCache[keyOffset]) {
  27824. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  27825. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  27826. switch (this.dataType) {
  27827. // Float
  27828. case Animation.ANIMATIONTYPE_FLOAT:
  27829. this._offsetsCache[keyOffset] = toValue - fromValue;
  27830. break;
  27831. // Quaternion
  27832. case Animation.ANIMATIONTYPE_QUATERNION:
  27833. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27834. break;
  27835. // Vector3
  27836. case Animation.ANIMATIONTYPE_VECTOR3:
  27837. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27838. // Vector2
  27839. case Animation.ANIMATIONTYPE_VECTOR2:
  27840. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27841. // Size
  27842. case Animation.ANIMATIONTYPE_SIZE:
  27843. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27844. // Color3
  27845. case Animation.ANIMATIONTYPE_COLOR3:
  27846. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27847. default:
  27848. break;
  27849. }
  27850. this._highLimitsCache[keyOffset] = toValue;
  27851. }
  27852. highLimitValue = this._highLimitsCache[keyOffset];
  27853. offsetValue = this._offsetsCache[keyOffset];
  27854. }
  27855. }
  27856. if (offsetValue === undefined) {
  27857. switch (this.dataType) {
  27858. // Float
  27859. case Animation.ANIMATIONTYPE_FLOAT:
  27860. offsetValue = 0;
  27861. break;
  27862. // Quaternion
  27863. case Animation.ANIMATIONTYPE_QUATERNION:
  27864. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  27865. break;
  27866. // Vector3
  27867. case Animation.ANIMATIONTYPE_VECTOR3:
  27868. offsetValue = BABYLON.Vector3.Zero();
  27869. break;
  27870. // Vector2
  27871. case Animation.ANIMATIONTYPE_VECTOR2:
  27872. offsetValue = BABYLON.Vector2.Zero();
  27873. break;
  27874. // Size
  27875. case Animation.ANIMATIONTYPE_SIZE:
  27876. offsetValue = BABYLON.Size.Zero();
  27877. break;
  27878. // Color3
  27879. case Animation.ANIMATIONTYPE_COLOR3:
  27880. offsetValue = BABYLON.Color3.Black();
  27881. }
  27882. }
  27883. // Compute value
  27884. var repeatCount = (ratio / range) >> 0;
  27885. var currentFrame = returnValue ? from + ratio % range : to;
  27886. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  27887. // Set value
  27888. this.setValue(currentValue);
  27889. // Check events
  27890. for (var index = 0; index < this._events.length; index++) {
  27891. if (currentFrame >= this._events[index].frame) {
  27892. var event = this._events[index];
  27893. if (!event.isDone) {
  27894. // If event should be done only once, remove it.
  27895. if (event.onlyOnce) {
  27896. this._events.splice(index, 1);
  27897. index--;
  27898. }
  27899. event.isDone = true;
  27900. event.action();
  27901. } // Don't do anything if the event has already be done.
  27902. }
  27903. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  27904. // reset event, the animation is looping
  27905. this._events[index].isDone = false;
  27906. }
  27907. }
  27908. if (!returnValue) {
  27909. this._stopped = true;
  27910. }
  27911. return returnValue;
  27912. };
  27913. Animation.prototype.serialize = function () {
  27914. var serializationObject = {};
  27915. serializationObject.name = this.name;
  27916. serializationObject.property = this.targetProperty;
  27917. serializationObject.framePerSecond = this.framePerSecond;
  27918. serializationObject.dataType = this.dataType;
  27919. serializationObject.loopBehavior = this.loopMode;
  27920. var dataType = this.dataType;
  27921. serializationObject.keys = [];
  27922. var keys = this.getKeys();
  27923. for (var index = 0; index < keys.length; index++) {
  27924. var animationKey = keys[index];
  27925. var key = {};
  27926. key.frame = animationKey.frame;
  27927. switch (dataType) {
  27928. case Animation.ANIMATIONTYPE_FLOAT:
  27929. key.values = [animationKey.value];
  27930. break;
  27931. case Animation.ANIMATIONTYPE_QUATERNION:
  27932. case Animation.ANIMATIONTYPE_MATRIX:
  27933. case Animation.ANIMATIONTYPE_VECTOR3:
  27934. case Animation.ANIMATIONTYPE_COLOR3:
  27935. key.values = animationKey.value.asArray();
  27936. break;
  27937. }
  27938. serializationObject.keys.push(key);
  27939. }
  27940. serializationObject.ranges = [];
  27941. for (var name in this._ranges) {
  27942. var range = {};
  27943. range.name = name;
  27944. range.from = this._ranges[name].from;
  27945. range.to = this._ranges[name].to;
  27946. serializationObject.ranges.push(range);
  27947. }
  27948. return serializationObject;
  27949. };
  27950. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  27951. get: function () {
  27952. return Animation._ANIMATIONTYPE_FLOAT;
  27953. },
  27954. enumerable: true,
  27955. configurable: true
  27956. });
  27957. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  27958. get: function () {
  27959. return Animation._ANIMATIONTYPE_VECTOR3;
  27960. },
  27961. enumerable: true,
  27962. configurable: true
  27963. });
  27964. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  27965. get: function () {
  27966. return Animation._ANIMATIONTYPE_VECTOR2;
  27967. },
  27968. enumerable: true,
  27969. configurable: true
  27970. });
  27971. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  27972. get: function () {
  27973. return Animation._ANIMATIONTYPE_SIZE;
  27974. },
  27975. enumerable: true,
  27976. configurable: true
  27977. });
  27978. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  27979. get: function () {
  27980. return Animation._ANIMATIONTYPE_QUATERNION;
  27981. },
  27982. enumerable: true,
  27983. configurable: true
  27984. });
  27985. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  27986. get: function () {
  27987. return Animation._ANIMATIONTYPE_MATRIX;
  27988. },
  27989. enumerable: true,
  27990. configurable: true
  27991. });
  27992. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  27993. get: function () {
  27994. return Animation._ANIMATIONTYPE_COLOR3;
  27995. },
  27996. enumerable: true,
  27997. configurable: true
  27998. });
  27999. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  28000. get: function () {
  28001. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  28002. },
  28003. enumerable: true,
  28004. configurable: true
  28005. });
  28006. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  28007. get: function () {
  28008. return Animation._ANIMATIONLOOPMODE_CYCLE;
  28009. },
  28010. enumerable: true,
  28011. configurable: true
  28012. });
  28013. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  28014. get: function () {
  28015. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  28016. },
  28017. enumerable: true,
  28018. configurable: true
  28019. });
  28020. Animation.Parse = function (parsedAnimation) {
  28021. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  28022. var dataType = parsedAnimation.dataType;
  28023. var keys = [];
  28024. var data;
  28025. var index;
  28026. for (index = 0; index < parsedAnimation.keys.length; index++) {
  28027. var key = parsedAnimation.keys[index];
  28028. switch (dataType) {
  28029. case Animation.ANIMATIONTYPE_FLOAT:
  28030. data = key.values[0];
  28031. break;
  28032. case Animation.ANIMATIONTYPE_QUATERNION:
  28033. data = BABYLON.Quaternion.FromArray(key.values);
  28034. break;
  28035. case Animation.ANIMATIONTYPE_MATRIX:
  28036. data = BABYLON.Matrix.FromArray(key.values);
  28037. break;
  28038. case Animation.ANIMATIONTYPE_COLOR3:
  28039. data = BABYLON.Color3.FromArray(key.values);
  28040. break;
  28041. case Animation.ANIMATIONTYPE_VECTOR3:
  28042. default:
  28043. data = BABYLON.Vector3.FromArray(key.values);
  28044. break;
  28045. }
  28046. keys.push({
  28047. frame: key.frame,
  28048. value: data
  28049. });
  28050. }
  28051. animation.setKeys(keys);
  28052. if (parsedAnimation.ranges) {
  28053. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  28054. data = parsedAnimation.ranges[index];
  28055. animation.createRange(data.name, data.from, data.to);
  28056. }
  28057. }
  28058. return animation;
  28059. };
  28060. Animation.AppendSerializedAnimations = function (source, destination) {
  28061. if (source.animations) {
  28062. destination.animations = [];
  28063. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  28064. var animation = source.animations[animationIndex];
  28065. destination.animations.push(animation.serialize());
  28066. }
  28067. }
  28068. };
  28069. // Statics
  28070. Animation._ANIMATIONTYPE_FLOAT = 0;
  28071. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  28072. Animation._ANIMATIONTYPE_QUATERNION = 2;
  28073. Animation._ANIMATIONTYPE_MATRIX = 3;
  28074. Animation._ANIMATIONTYPE_COLOR3 = 4;
  28075. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  28076. Animation._ANIMATIONTYPE_SIZE = 6;
  28077. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  28078. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  28079. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  28080. return Animation;
  28081. })();
  28082. BABYLON.Animation = Animation;
  28083. })(BABYLON || (BABYLON = {}));
  28084. var BABYLON;
  28085. (function (BABYLON) {
  28086. var Animatable = (function () {
  28087. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  28088. if (fromFrame === void 0) { fromFrame = 0; }
  28089. if (toFrame === void 0) { toFrame = 100; }
  28090. if (loopAnimation === void 0) { loopAnimation = false; }
  28091. if (speedRatio === void 0) { speedRatio = 1.0; }
  28092. this.target = target;
  28093. this.fromFrame = fromFrame;
  28094. this.toFrame = toFrame;
  28095. this.loopAnimation = loopAnimation;
  28096. this.speedRatio = speedRatio;
  28097. this.onAnimationEnd = onAnimationEnd;
  28098. this._animations = new Array();
  28099. this._paused = false;
  28100. this.animationStarted = false;
  28101. if (animations) {
  28102. this.appendAnimations(target, animations);
  28103. }
  28104. this._scene = scene;
  28105. scene._activeAnimatables.push(this);
  28106. }
  28107. // Methods
  28108. Animatable.prototype.getAnimations = function () {
  28109. return this._animations;
  28110. };
  28111. Animatable.prototype.appendAnimations = function (target, animations) {
  28112. for (var index = 0; index < animations.length; index++) {
  28113. var animation = animations[index];
  28114. animation._target = target;
  28115. this._animations.push(animation);
  28116. }
  28117. };
  28118. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  28119. var animations = this._animations;
  28120. for (var index = 0; index < animations.length; index++) {
  28121. if (animations[index].targetProperty === property) {
  28122. return animations[index];
  28123. }
  28124. }
  28125. return null;
  28126. };
  28127. Animatable.prototype.reset = function () {
  28128. var animations = this._animations;
  28129. for (var index = 0; index < animations.length; index++) {
  28130. animations[index].reset();
  28131. }
  28132. this._localDelayOffset = null;
  28133. this._pausedDelay = null;
  28134. };
  28135. Animatable.prototype.enableBlending = function (blendingSpeed) {
  28136. var animations = this._animations;
  28137. for (var index = 0; index < animations.length; index++) {
  28138. animations[index].enableBlending = true;
  28139. animations[index].blendingSpeed = blendingSpeed;
  28140. }
  28141. };
  28142. Animatable.prototype.disableBlending = function () {
  28143. var animations = this._animations;
  28144. for (var index = 0; index < animations.length; index++) {
  28145. animations[index].enableBlending = false;
  28146. }
  28147. };
  28148. Animatable.prototype.goToFrame = function (frame) {
  28149. var animations = this._animations;
  28150. for (var index = 0; index < animations.length; index++) {
  28151. animations[index].goToFrame(frame);
  28152. }
  28153. };
  28154. Animatable.prototype.pause = function () {
  28155. if (this._paused) {
  28156. return;
  28157. }
  28158. this._paused = true;
  28159. };
  28160. Animatable.prototype.restart = function () {
  28161. this._paused = false;
  28162. };
  28163. Animatable.prototype.stop = function () {
  28164. var index = this._scene._activeAnimatables.indexOf(this);
  28165. if (index > -1) {
  28166. this._scene._activeAnimatables.splice(index, 1);
  28167. var animations = this._animations;
  28168. for (var index = 0; index < animations.length; index++) {
  28169. animations[index].reset();
  28170. }
  28171. if (this.onAnimationEnd) {
  28172. this.onAnimationEnd();
  28173. }
  28174. }
  28175. };
  28176. Animatable.prototype._animate = function (delay) {
  28177. if (this._paused) {
  28178. this.animationStarted = false;
  28179. if (!this._pausedDelay) {
  28180. this._pausedDelay = delay;
  28181. }
  28182. return true;
  28183. }
  28184. if (!this._localDelayOffset) {
  28185. this._localDelayOffset = delay;
  28186. }
  28187. else if (this._pausedDelay) {
  28188. this._localDelayOffset += delay - this._pausedDelay;
  28189. this._pausedDelay = null;
  28190. }
  28191. // Animating
  28192. var running = false;
  28193. var animations = this._animations;
  28194. var index;
  28195. for (index = 0; index < animations.length; index++) {
  28196. var animation = animations[index];
  28197. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  28198. running = running || isRunning;
  28199. }
  28200. this.animationStarted = running;
  28201. if (!running) {
  28202. // Remove from active animatables
  28203. index = this._scene._activeAnimatables.indexOf(this);
  28204. this._scene._activeAnimatables.splice(index, 1);
  28205. }
  28206. if (!running && this.onAnimationEnd) {
  28207. this.onAnimationEnd();
  28208. this.onAnimationEnd = null;
  28209. }
  28210. return running;
  28211. };
  28212. return Animatable;
  28213. })();
  28214. BABYLON.Animatable = Animatable;
  28215. })(BABYLON || (BABYLON = {}));
  28216. var BABYLON;
  28217. (function (BABYLON) {
  28218. var EasingFunction = (function () {
  28219. function EasingFunction() {
  28220. // Properties
  28221. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  28222. }
  28223. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  28224. get: function () {
  28225. return EasingFunction._EASINGMODE_EASEIN;
  28226. },
  28227. enumerable: true,
  28228. configurable: true
  28229. });
  28230. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  28231. get: function () {
  28232. return EasingFunction._EASINGMODE_EASEOUT;
  28233. },
  28234. enumerable: true,
  28235. configurable: true
  28236. });
  28237. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  28238. get: function () {
  28239. return EasingFunction._EASINGMODE_EASEINOUT;
  28240. },
  28241. enumerable: true,
  28242. configurable: true
  28243. });
  28244. EasingFunction.prototype.setEasingMode = function (easingMode) {
  28245. var n = Math.min(Math.max(easingMode, 0), 2);
  28246. this._easingMode = n;
  28247. };
  28248. EasingFunction.prototype.getEasingMode = function () {
  28249. return this._easingMode;
  28250. };
  28251. EasingFunction.prototype.easeInCore = function (gradient) {
  28252. throw new Error('You must implement this method');
  28253. };
  28254. EasingFunction.prototype.ease = function (gradient) {
  28255. switch (this._easingMode) {
  28256. case EasingFunction.EASINGMODE_EASEIN:
  28257. return this.easeInCore(gradient);
  28258. case EasingFunction.EASINGMODE_EASEOUT:
  28259. return (1 - this.easeInCore(1 - gradient));
  28260. }
  28261. if (gradient >= 0.5) {
  28262. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  28263. }
  28264. return (this.easeInCore(gradient * 2) * 0.5);
  28265. };
  28266. //Statics
  28267. EasingFunction._EASINGMODE_EASEIN = 0;
  28268. EasingFunction._EASINGMODE_EASEOUT = 1;
  28269. EasingFunction._EASINGMODE_EASEINOUT = 2;
  28270. return EasingFunction;
  28271. })();
  28272. BABYLON.EasingFunction = EasingFunction;
  28273. var CircleEase = (function (_super) {
  28274. __extends(CircleEase, _super);
  28275. function CircleEase() {
  28276. _super.apply(this, arguments);
  28277. }
  28278. CircleEase.prototype.easeInCore = function (gradient) {
  28279. gradient = Math.max(0, Math.min(1, gradient));
  28280. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  28281. };
  28282. return CircleEase;
  28283. })(EasingFunction);
  28284. BABYLON.CircleEase = CircleEase;
  28285. var BackEase = (function (_super) {
  28286. __extends(BackEase, _super);
  28287. function BackEase(amplitude) {
  28288. if (amplitude === void 0) { amplitude = 1; }
  28289. _super.call(this);
  28290. this.amplitude = amplitude;
  28291. }
  28292. BackEase.prototype.easeInCore = function (gradient) {
  28293. var num = Math.max(0, this.amplitude);
  28294. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  28295. };
  28296. return BackEase;
  28297. })(EasingFunction);
  28298. BABYLON.BackEase = BackEase;
  28299. var BounceEase = (function (_super) {
  28300. __extends(BounceEase, _super);
  28301. function BounceEase(bounces, bounciness) {
  28302. if (bounces === void 0) { bounces = 3; }
  28303. if (bounciness === void 0) { bounciness = 2; }
  28304. _super.call(this);
  28305. this.bounces = bounces;
  28306. this.bounciness = bounciness;
  28307. }
  28308. BounceEase.prototype.easeInCore = function (gradient) {
  28309. var y = Math.max(0.0, this.bounces);
  28310. var bounciness = this.bounciness;
  28311. if (bounciness <= 1.0) {
  28312. bounciness = 1.001;
  28313. }
  28314. var num9 = Math.pow(bounciness, y);
  28315. var num5 = 1.0 - bounciness;
  28316. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  28317. var num15 = gradient * num4;
  28318. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  28319. var num3 = Math.floor(num65);
  28320. var num13 = num3 + 1.0;
  28321. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  28322. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  28323. var num7 = (num8 + num12) * 0.5;
  28324. var num6 = gradient - num7;
  28325. var num2 = num7 - num8;
  28326. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  28327. };
  28328. return BounceEase;
  28329. })(EasingFunction);
  28330. BABYLON.BounceEase = BounceEase;
  28331. var CubicEase = (function (_super) {
  28332. __extends(CubicEase, _super);
  28333. function CubicEase() {
  28334. _super.apply(this, arguments);
  28335. }
  28336. CubicEase.prototype.easeInCore = function (gradient) {
  28337. return (gradient * gradient * gradient);
  28338. };
  28339. return CubicEase;
  28340. })(EasingFunction);
  28341. BABYLON.CubicEase = CubicEase;
  28342. var ElasticEase = (function (_super) {
  28343. __extends(ElasticEase, _super);
  28344. function ElasticEase(oscillations, springiness) {
  28345. if (oscillations === void 0) { oscillations = 3; }
  28346. if (springiness === void 0) { springiness = 3; }
  28347. _super.call(this);
  28348. this.oscillations = oscillations;
  28349. this.springiness = springiness;
  28350. }
  28351. ElasticEase.prototype.easeInCore = function (gradient) {
  28352. var num2;
  28353. var num3 = Math.max(0.0, this.oscillations);
  28354. var num = Math.max(0.0, this.springiness);
  28355. if (num == 0) {
  28356. num2 = gradient;
  28357. }
  28358. else {
  28359. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  28360. }
  28361. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  28362. };
  28363. return ElasticEase;
  28364. })(EasingFunction);
  28365. BABYLON.ElasticEase = ElasticEase;
  28366. var ExponentialEase = (function (_super) {
  28367. __extends(ExponentialEase, _super);
  28368. function ExponentialEase(exponent) {
  28369. if (exponent === void 0) { exponent = 2; }
  28370. _super.call(this);
  28371. this.exponent = exponent;
  28372. }
  28373. ExponentialEase.prototype.easeInCore = function (gradient) {
  28374. if (this.exponent <= 0) {
  28375. return gradient;
  28376. }
  28377. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  28378. };
  28379. return ExponentialEase;
  28380. })(EasingFunction);
  28381. BABYLON.ExponentialEase = ExponentialEase;
  28382. var PowerEase = (function (_super) {
  28383. __extends(PowerEase, _super);
  28384. function PowerEase(power) {
  28385. if (power === void 0) { power = 2; }
  28386. _super.call(this);
  28387. this.power = power;
  28388. }
  28389. PowerEase.prototype.easeInCore = function (gradient) {
  28390. var y = Math.max(0.0, this.power);
  28391. return Math.pow(gradient, y);
  28392. };
  28393. return PowerEase;
  28394. })(EasingFunction);
  28395. BABYLON.PowerEase = PowerEase;
  28396. var QuadraticEase = (function (_super) {
  28397. __extends(QuadraticEase, _super);
  28398. function QuadraticEase() {
  28399. _super.apply(this, arguments);
  28400. }
  28401. QuadraticEase.prototype.easeInCore = function (gradient) {
  28402. return (gradient * gradient);
  28403. };
  28404. return QuadraticEase;
  28405. })(EasingFunction);
  28406. BABYLON.QuadraticEase = QuadraticEase;
  28407. var QuarticEase = (function (_super) {
  28408. __extends(QuarticEase, _super);
  28409. function QuarticEase() {
  28410. _super.apply(this, arguments);
  28411. }
  28412. QuarticEase.prototype.easeInCore = function (gradient) {
  28413. return (gradient * gradient * gradient * gradient);
  28414. };
  28415. return QuarticEase;
  28416. })(EasingFunction);
  28417. BABYLON.QuarticEase = QuarticEase;
  28418. var QuinticEase = (function (_super) {
  28419. __extends(QuinticEase, _super);
  28420. function QuinticEase() {
  28421. _super.apply(this, arguments);
  28422. }
  28423. QuinticEase.prototype.easeInCore = function (gradient) {
  28424. return (gradient * gradient * gradient * gradient * gradient);
  28425. };
  28426. return QuinticEase;
  28427. })(EasingFunction);
  28428. BABYLON.QuinticEase = QuinticEase;
  28429. var SineEase = (function (_super) {
  28430. __extends(SineEase, _super);
  28431. function SineEase() {
  28432. _super.apply(this, arguments);
  28433. }
  28434. SineEase.prototype.easeInCore = function (gradient) {
  28435. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  28436. };
  28437. return SineEase;
  28438. })(EasingFunction);
  28439. BABYLON.SineEase = SineEase;
  28440. var BezierCurveEase = (function (_super) {
  28441. __extends(BezierCurveEase, _super);
  28442. function BezierCurveEase(x1, y1, x2, y2) {
  28443. if (x1 === void 0) { x1 = 0; }
  28444. if (y1 === void 0) { y1 = 0; }
  28445. if (x2 === void 0) { x2 = 1; }
  28446. if (y2 === void 0) { y2 = 1; }
  28447. _super.call(this);
  28448. this.x1 = x1;
  28449. this.y1 = y1;
  28450. this.x2 = x2;
  28451. this.y2 = y2;
  28452. }
  28453. BezierCurveEase.prototype.easeInCore = function (gradient) {
  28454. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  28455. };
  28456. return BezierCurveEase;
  28457. })(EasingFunction);
  28458. BABYLON.BezierCurveEase = BezierCurveEase;
  28459. })(BABYLON || (BABYLON = {}));
  28460. var BABYLON;
  28461. (function (BABYLON) {
  28462. var Bone = (function (_super) {
  28463. __extends(Bone, _super);
  28464. function Bone(name, skeleton, parentBone, matrix, restPose) {
  28465. _super.call(this, name, skeleton.getScene());
  28466. this.name = name;
  28467. this.children = new Array();
  28468. this.animations = new Array();
  28469. this._worldTransform = new BABYLON.Matrix();
  28470. this._absoluteTransform = new BABYLON.Matrix();
  28471. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  28472. this._skeleton = skeleton;
  28473. this._matrix = matrix;
  28474. this._baseMatrix = matrix;
  28475. this._restPose = restPose ? restPose : matrix.clone();
  28476. skeleton.bones.push(this);
  28477. if (parentBone) {
  28478. this._parent = parentBone;
  28479. parentBone.children.push(this);
  28480. }
  28481. else {
  28482. this._parent = null;
  28483. }
  28484. this._updateDifferenceMatrix();
  28485. }
  28486. // Members
  28487. Bone.prototype.getParent = function () {
  28488. return this._parent;
  28489. };
  28490. Bone.prototype.getLocalMatrix = function () {
  28491. return this._matrix;
  28492. };
  28493. Bone.prototype.getBaseMatrix = function () {
  28494. return this._baseMatrix;
  28495. };
  28496. Bone.prototype.getRestPose = function () {
  28497. return this._restPose;
  28498. };
  28499. Bone.prototype.returnToRest = function () {
  28500. this.updateMatrix(this._restPose.clone());
  28501. };
  28502. Bone.prototype.getWorldMatrix = function () {
  28503. return this._worldTransform;
  28504. };
  28505. Bone.prototype.getInvertedAbsoluteTransform = function () {
  28506. return this._invertedAbsoluteTransform;
  28507. };
  28508. Bone.prototype.getAbsoluteTransform = function () {
  28509. return this._absoluteTransform;
  28510. };
  28511. // Methods
  28512. Bone.prototype.updateMatrix = function (matrix) {
  28513. this._baseMatrix = matrix.clone();
  28514. this._matrix = matrix.clone();
  28515. this._skeleton._markAsDirty();
  28516. this._updateDifferenceMatrix();
  28517. };
  28518. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  28519. if (!rootMatrix) {
  28520. rootMatrix = this._baseMatrix;
  28521. }
  28522. if (this._parent) {
  28523. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  28524. }
  28525. else {
  28526. this._absoluteTransform.copyFrom(rootMatrix);
  28527. }
  28528. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  28529. for (var index = 0; index < this.children.length; index++) {
  28530. this.children[index]._updateDifferenceMatrix();
  28531. }
  28532. };
  28533. Bone.prototype.markAsDirty = function () {
  28534. this._currentRenderId++;
  28535. this._skeleton._markAsDirty();
  28536. };
  28537. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  28538. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  28539. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  28540. // all animation may be coming from a library skeleton, so may need to create animation
  28541. if (this.animations.length === 0) {
  28542. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  28543. this.animations[0].setKeys([]);
  28544. }
  28545. // get animation info / verify there is such a range from the source bone
  28546. var sourceRange = source.animations[0].getRange(rangeName);
  28547. if (!sourceRange) {
  28548. return false;
  28549. }
  28550. var from = sourceRange.from;
  28551. var to = sourceRange.to;
  28552. var sourceKeys = source.animations[0].getKeys();
  28553. // rescaling prep
  28554. var sourceBoneLength = source.length;
  28555. var sourceParent = source.getParent();
  28556. var parent = this.getParent();
  28557. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  28558. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  28559. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  28560. var destKeys = this.animations[0].getKeys();
  28561. // loop vars declaration
  28562. var orig;
  28563. var origTranslation;
  28564. var mat;
  28565. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  28566. orig = sourceKeys[key];
  28567. if (orig.frame >= from && orig.frame <= to) {
  28568. if (rescaleAsRequired) {
  28569. mat = orig.value.clone();
  28570. // scale based on parent ratio, when bone has parent
  28571. if (parentScalingReqd) {
  28572. origTranslation = mat.getTranslation();
  28573. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  28574. }
  28575. else if (dimensionsScalingReqd) {
  28576. origTranslation = mat.getTranslation();
  28577. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  28578. }
  28579. else {
  28580. mat = orig.value;
  28581. }
  28582. }
  28583. else {
  28584. mat = orig.value;
  28585. }
  28586. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  28587. }
  28588. }
  28589. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  28590. return true;
  28591. };
  28592. return Bone;
  28593. })(BABYLON.Node);
  28594. BABYLON.Bone = Bone;
  28595. })(BABYLON || (BABYLON = {}));
  28596. var BABYLON;
  28597. (function (BABYLON) {
  28598. var Skeleton = (function () {
  28599. function Skeleton(name, id, scene) {
  28600. this.name = name;
  28601. this.id = id;
  28602. this.bones = new Array();
  28603. this.needInitialSkinMatrix = false;
  28604. this._isDirty = true;
  28605. this._meshesWithPoseMatrix = new Array();
  28606. this._identity = BABYLON.Matrix.Identity();
  28607. this._ranges = {};
  28608. this.bones = [];
  28609. this._scene = scene;
  28610. scene.skeletons.push(this);
  28611. //make sure it will recalculate the matrix next time prepare is called.
  28612. this._isDirty = true;
  28613. }
  28614. // Members
  28615. Skeleton.prototype.getTransformMatrices = function (mesh) {
  28616. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  28617. return mesh._bonesTransformMatrices;
  28618. }
  28619. return this._transformMatrices;
  28620. };
  28621. Skeleton.prototype.getScene = function () {
  28622. return this._scene;
  28623. };
  28624. // Methods
  28625. /**
  28626. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28627. */
  28628. Skeleton.prototype.toString = function (fullDetails) {
  28629. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  28630. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  28631. if (fullDetails) {
  28632. ret += ", Ranges: {";
  28633. var first = true;
  28634. for (var name_1 in this._ranges) {
  28635. if (first) {
  28636. ret += ", ";
  28637. first = false;
  28638. }
  28639. ret += name_1;
  28640. }
  28641. ret += "}";
  28642. }
  28643. return ret;
  28644. };
  28645. /**
  28646. * Get bone's index searching by name
  28647. * @param {string} name is bone's name to search for
  28648. * @return {number} Indice of the bone. Returns -1 if not found
  28649. */
  28650. Skeleton.prototype.getBoneIndexByName = function (name) {
  28651. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  28652. if (this.bones[boneIndex].name === name) {
  28653. return boneIndex;
  28654. }
  28655. }
  28656. return -1;
  28657. };
  28658. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  28659. // check name not already in use
  28660. if (!this._ranges[name]) {
  28661. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  28662. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28663. if (this.bones[i].animations[0]) {
  28664. this.bones[i].animations[0].createRange(name, from, to);
  28665. }
  28666. }
  28667. }
  28668. };
  28669. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  28670. if (deleteFrames === void 0) { deleteFrames = true; }
  28671. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28672. if (this.bones[i].animations[0]) {
  28673. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  28674. }
  28675. }
  28676. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  28677. };
  28678. Skeleton.prototype.getAnimationRange = function (name) {
  28679. return this._ranges[name];
  28680. };
  28681. /**
  28682. * Returns as an Array, all AnimationRanges defined on this skeleton
  28683. */
  28684. Skeleton.prototype.getAnimationRanges = function () {
  28685. var animationRanges = [];
  28686. var name;
  28687. var i = 0;
  28688. for (name in this._ranges) {
  28689. animationRanges[i] = this._ranges[name];
  28690. i++;
  28691. }
  28692. return animationRanges;
  28693. };
  28694. /**
  28695. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  28696. */
  28697. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  28698. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  28699. if (this._ranges[name] || !source.getAnimationRange(name)) {
  28700. return false;
  28701. }
  28702. var ret = true;
  28703. var frameOffset = this._getHighestAnimationFrame() + 1;
  28704. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  28705. var boneDict = {};
  28706. var sourceBones = source.bones;
  28707. var nBones;
  28708. var i;
  28709. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  28710. boneDict[sourceBones[i].name] = sourceBones[i];
  28711. }
  28712. if (this.bones.length !== sourceBones.length) {
  28713. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  28714. ret = false;
  28715. }
  28716. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  28717. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  28718. var boneName = this.bones[i].name;
  28719. var sourceBone = boneDict[boneName];
  28720. if (sourceBone) {
  28721. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  28722. }
  28723. else {
  28724. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  28725. ret = false;
  28726. }
  28727. }
  28728. // do not call createAnimationRange(), since it also is done to bones, which was already done
  28729. var range = source.getAnimationRange(name);
  28730. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  28731. return ret;
  28732. };
  28733. Skeleton.prototype.returnToRest = function () {
  28734. for (var index = 0; index < this.bones.length; index++) {
  28735. this.bones[index].returnToRest();
  28736. }
  28737. };
  28738. Skeleton.prototype._getHighestAnimationFrame = function () {
  28739. var ret = 0;
  28740. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28741. if (this.bones[i].animations[0]) {
  28742. var highest = this.bones[i].animations[0].getHighestFrame();
  28743. if (ret < highest) {
  28744. ret = highest;
  28745. }
  28746. }
  28747. }
  28748. return ret;
  28749. };
  28750. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  28751. var range = this.getAnimationRange(name);
  28752. if (!range) {
  28753. return null;
  28754. }
  28755. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  28756. };
  28757. Skeleton.prototype._markAsDirty = function () {
  28758. this._isDirty = true;
  28759. };
  28760. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  28761. this._meshesWithPoseMatrix.push(mesh);
  28762. };
  28763. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  28764. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  28765. if (index > -1) {
  28766. this._meshesWithPoseMatrix.splice(index, 1);
  28767. }
  28768. };
  28769. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  28770. for (var index = 0; index < this.bones.length; index++) {
  28771. var bone = this.bones[index];
  28772. var parentBone = bone.getParent();
  28773. if (parentBone) {
  28774. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  28775. }
  28776. else {
  28777. if (initialSkinMatrix) {
  28778. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  28779. }
  28780. else {
  28781. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  28782. }
  28783. }
  28784. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  28785. }
  28786. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  28787. };
  28788. Skeleton.prototype.prepare = function () {
  28789. if (!this._isDirty) {
  28790. return;
  28791. }
  28792. if (this.needInitialSkinMatrix) {
  28793. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  28794. var mesh = this._meshesWithPoseMatrix[index];
  28795. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  28796. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  28797. }
  28798. var poseMatrix = mesh.getPoseMatrix();
  28799. // Prepare bones
  28800. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  28801. var bone = this.bones[boneIndex];
  28802. if (!bone.getParent()) {
  28803. var matrix = bone.getBaseMatrix();
  28804. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  28805. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  28806. }
  28807. }
  28808. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  28809. }
  28810. }
  28811. else {
  28812. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  28813. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  28814. }
  28815. this._computeTransformMatrices(this._transformMatrices, null);
  28816. }
  28817. this._isDirty = false;
  28818. this._scene._activeBones.addCount(this.bones.length, false);
  28819. };
  28820. Skeleton.prototype.getAnimatables = function () {
  28821. if (!this._animatables || this._animatables.length !== this.bones.length) {
  28822. this._animatables = [];
  28823. for (var index = 0; index < this.bones.length; index++) {
  28824. this._animatables.push(this.bones[index]);
  28825. }
  28826. }
  28827. return this._animatables;
  28828. };
  28829. Skeleton.prototype.clone = function (name, id) {
  28830. var result = new Skeleton(name, id || name, this._scene);
  28831. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  28832. for (var index = 0; index < this.bones.length; index++) {
  28833. var source = this.bones[index];
  28834. var parentBone = null;
  28835. if (source.getParent()) {
  28836. var parentIndex = this.bones.indexOf(source.getParent());
  28837. parentBone = result.bones[parentIndex];
  28838. }
  28839. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  28840. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  28841. }
  28842. if (this._ranges) {
  28843. result._ranges = {};
  28844. for (var rangeName in this._ranges) {
  28845. result._ranges[rangeName] = this._ranges[rangeName].clone();
  28846. }
  28847. }
  28848. this._isDirty = true;
  28849. return result;
  28850. };
  28851. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  28852. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  28853. this.bones.forEach(function (bone) {
  28854. bone.animations.forEach(function (animation) {
  28855. animation.enableBlending = true;
  28856. animation.blendingSpeed = blendingSpeed;
  28857. });
  28858. });
  28859. };
  28860. Skeleton.prototype.dispose = function () {
  28861. this._meshesWithPoseMatrix = [];
  28862. // Animations
  28863. this.getScene().stopAnimation(this);
  28864. // Remove from scene
  28865. this.getScene().removeSkeleton(this);
  28866. };
  28867. Skeleton.prototype.serialize = function () {
  28868. var serializationObject = {};
  28869. serializationObject.name = this.name;
  28870. serializationObject.id = this.id;
  28871. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  28872. serializationObject.bones = [];
  28873. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  28874. for (var index = 0; index < this.bones.length; index++) {
  28875. var bone = this.bones[index];
  28876. var serializedBone = {
  28877. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  28878. name: bone.name,
  28879. matrix: bone.getLocalMatrix().toArray(),
  28880. rest: bone.getRestPose().toArray()
  28881. };
  28882. serializationObject.bones.push(serializedBone);
  28883. if (bone.length) {
  28884. serializedBone.length = bone.length;
  28885. }
  28886. if (bone.animations && bone.animations.length > 0) {
  28887. serializedBone.animation = bone.animations[0].serialize();
  28888. }
  28889. serializationObject.ranges = [];
  28890. for (var name in this._ranges) {
  28891. var range = {};
  28892. range.name = name;
  28893. range.from = this._ranges[name].from;
  28894. range.to = this._ranges[name].to;
  28895. serializationObject.ranges.push(range);
  28896. }
  28897. }
  28898. return serializationObject;
  28899. };
  28900. Skeleton.Parse = function (parsedSkeleton, scene) {
  28901. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  28902. if (parsedSkeleton.dimensionsAtRest) {
  28903. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  28904. }
  28905. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  28906. var index;
  28907. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  28908. var parsedBone = parsedSkeleton.bones[index];
  28909. var parentBone = null;
  28910. if (parsedBone.parentBoneIndex > -1) {
  28911. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  28912. }
  28913. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  28914. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  28915. if (parsedBone.length) {
  28916. bone.length = parsedBone.length;
  28917. }
  28918. if (parsedBone.animation) {
  28919. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  28920. }
  28921. }
  28922. // placed after bones, so createAnimationRange can cascade down
  28923. if (parsedSkeleton.ranges) {
  28924. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  28925. var data = parsedSkeleton.ranges[index];
  28926. skeleton.createAnimationRange(data.name, data.from, data.to);
  28927. }
  28928. }
  28929. return skeleton;
  28930. };
  28931. return Skeleton;
  28932. })();
  28933. BABYLON.Skeleton = Skeleton;
  28934. })(BABYLON || (BABYLON = {}));
  28935. var BABYLON;
  28936. (function (BABYLON) {
  28937. var PostProcess = (function () {
  28938. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  28939. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  28940. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  28941. this.name = name;
  28942. this.width = -1;
  28943. this.height = -1;
  28944. /*
  28945. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  28946. Can only be used on a single postprocess or on the last one of a chain.
  28947. */
  28948. this.enablePixelPerfectMode = false;
  28949. this._reusable = false;
  28950. this._textures = new BABYLON.SmartArray(2);
  28951. this._currentRenderTextureInd = 0;
  28952. this._scaleRatio = new BABYLON.Vector2(1, 1);
  28953. // Events
  28954. /**
  28955. * An event triggered when the postprocess is activated.
  28956. * @type {BABYLON.Observable}
  28957. */
  28958. this.onActivateObservable = new BABYLON.Observable();
  28959. /**
  28960. * An event triggered when the postprocess changes its size.
  28961. * @type {BABYLON.Observable}
  28962. */
  28963. this.onSizeChangedObservable = new BABYLON.Observable();
  28964. /**
  28965. * An event triggered when the postprocess applies its effect.
  28966. * @type {BABYLON.Observable}
  28967. */
  28968. this.onApplyObservable = new BABYLON.Observable();
  28969. /**
  28970. * An event triggered before rendering the postprocess
  28971. * @type {BABYLON.Observable}
  28972. */
  28973. this.onBeforeRenderObservable = new BABYLON.Observable();
  28974. /**
  28975. * An event triggered after rendering the postprocess
  28976. * @type {BABYLON.Observable}
  28977. */
  28978. this.onAfterRenderObservable = new BABYLON.Observable();
  28979. if (camera != null) {
  28980. this._camera = camera;
  28981. this._scene = camera.getScene();
  28982. camera.attachPostProcess(this);
  28983. this._engine = this._scene.getEngine();
  28984. }
  28985. else {
  28986. this._engine = engine;
  28987. }
  28988. this._options = options;
  28989. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  28990. this._reusable = reusable || false;
  28991. this._textureType = textureType;
  28992. this._samplers = samplers || [];
  28993. this._samplers.push("textureSampler");
  28994. this._fragmentUrl = fragmentUrl;
  28995. this._parameters = parameters || [];
  28996. this._parameters.push("scale");
  28997. this.updateEffect(defines);
  28998. }
  28999. Object.defineProperty(PostProcess.prototype, "onActivate", {
  29000. set: function (callback) {
  29001. if (this._onActivateObserver) {
  29002. this.onActivateObservable.remove(this._onActivateObserver);
  29003. }
  29004. this._onActivateObserver = this.onActivateObservable.add(callback);
  29005. },
  29006. enumerable: true,
  29007. configurable: true
  29008. });
  29009. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  29010. set: function (callback) {
  29011. if (this._onSizeChangedObserver) {
  29012. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  29013. }
  29014. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  29015. },
  29016. enumerable: true,
  29017. configurable: true
  29018. });
  29019. Object.defineProperty(PostProcess.prototype, "onApply", {
  29020. set: function (callback) {
  29021. if (this._onApplyObserver) {
  29022. this.onApplyObservable.remove(this._onApplyObserver);
  29023. }
  29024. this._onApplyObserver = this.onApplyObservable.add(callback);
  29025. },
  29026. enumerable: true,
  29027. configurable: true
  29028. });
  29029. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  29030. set: function (callback) {
  29031. if (this._onBeforeRenderObserver) {
  29032. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  29033. }
  29034. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  29035. },
  29036. enumerable: true,
  29037. configurable: true
  29038. });
  29039. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  29040. set: function (callback) {
  29041. if (this._onAfterRenderObserver) {
  29042. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  29043. }
  29044. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  29045. },
  29046. enumerable: true,
  29047. configurable: true
  29048. });
  29049. PostProcess.prototype.updateEffect = function (defines) {
  29050. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  29051. };
  29052. PostProcess.prototype.isReusable = function () {
  29053. return this._reusable;
  29054. };
  29055. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  29056. PostProcess.prototype.markTextureDirty = function () {
  29057. this.width = -1;
  29058. };
  29059. PostProcess.prototype.activate = function (camera, sourceTexture) {
  29060. camera = camera || this._camera;
  29061. var scene = camera.getScene();
  29062. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  29063. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  29064. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  29065. var desiredWidth = this._options.width || requiredWidth;
  29066. var desiredHeight = this._options.height || requiredHeight;
  29067. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  29068. if (!this._options.width) {
  29069. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  29070. }
  29071. if (!this._options.height) {
  29072. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  29073. }
  29074. }
  29075. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  29076. if (this._textures.length > 0) {
  29077. for (var i = 0; i < this._textures.length; i++) {
  29078. this._engine._releaseTexture(this._textures.data[i]);
  29079. }
  29080. this._textures.reset();
  29081. }
  29082. this.width = desiredWidth;
  29083. this.height = desiredHeight;
  29084. var textureSize = { width: this.width, height: this.height };
  29085. var textureOptions = {
  29086. generateMipMaps: false,
  29087. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  29088. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  29089. samplingMode: this.renderTargetSamplingMode,
  29090. type: this._textureType
  29091. };
  29092. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  29093. if (this._reusable) {
  29094. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  29095. }
  29096. this.onSizeChangedObservable.notifyObservers(this);
  29097. }
  29098. if (this.enablePixelPerfectMode) {
  29099. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  29100. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  29101. }
  29102. else {
  29103. this._scaleRatio.copyFromFloats(1, 1);
  29104. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  29105. }
  29106. this.onActivateObservable.notifyObservers(camera);
  29107. // Clear
  29108. if (this.clearColor) {
  29109. this._engine.clear(this.clearColor, true, true, true);
  29110. }
  29111. else {
  29112. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  29113. }
  29114. if (this._reusable) {
  29115. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  29116. }
  29117. };
  29118. Object.defineProperty(PostProcess.prototype, "isSupported", {
  29119. get: function () {
  29120. return this._effect.isSupported;
  29121. },
  29122. enumerable: true,
  29123. configurable: true
  29124. });
  29125. PostProcess.prototype.apply = function () {
  29126. // Check
  29127. if (!this._effect.isReady())
  29128. return null;
  29129. // States
  29130. this._engine.enableEffect(this._effect);
  29131. this._engine.setState(false);
  29132. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29133. this._engine.setDepthBuffer(false);
  29134. this._engine.setDepthWrite(false);
  29135. // Texture
  29136. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  29137. // Parameters
  29138. this._effect.setVector2("scale", this._scaleRatio);
  29139. this.onApplyObservable.notifyObservers(this._effect);
  29140. return this._effect;
  29141. };
  29142. PostProcess.prototype.dispose = function (camera) {
  29143. camera = camera || this._camera;
  29144. if (this._textures.length > 0) {
  29145. for (var i = 0; i < this._textures.length; i++) {
  29146. this._engine._releaseTexture(this._textures.data[i]);
  29147. }
  29148. this._textures.reset();
  29149. }
  29150. if (!camera) {
  29151. return;
  29152. }
  29153. camera.detachPostProcess(this);
  29154. var index = camera._postProcesses.indexOf(this);
  29155. if (index === 0 && camera._postProcesses.length > 0) {
  29156. this._camera._postProcesses[0].markTextureDirty();
  29157. }
  29158. this.onActivateObservable.clear();
  29159. this.onAfterRenderObservable.clear();
  29160. this.onApplyObservable.clear();
  29161. this.onBeforeRenderObservable.clear();
  29162. this.onSizeChangedObservable.clear();
  29163. };
  29164. return PostProcess;
  29165. })();
  29166. BABYLON.PostProcess = PostProcess;
  29167. })(BABYLON || (BABYLON = {}));
  29168. var BABYLON;
  29169. (function (BABYLON) {
  29170. var PostProcessManager = (function () {
  29171. function PostProcessManager(scene) {
  29172. this._vertexBuffers = {};
  29173. this._scene = scene;
  29174. }
  29175. PostProcessManager.prototype._prepareBuffers = function () {
  29176. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29177. return;
  29178. }
  29179. // VBO
  29180. var vertices = [];
  29181. vertices.push(1, 1);
  29182. vertices.push(-1, 1);
  29183. vertices.push(-1, -1);
  29184. vertices.push(1, -1);
  29185. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29186. // Indices
  29187. var indices = [];
  29188. indices.push(0);
  29189. indices.push(1);
  29190. indices.push(2);
  29191. indices.push(0);
  29192. indices.push(2);
  29193. indices.push(3);
  29194. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  29195. };
  29196. // Methods
  29197. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  29198. var postProcesses = this._scene.activeCamera._postProcesses;
  29199. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29200. return false;
  29201. }
  29202. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  29203. return true;
  29204. };
  29205. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  29206. var engine = this._scene.getEngine();
  29207. for (var index = 0; index < postProcesses.length; index++) {
  29208. if (index < postProcesses.length - 1) {
  29209. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29210. }
  29211. else {
  29212. if (targetTexture) {
  29213. engine.bindFramebuffer(targetTexture);
  29214. }
  29215. else {
  29216. engine.restoreDefaultFramebuffer();
  29217. }
  29218. }
  29219. var pp = postProcesses[index];
  29220. var effect = pp.apply();
  29221. if (effect) {
  29222. pp.onBeforeRenderObservable.notifyObservers(effect);
  29223. // VBOs
  29224. this._prepareBuffers();
  29225. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29226. // Draw order
  29227. engine.draw(true, 0, 6);
  29228. pp.onAfterRenderObservable.notifyObservers(effect);
  29229. }
  29230. }
  29231. // Restore depth buffer
  29232. engine.setDepthBuffer(true);
  29233. engine.setDepthWrite(true);
  29234. };
  29235. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  29236. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29237. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29238. return;
  29239. }
  29240. var engine = this._scene.getEngine();
  29241. for (var index = 0, len = postProcesses.length; index < len; index++) {
  29242. if (index < len - 1) {
  29243. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29244. }
  29245. else {
  29246. if (targetTexture) {
  29247. engine.bindFramebuffer(targetTexture, faceIndex);
  29248. }
  29249. else {
  29250. engine.restoreDefaultFramebuffer();
  29251. }
  29252. }
  29253. if (doNotPresent) {
  29254. break;
  29255. }
  29256. var pp = postProcesses[index];
  29257. var effect = pp.apply();
  29258. if (effect) {
  29259. pp.onBeforeRenderObservable.notifyObservers(effect);
  29260. // VBOs
  29261. this._prepareBuffers();
  29262. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29263. // Draw order
  29264. engine.draw(true, 0, 6);
  29265. pp.onAfterRenderObservable.notifyObservers(effect);
  29266. }
  29267. }
  29268. // Restore depth buffer
  29269. engine.setDepthBuffer(true);
  29270. engine.setDepthWrite(true);
  29271. };
  29272. PostProcessManager.prototype.dispose = function () {
  29273. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29274. if (buffer) {
  29275. buffer.dispose();
  29276. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29277. }
  29278. if (this._indexBuffer) {
  29279. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29280. this._indexBuffer = null;
  29281. }
  29282. };
  29283. return PostProcessManager;
  29284. })();
  29285. BABYLON.PostProcessManager = PostProcessManager;
  29286. })(BABYLON || (BABYLON = {}));
  29287. var BABYLON;
  29288. (function (BABYLON) {
  29289. var PassPostProcess = (function (_super) {
  29290. __extends(PassPostProcess, _super);
  29291. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  29292. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  29293. }
  29294. return PassPostProcess;
  29295. })(BABYLON.PostProcess);
  29296. BABYLON.PassPostProcess = PassPostProcess;
  29297. })(BABYLON || (BABYLON = {}));
  29298. var BABYLON;
  29299. (function (BABYLON) {
  29300. /**
  29301. * This is a holder class for the physics joint created by the physics plugin.
  29302. * It holds a set of functions to control the underlying joint.
  29303. */
  29304. var PhysicsJoint = (function () {
  29305. function PhysicsJoint(type, jointData) {
  29306. this.type = type;
  29307. this.jointData = jointData;
  29308. jointData.nativeParams = jointData.nativeParams || {};
  29309. }
  29310. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  29311. get: function () {
  29312. return this._physicsJoint;
  29313. },
  29314. set: function (newJoint) {
  29315. if (this._physicsJoint) {
  29316. }
  29317. this._physicsJoint = newJoint;
  29318. },
  29319. enumerable: true,
  29320. configurable: true
  29321. });
  29322. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  29323. set: function (physicsPlugin) {
  29324. this._physicsPlugin = physicsPlugin;
  29325. },
  29326. enumerable: true,
  29327. configurable: true
  29328. });
  29329. /**
  29330. * Execute a function that is physics-plugin specific.
  29331. * @param {Function} func the function that will be executed.
  29332. * It accepts two parameters: the physics world and the physics joint.
  29333. */
  29334. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  29335. func(this._physicsPlugin.world, this._physicsJoint);
  29336. };
  29337. //TODO check if the native joints are the same
  29338. //Joint Types
  29339. PhysicsJoint.DistanceJoint = 0;
  29340. PhysicsJoint.HingeJoint = 1;
  29341. PhysicsJoint.BallAndSocketJoint = 2;
  29342. PhysicsJoint.WheelJoint = 3;
  29343. PhysicsJoint.SliderJoint = 4;
  29344. //OIMO
  29345. PhysicsJoint.PrismaticJoint = 5;
  29346. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  29347. PhysicsJoint.UniversalJoint = 6;
  29348. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  29349. //Cannon
  29350. //Similar to a Ball-Joint. Different in params
  29351. PhysicsJoint.PointToPointJoint = 8;
  29352. //Cannon only at the moment
  29353. PhysicsJoint.SpringJoint = 9;
  29354. PhysicsJoint.LockJoint = 10;
  29355. return PhysicsJoint;
  29356. })();
  29357. BABYLON.PhysicsJoint = PhysicsJoint;
  29358. /**
  29359. * A class representing a physics distance joint.
  29360. */
  29361. var DistanceJoint = (function (_super) {
  29362. __extends(DistanceJoint, _super);
  29363. function DistanceJoint(jointData) {
  29364. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  29365. }
  29366. /**
  29367. * Update the predefined distance.
  29368. */
  29369. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  29370. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  29371. };
  29372. return DistanceJoint;
  29373. })(PhysicsJoint);
  29374. BABYLON.DistanceJoint = DistanceJoint;
  29375. var MotorEnabledJoint = (function (_super) {
  29376. __extends(MotorEnabledJoint, _super);
  29377. function MotorEnabledJoint(type, jointData) {
  29378. _super.call(this, type, jointData);
  29379. }
  29380. /**
  29381. * Set the motor values.
  29382. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29383. * @param {number} force the force to apply
  29384. * @param {number} maxForce max force for this motor.
  29385. */
  29386. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  29387. this._physicsPlugin.setMotor(this, force, maxForce);
  29388. };
  29389. /**
  29390. * Set the motor's limits.
  29391. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29392. */
  29393. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  29394. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  29395. };
  29396. return MotorEnabledJoint;
  29397. })(PhysicsJoint);
  29398. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  29399. /**
  29400. * This class represents a single hinge physics joint
  29401. */
  29402. var HingeJoint = (function (_super) {
  29403. __extends(HingeJoint, _super);
  29404. function HingeJoint(jointData) {
  29405. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  29406. }
  29407. /**
  29408. * Set the motor values.
  29409. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29410. * @param {number} force the force to apply
  29411. * @param {number} maxForce max force for this motor.
  29412. */
  29413. HingeJoint.prototype.setMotor = function (force, maxForce) {
  29414. this._physicsPlugin.setMotor(this, force, maxForce);
  29415. };
  29416. /**
  29417. * Set the motor's limits.
  29418. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29419. */
  29420. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  29421. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  29422. };
  29423. return HingeJoint;
  29424. })(MotorEnabledJoint);
  29425. BABYLON.HingeJoint = HingeJoint;
  29426. /**
  29427. * This class represents a dual hinge physics joint (same as wheel joint)
  29428. */
  29429. var Hinge2Joint = (function (_super) {
  29430. __extends(Hinge2Joint, _super);
  29431. function Hinge2Joint(jointData) {
  29432. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  29433. }
  29434. /**
  29435. * Set the motor values.
  29436. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29437. * @param {number} force the force to apply
  29438. * @param {number} maxForce max force for this motor.
  29439. * @param {motorIndex} the motor's index, 0 or 1.
  29440. */
  29441. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  29442. if (motorIndex === void 0) { motorIndex = 0; }
  29443. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  29444. };
  29445. /**
  29446. * Set the motor limits.
  29447. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29448. * @param {number} upperLimit the upper limit
  29449. * @param {number} lowerLimit lower limit
  29450. * @param {motorIndex} the motor's index, 0 or 1.
  29451. */
  29452. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  29453. if (motorIndex === void 0) { motorIndex = 0; }
  29454. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  29455. };
  29456. return Hinge2Joint;
  29457. })(MotorEnabledJoint);
  29458. BABYLON.Hinge2Joint = Hinge2Joint;
  29459. })(BABYLON || (BABYLON = {}));
  29460. var BABYLON;
  29461. (function (BABYLON) {
  29462. var PhysicsImpostor = (function () {
  29463. function PhysicsImpostor(object, type, _options, _scene) {
  29464. var _this = this;
  29465. if (_options === void 0) { _options = { mass: 0 }; }
  29466. this.object = object;
  29467. this.type = type;
  29468. this._options = _options;
  29469. this._scene = _scene;
  29470. this._bodyUpdateRequired = false;
  29471. this._onBeforePhysicsStepCallbacks = new Array();
  29472. this._onAfterPhysicsStepCallbacks = new Array();
  29473. this._onPhysicsCollideCallbacks = [];
  29474. this._deltaPosition = BABYLON.Vector3.Zero();
  29475. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  29476. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  29477. /**
  29478. * this function is executed by the physics engine.
  29479. */
  29480. this.beforeStep = function () {
  29481. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  29482. //conjugate deltaRotation
  29483. if (_this._deltaRotationConjugated) {
  29484. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  29485. }
  29486. else {
  29487. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  29488. }
  29489. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  29490. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  29491. func(_this);
  29492. });
  29493. };
  29494. /**
  29495. * this function is executed by the physics engine.
  29496. */
  29497. this.afterStep = function () {
  29498. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  29499. func(_this);
  29500. });
  29501. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  29502. _this.object.position.addInPlace(_this._deltaPosition);
  29503. if (_this._deltaRotation) {
  29504. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  29505. }
  29506. };
  29507. //event and body object due to cannon's event-based architecture.
  29508. this.onCollide = function (e) {
  29509. if (!_this._onPhysicsCollideCallbacks.length)
  29510. return;
  29511. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  29512. if (otherImpostor) {
  29513. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  29514. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  29515. }).forEach(function (obj) {
  29516. obj.callback(_this, otherImpostor);
  29517. });
  29518. }
  29519. };
  29520. //sanity check!
  29521. if (!this.object) {
  29522. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  29523. return;
  29524. }
  29525. //legacy support for old syntax.
  29526. if (!this._scene && object.getScene) {
  29527. this._scene = object.getScene();
  29528. }
  29529. this._physicsEngine = this._scene.getPhysicsEngine();
  29530. if (!this._physicsEngine) {
  29531. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  29532. }
  29533. else {
  29534. //set the object's quaternion, if not set
  29535. if (!this.object.rotationQuaternion) {
  29536. if (this.object.rotation) {
  29537. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  29538. }
  29539. else {
  29540. this.object.rotationQuaternion = new BABYLON.Quaternion();
  29541. }
  29542. }
  29543. //default options params
  29544. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  29545. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  29546. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  29547. this._joints = [];
  29548. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  29549. if (!this.object.parent) {
  29550. this._init();
  29551. }
  29552. }
  29553. }
  29554. /**
  29555. * This function will completly initialize this impostor.
  29556. * It will create a new body - but only if this mesh has no parent.
  29557. * If it has, this impostor will not be used other than to define the impostor
  29558. * of the child mesh.
  29559. */
  29560. PhysicsImpostor.prototype._init = function () {
  29561. this._physicsEngine.removeImpostor(this);
  29562. this.physicsBody = null;
  29563. this._parent = this._parent || this._getPhysicsParent();
  29564. if (!this.parent) {
  29565. this._physicsEngine.addImpostor(this);
  29566. }
  29567. };
  29568. PhysicsImpostor.prototype._getPhysicsParent = function () {
  29569. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  29570. var parentMesh = this.object.parent;
  29571. return parentMesh.physicsImpostor;
  29572. }
  29573. return;
  29574. };
  29575. /**
  29576. * Should a new body be generated.
  29577. */
  29578. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  29579. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  29580. };
  29581. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  29582. this.forceUpdate();
  29583. };
  29584. /**
  29585. * Force a regeneration of this or the parent's impostor's body.
  29586. * Use under cautious - This will remove all joints already implemented.
  29587. */
  29588. PhysicsImpostor.prototype.forceUpdate = function () {
  29589. this._init();
  29590. if (this.parent) {
  29591. this.parent.forceUpdate();
  29592. }
  29593. };
  29594. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  29595. /*public get mesh(): AbstractMesh {
  29596. return this._mesh;
  29597. }*/
  29598. /**
  29599. * Gets the body that holds this impostor. Either its own, or its parent.
  29600. */
  29601. get: function () {
  29602. return this._parent ? this._parent.physicsBody : this._physicsBody;
  29603. },
  29604. /**
  29605. * Set the physics body. Used mainly by the physics engine/plugin
  29606. */
  29607. set: function (physicsBody) {
  29608. if (this._physicsBody) {
  29609. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  29610. }
  29611. this._physicsBody = physicsBody;
  29612. this.resetUpdateFlags();
  29613. },
  29614. enumerable: true,
  29615. configurable: true
  29616. });
  29617. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  29618. get: function () {
  29619. return this._parent;
  29620. },
  29621. enumerable: true,
  29622. configurable: true
  29623. });
  29624. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  29625. this._bodyUpdateRequired = false;
  29626. };
  29627. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  29628. if (this.object.getBoundingInfo) {
  29629. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  29630. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  29631. }
  29632. else {
  29633. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  29634. }
  29635. };
  29636. PhysicsImpostor.prototype.getObjectCenter = function () {
  29637. if (this.object.getBoundingInfo) {
  29638. return this.object.getBoundingInfo().boundingBox.center;
  29639. }
  29640. else {
  29641. return this.object.position;
  29642. }
  29643. };
  29644. /**
  29645. * Get a specific parametes from the options parameter.
  29646. */
  29647. PhysicsImpostor.prototype.getParam = function (paramName) {
  29648. return this._options[paramName];
  29649. };
  29650. /**
  29651. * Sets a specific parameter in the options given to the physics plugin
  29652. */
  29653. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  29654. this._options[paramName] = value;
  29655. this._bodyUpdateRequired = true;
  29656. };
  29657. /**
  29658. * Specifically change the body's mass option. Won't recreate the physics body object
  29659. */
  29660. PhysicsImpostor.prototype.setMass = function (mass) {
  29661. if (this.getParam("mass") !== mass) {
  29662. this.setParam("mass", mass);
  29663. }
  29664. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  29665. };
  29666. PhysicsImpostor.prototype.getLinearVelocity = function () {
  29667. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  29668. };
  29669. /**
  29670. * Set the body's linear velocity.
  29671. */
  29672. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  29673. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  29674. };
  29675. PhysicsImpostor.prototype.getAngularVelocity = function () {
  29676. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  29677. };
  29678. /**
  29679. * Set the body's linear velocity.
  29680. */
  29681. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  29682. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  29683. };
  29684. /**
  29685. * Execute a function with the physics plugin native code.
  29686. * Provide a function the will have two variables - the world object and the physics body object.
  29687. */
  29688. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  29689. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  29690. };
  29691. /**
  29692. * Register a function that will be executed before the physics world is stepping forward.
  29693. */
  29694. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  29695. this._onBeforePhysicsStepCallbacks.push(func);
  29696. };
  29697. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  29698. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  29699. if (index > -1) {
  29700. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  29701. }
  29702. else {
  29703. BABYLON.Tools.Warn("Function to remove was not found");
  29704. }
  29705. };
  29706. /**
  29707. * Register a function that will be executed after the physics step
  29708. */
  29709. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  29710. this._onAfterPhysicsStepCallbacks.push(func);
  29711. };
  29712. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  29713. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  29714. if (index > -1) {
  29715. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  29716. }
  29717. else {
  29718. BABYLON.Tools.Warn("Function to remove was not found");
  29719. }
  29720. };
  29721. /**
  29722. * register a function that will be executed when this impostor collides against a different body.
  29723. */
  29724. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  29725. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  29726. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  29727. };
  29728. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  29729. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  29730. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  29731. if (index > -1) {
  29732. this._onPhysicsCollideCallbacks.splice(index, 1);
  29733. }
  29734. else {
  29735. BABYLON.Tools.Warn("Function to remove was not found");
  29736. }
  29737. };
  29738. /**
  29739. * Apply a force
  29740. */
  29741. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  29742. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  29743. };
  29744. /**
  29745. * Apply an impulse
  29746. */
  29747. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  29748. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  29749. };
  29750. /**
  29751. * A help function to create a joint.
  29752. */
  29753. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  29754. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  29755. this.addJoint(otherImpostor, joint);
  29756. };
  29757. /**
  29758. * Add a joint to this impostor with a different impostor.
  29759. */
  29760. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  29761. this._joints.push({
  29762. otherImpostor: otherImpostor,
  29763. joint: joint
  29764. });
  29765. this._physicsEngine.addJoint(this, otherImpostor, joint);
  29766. };
  29767. /**
  29768. * Will keep this body still, in a sleep mode.
  29769. */
  29770. PhysicsImpostor.prototype.sleep = function () {
  29771. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  29772. };
  29773. /**
  29774. * Wake the body up.
  29775. */
  29776. PhysicsImpostor.prototype.wakeUp = function () {
  29777. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  29778. };
  29779. PhysicsImpostor.prototype.clone = function (newObject) {
  29780. if (!newObject)
  29781. return null;
  29782. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  29783. };
  29784. PhysicsImpostor.prototype.dispose = function () {
  29785. var _this = this;
  29786. //no dispose if no physics engine is available.
  29787. if (!this._physicsEngine) {
  29788. return;
  29789. }
  29790. this._joints.forEach(function (j) {
  29791. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  29792. });
  29793. //dispose the physics body
  29794. this._physicsEngine.removeImpostor(this);
  29795. if (this.parent) {
  29796. this.parent.forceUpdate();
  29797. }
  29798. else {
  29799. }
  29800. };
  29801. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  29802. this._deltaPosition.copyFrom(position);
  29803. };
  29804. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  29805. if (!this._deltaRotation) {
  29806. this._deltaRotation = new BABYLON.Quaternion();
  29807. }
  29808. this._deltaRotation.copyFrom(rotation);
  29809. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  29810. };
  29811. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  29812. //Impostor types
  29813. PhysicsImpostor.NoImpostor = 0;
  29814. PhysicsImpostor.SphereImpostor = 1;
  29815. PhysicsImpostor.BoxImpostor = 2;
  29816. PhysicsImpostor.PlaneImpostor = 3;
  29817. PhysicsImpostor.MeshImpostor = 4;
  29818. PhysicsImpostor.CylinderImpostor = 7;
  29819. PhysicsImpostor.ParticleImpostor = 8;
  29820. PhysicsImpostor.HeightmapImpostor = 9;
  29821. return PhysicsImpostor;
  29822. })();
  29823. BABYLON.PhysicsImpostor = PhysicsImpostor;
  29824. })(BABYLON || (BABYLON = {}));
  29825. var BABYLON;
  29826. (function (BABYLON) {
  29827. var PhysicsEngine = (function () {
  29828. function PhysicsEngine(gravity, _physicsPlugin) {
  29829. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  29830. this._physicsPlugin = _physicsPlugin;
  29831. //new methods and parameters
  29832. this._impostors = [];
  29833. this._joints = [];
  29834. if (!this._physicsPlugin.isSupported()) {
  29835. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  29836. + "Please make sure it is included.");
  29837. }
  29838. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  29839. this.setGravity(gravity);
  29840. this.setTimeStep();
  29841. }
  29842. PhysicsEngine.prototype.setGravity = function (gravity) {
  29843. this.gravity = gravity;
  29844. this._physicsPlugin.setGravity(this.gravity);
  29845. };
  29846. /**
  29847. * Set the time step of the physics engine.
  29848. * default is 1/60.
  29849. * To slow it down, enter 1/600 for example.
  29850. * To speed it up, 1/30
  29851. * @param {number} newTimeStep the new timestep to apply to this world.
  29852. */
  29853. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  29854. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  29855. this._physicsPlugin.setTimeStep(newTimeStep);
  29856. };
  29857. PhysicsEngine.prototype.dispose = function () {
  29858. this._impostors.forEach(function (impostor) {
  29859. impostor.dispose();
  29860. });
  29861. this._physicsPlugin.dispose();
  29862. };
  29863. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  29864. return this._physicsPlugin.name;
  29865. };
  29866. /**
  29867. * Adding a new impostor for the impostor tracking.
  29868. * This will be done by the impostor itself.
  29869. * @param {PhysicsImpostor} impostor the impostor to add
  29870. */
  29871. PhysicsEngine.prototype.addImpostor = function (impostor) {
  29872. impostor.uniqueId = this._impostors.push(impostor);
  29873. //if no parent, generate the body
  29874. if (!impostor.parent) {
  29875. this._physicsPlugin.generatePhysicsBody(impostor);
  29876. }
  29877. };
  29878. /**
  29879. * Remove an impostor from the engine.
  29880. * This impostor and its mesh will not longer be updated by the physics engine.
  29881. * @param {PhysicsImpostor} impostor the impostor to remove
  29882. */
  29883. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  29884. var index = this._impostors.indexOf(impostor);
  29885. if (index > -1) {
  29886. var removed = this._impostors.splice(index, 1);
  29887. //Is it needed?
  29888. if (removed.length) {
  29889. //this will also remove it from the world.
  29890. removed[0].physicsBody = null;
  29891. }
  29892. }
  29893. };
  29894. /**
  29895. * Add a joint to the physics engine
  29896. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  29897. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  29898. * @param {PhysicsJoint} the joint that will connect both impostors.
  29899. */
  29900. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  29901. var impostorJoint = {
  29902. mainImpostor: mainImpostor,
  29903. connectedImpostor: connectedImpostor,
  29904. joint: joint
  29905. };
  29906. joint.physicsPlugin = this._physicsPlugin;
  29907. this._joints.push(impostorJoint);
  29908. this._physicsPlugin.generateJoint(impostorJoint);
  29909. };
  29910. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  29911. var matchingJoints = this._joints.filter(function (impostorJoint) {
  29912. return (impostorJoint.connectedImpostor === connectedImpostor
  29913. && impostorJoint.joint === joint
  29914. && impostorJoint.mainImpostor === mainImpostor);
  29915. });
  29916. if (matchingJoints.length) {
  29917. this._physicsPlugin.removeJoint(matchingJoints[0]);
  29918. }
  29919. };
  29920. /**
  29921. * Called by the scene. no need to call it.
  29922. */
  29923. PhysicsEngine.prototype._step = function (delta) {
  29924. var _this = this;
  29925. //check if any mesh has no body / requires an update
  29926. this._impostors.forEach(function (impostor) {
  29927. if (impostor.isBodyInitRequired()) {
  29928. _this._physicsPlugin.generatePhysicsBody(impostor);
  29929. }
  29930. });
  29931. if (delta > 0.1) {
  29932. delta = 0.1;
  29933. }
  29934. else if (delta <= 0) {
  29935. delta = 1.0 / 60.0;
  29936. }
  29937. this._physicsPlugin.executeStep(delta, this._impostors);
  29938. };
  29939. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  29940. return this._physicsPlugin;
  29941. };
  29942. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  29943. for (var i = 0; i < this._impostors.length; ++i) {
  29944. if (this._impostors[i].object === object) {
  29945. return this._impostors[i];
  29946. }
  29947. }
  29948. };
  29949. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  29950. for (var i = 0; i < this._impostors.length; ++i) {
  29951. if (this._impostors[i].physicsBody === body) {
  29952. return this._impostors[i];
  29953. }
  29954. }
  29955. };
  29956. // Statics, Legacy support.
  29957. /**
  29958. * @Deprecated
  29959. *
  29960. */
  29961. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  29962. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  29963. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  29964. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  29965. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  29966. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  29967. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  29968. PhysicsEngine.CapsuleImpostor = -1;
  29969. PhysicsEngine.ConeImpostor = -1;
  29970. PhysicsEngine.ConvexHullImpostor = -1;
  29971. PhysicsEngine.Epsilon = 0.001;
  29972. return PhysicsEngine;
  29973. })();
  29974. BABYLON.PhysicsEngine = PhysicsEngine;
  29975. })(BABYLON || (BABYLON = {}));
  29976. var BABYLON;
  29977. (function (BABYLON) {
  29978. var VertexData = (function () {
  29979. function VertexData() {
  29980. }
  29981. VertexData.prototype.set = function (data, kind) {
  29982. switch (kind) {
  29983. case BABYLON.VertexBuffer.PositionKind:
  29984. this.positions = data;
  29985. break;
  29986. case BABYLON.VertexBuffer.NormalKind:
  29987. this.normals = data;
  29988. break;
  29989. case BABYLON.VertexBuffer.UVKind:
  29990. this.uvs = data;
  29991. break;
  29992. case BABYLON.VertexBuffer.UV2Kind:
  29993. this.uvs2 = data;
  29994. break;
  29995. case BABYLON.VertexBuffer.UV3Kind:
  29996. this.uvs3 = data;
  29997. break;
  29998. case BABYLON.VertexBuffer.UV4Kind:
  29999. this.uvs4 = data;
  30000. break;
  30001. case BABYLON.VertexBuffer.UV5Kind:
  30002. this.uvs5 = data;
  30003. break;
  30004. case BABYLON.VertexBuffer.UV6Kind:
  30005. this.uvs6 = data;
  30006. break;
  30007. case BABYLON.VertexBuffer.ColorKind:
  30008. this.colors = data;
  30009. break;
  30010. case BABYLON.VertexBuffer.MatricesIndicesKind:
  30011. this.matricesIndices = data;
  30012. break;
  30013. case BABYLON.VertexBuffer.MatricesWeightsKind:
  30014. this.matricesWeights = data;
  30015. break;
  30016. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  30017. this.matricesIndicesExtra = data;
  30018. break;
  30019. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  30020. this.matricesWeightsExtra = data;
  30021. break;
  30022. }
  30023. };
  30024. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  30025. this._applyTo(mesh, updatable);
  30026. };
  30027. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  30028. this._applyTo(geometry, updatable);
  30029. };
  30030. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  30031. this._update(mesh);
  30032. };
  30033. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  30034. this._update(geometry);
  30035. };
  30036. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  30037. if (this.positions) {
  30038. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  30039. }
  30040. if (this.normals) {
  30041. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  30042. }
  30043. if (this.uvs) {
  30044. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  30045. }
  30046. if (this.uvs2) {
  30047. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  30048. }
  30049. if (this.uvs3) {
  30050. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  30051. }
  30052. if (this.uvs4) {
  30053. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  30054. }
  30055. if (this.uvs5) {
  30056. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  30057. }
  30058. if (this.uvs6) {
  30059. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  30060. }
  30061. if (this.colors) {
  30062. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  30063. }
  30064. if (this.matricesIndices) {
  30065. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  30066. }
  30067. if (this.matricesWeights) {
  30068. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  30069. }
  30070. if (this.matricesIndicesExtra) {
  30071. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  30072. }
  30073. if (this.matricesWeightsExtra) {
  30074. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  30075. }
  30076. if (this.indices) {
  30077. meshOrGeometry.setIndices(this.indices);
  30078. }
  30079. };
  30080. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  30081. if (this.positions) {
  30082. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  30083. }
  30084. if (this.normals) {
  30085. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  30086. }
  30087. if (this.uvs) {
  30088. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  30089. }
  30090. if (this.uvs2) {
  30091. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  30092. }
  30093. if (this.uvs3) {
  30094. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  30095. }
  30096. if (this.uvs4) {
  30097. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  30098. }
  30099. if (this.uvs5) {
  30100. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  30101. }
  30102. if (this.uvs6) {
  30103. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  30104. }
  30105. if (this.colors) {
  30106. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  30107. }
  30108. if (this.matricesIndices) {
  30109. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  30110. }
  30111. if (this.matricesWeights) {
  30112. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  30113. }
  30114. if (this.matricesIndicesExtra) {
  30115. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  30116. }
  30117. if (this.matricesWeightsExtra) {
  30118. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  30119. }
  30120. if (this.indices) {
  30121. meshOrGeometry.setIndices(this.indices);
  30122. }
  30123. };
  30124. VertexData.prototype.transform = function (matrix) {
  30125. var transformed = BABYLON.Vector3.Zero();
  30126. var index;
  30127. if (this.positions) {
  30128. var position = BABYLON.Vector3.Zero();
  30129. for (index = 0; index < this.positions.length; index += 3) {
  30130. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  30131. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  30132. this.positions[index] = transformed.x;
  30133. this.positions[index + 1] = transformed.y;
  30134. this.positions[index + 2] = transformed.z;
  30135. }
  30136. }
  30137. if (this.normals) {
  30138. var normal = BABYLON.Vector3.Zero();
  30139. for (index = 0; index < this.normals.length; index += 3) {
  30140. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  30141. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  30142. this.normals[index] = transformed.x;
  30143. this.normals[index + 1] = transformed.y;
  30144. this.normals[index + 2] = transformed.z;
  30145. }
  30146. }
  30147. };
  30148. VertexData.prototype.merge = function (other) {
  30149. if (other.indices) {
  30150. if (!this.indices) {
  30151. this.indices = [];
  30152. }
  30153. var offset = this.positions ? this.positions.length / 3 : 0;
  30154. for (var index = 0; index < other.indices.length; index++) {
  30155. //TODO check type - if Int32Array!
  30156. this.indices.push(other.indices[index] + offset);
  30157. }
  30158. }
  30159. this.positions = this._mergeElement(this.positions, other.positions);
  30160. this.normals = this._mergeElement(this.normals, other.normals);
  30161. this.uvs = this._mergeElement(this.uvs, other.uvs);
  30162. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  30163. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  30164. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  30165. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  30166. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  30167. this.colors = this._mergeElement(this.colors, other.colors);
  30168. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  30169. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  30170. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  30171. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  30172. };
  30173. VertexData.prototype._mergeElement = function (source, other) {
  30174. if (!other)
  30175. return source;
  30176. if (!source)
  30177. return other;
  30178. var len = other.length + source.length;
  30179. var isSrcTypedArray = source instanceof Float32Array;
  30180. var isOthTypedArray = other instanceof Float32Array;
  30181. // use non-loop method when the source is Float32Array
  30182. if (isSrcTypedArray) {
  30183. var ret32 = new Float32Array(len);
  30184. ret32.set(source);
  30185. ret32.set(other, source.length);
  30186. return ret32;
  30187. }
  30188. else if (!isOthTypedArray) {
  30189. return source.concat(other);
  30190. }
  30191. else {
  30192. var ret = source.slice(0); // copy source to a separate array
  30193. for (var i = 0, len = other.length; i < len; i++) {
  30194. ret.push(other[i]);
  30195. }
  30196. return ret;
  30197. }
  30198. };
  30199. VertexData.prototype.serialize = function () {
  30200. var serializationObject = this.serialize();
  30201. if (this.positions) {
  30202. serializationObject.positions = this.positions;
  30203. }
  30204. if (this.normals) {
  30205. serializationObject.normals = this.normals;
  30206. }
  30207. if (this.uvs) {
  30208. serializationObject.uvs = this.uvs;
  30209. }
  30210. if (this.uvs2) {
  30211. serializationObject.uvs2 = this.uvs2;
  30212. }
  30213. if (this.uvs3) {
  30214. serializationObject.uvs3 = this.uvs3;
  30215. }
  30216. if (this.uvs4) {
  30217. serializationObject.uvs4 = this.uvs4;
  30218. }
  30219. if (this.uvs5) {
  30220. serializationObject.uvs5 = this.uvs5;
  30221. }
  30222. if (this.uvs6) {
  30223. serializationObject.uvs6 = this.uvs6;
  30224. }
  30225. if (this.colors) {
  30226. serializationObject.colors = this.colors;
  30227. }
  30228. if (this.matricesIndices) {
  30229. serializationObject.matricesIndices = this.matricesIndices;
  30230. serializationObject.matricesIndices._isExpanded = true;
  30231. }
  30232. if (this.matricesWeights) {
  30233. serializationObject.matricesWeights = this.matricesWeights;
  30234. }
  30235. if (this.matricesIndicesExtra) {
  30236. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  30237. serializationObject.matricesIndicesExtra._isExpanded = true;
  30238. }
  30239. if (this.matricesWeightsExtra) {
  30240. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  30241. }
  30242. serializationObject.indices = this.indices;
  30243. return serializationObject;
  30244. };
  30245. // Statics
  30246. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  30247. return VertexData._ExtractFrom(mesh, copyWhenShared);
  30248. };
  30249. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  30250. return VertexData._ExtractFrom(geometry, copyWhenShared);
  30251. };
  30252. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  30253. var result = new VertexData();
  30254. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30255. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  30256. }
  30257. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30258. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  30259. }
  30260. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30261. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  30262. }
  30263. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30264. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  30265. }
  30266. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30267. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  30268. }
  30269. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30270. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  30271. }
  30272. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30273. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  30274. }
  30275. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30276. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  30277. }
  30278. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30279. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  30280. }
  30281. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30282. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  30283. }
  30284. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30285. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  30286. }
  30287. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  30288. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  30289. }
  30290. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  30291. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  30292. }
  30293. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  30294. return result;
  30295. };
  30296. VertexData.CreateRibbon = function (options) {
  30297. var pathArray = options.pathArray;
  30298. var closeArray = options.closeArray || false;
  30299. var closePath = options.closePath || false;
  30300. var invertUV = options.invertUV || false;
  30301. var defaultOffset = Math.floor(pathArray[0].length / 2);
  30302. var offset = options.offset || defaultOffset;
  30303. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  30304. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30305. var positions = [];
  30306. var indices = [];
  30307. var normals = [];
  30308. var uvs = [];
  30309. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  30310. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  30311. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  30312. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  30313. var minlg; // minimal length among all paths from pathArray
  30314. var lg = []; // array of path lengths : nb of vertex per path
  30315. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  30316. var p; // path iterator
  30317. var i; // point iterator
  30318. var j; // point iterator
  30319. // if single path in pathArray
  30320. if (pathArray.length < 2) {
  30321. var ar1 = [];
  30322. var ar2 = [];
  30323. for (i = 0; i < pathArray[0].length - offset; i++) {
  30324. ar1.push(pathArray[0][i]);
  30325. ar2.push(pathArray[0][i + offset]);
  30326. }
  30327. pathArray = [ar1, ar2];
  30328. }
  30329. // positions and horizontal distances (u)
  30330. var idc = 0;
  30331. var closePathCorr = (closePath) ? 1 : 0;
  30332. var path;
  30333. var l;
  30334. minlg = pathArray[0].length;
  30335. var vectlg;
  30336. var dist;
  30337. for (p = 0; p < pathArray.length; p++) {
  30338. uTotalDistance[p] = 0;
  30339. us[p] = [0];
  30340. path = pathArray[p];
  30341. l = path.length;
  30342. minlg = (minlg < l) ? minlg : l;
  30343. j = 0;
  30344. while (j < l) {
  30345. positions.push(path[j].x, path[j].y, path[j].z);
  30346. if (j > 0) {
  30347. vectlg = path[j].subtract(path[j - 1]).length();
  30348. dist = vectlg + uTotalDistance[p];
  30349. us[p].push(dist);
  30350. uTotalDistance[p] = dist;
  30351. }
  30352. j++;
  30353. }
  30354. if (closePath) {
  30355. j--;
  30356. positions.push(path[0].x, path[0].y, path[0].z);
  30357. vectlg = path[j].subtract(path[0]).length();
  30358. dist = vectlg + uTotalDistance[p];
  30359. us[p].push(dist);
  30360. uTotalDistance[p] = dist;
  30361. }
  30362. lg[p] = l + closePathCorr;
  30363. idx[p] = idc;
  30364. idc += (l + closePathCorr);
  30365. }
  30366. // vertical distances (v)
  30367. var path1;
  30368. var path2;
  30369. var vertex1;
  30370. var vertex2;
  30371. for (i = 0; i < minlg + closePathCorr; i++) {
  30372. vTotalDistance[i] = 0;
  30373. vs[i] = [0];
  30374. for (p = 0; p < pathArray.length - 1; p++) {
  30375. path1 = pathArray[p];
  30376. path2 = pathArray[p + 1];
  30377. if (i === minlg) {
  30378. vertex1 = path1[0];
  30379. vertex2 = path2[0];
  30380. }
  30381. else {
  30382. vertex1 = path1[i];
  30383. vertex2 = path2[i];
  30384. }
  30385. vectlg = vertex2.subtract(vertex1).length();
  30386. dist = vectlg + vTotalDistance[i];
  30387. vs[i].push(dist);
  30388. vTotalDistance[i] = dist;
  30389. }
  30390. if (closeArray) {
  30391. path1 = pathArray[p];
  30392. path2 = pathArray[0];
  30393. if (i === minlg) {
  30394. vertex2 = path2[0];
  30395. }
  30396. vectlg = vertex2.subtract(vertex1).length();
  30397. dist = vectlg + vTotalDistance[i];
  30398. vTotalDistance[i] = dist;
  30399. }
  30400. }
  30401. // uvs
  30402. var u;
  30403. var v;
  30404. for (p = 0; p < pathArray.length; p++) {
  30405. for (i = 0; i < minlg + closePathCorr; i++) {
  30406. u = us[p][i] / uTotalDistance[p];
  30407. v = vs[i][p] / vTotalDistance[i];
  30408. if (invertUV) {
  30409. uvs.push(v, u);
  30410. }
  30411. else {
  30412. uvs.push(u, v);
  30413. }
  30414. }
  30415. }
  30416. // indices
  30417. p = 0; // path index
  30418. var pi = 0; // positions array index
  30419. var l1 = lg[p] - 1; // path1 length
  30420. var l2 = lg[p + 1] - 1; // path2 length
  30421. var min = (l1 < l2) ? l1 : l2; // current path stop index
  30422. var shft = idx[1] - idx[0]; // shift
  30423. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  30424. while (pi <= min && p < path1nb) {
  30425. // 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
  30426. indices.push(pi, pi + shft, pi + 1);
  30427. indices.push(pi + shft + 1, pi + 1, pi + shft);
  30428. pi += 1;
  30429. if (pi === min) {
  30430. p++;
  30431. if (p === lg.length - 1) {
  30432. shft = idx[0] - idx[p];
  30433. l1 = lg[p] - 1;
  30434. l2 = lg[0] - 1;
  30435. }
  30436. else {
  30437. shft = idx[p + 1] - idx[p];
  30438. l1 = lg[p] - 1;
  30439. l2 = lg[p + 1] - 1;
  30440. }
  30441. pi = idx[p];
  30442. min = (l1 < l2) ? l1 + pi : l2 + pi;
  30443. }
  30444. }
  30445. // normals
  30446. VertexData.ComputeNormals(positions, indices, normals);
  30447. if (closePath) {
  30448. var indexFirst = 0;
  30449. var indexLast = 0;
  30450. for (p = 0; p < pathArray.length; p++) {
  30451. indexFirst = idx[p] * 3;
  30452. if (p + 1 < pathArray.length) {
  30453. indexLast = (idx[p + 1] - 1) * 3;
  30454. }
  30455. else {
  30456. indexLast = normals.length - 3;
  30457. }
  30458. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  30459. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  30460. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  30461. normals[indexLast] = normals[indexFirst];
  30462. normals[indexLast + 1] = normals[indexFirst + 1];
  30463. normals[indexLast + 2] = normals[indexFirst + 2];
  30464. }
  30465. }
  30466. // sides
  30467. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30468. // Result
  30469. var vertexData = new VertexData();
  30470. vertexData.indices = indices;
  30471. vertexData.positions = positions;
  30472. vertexData.normals = normals;
  30473. vertexData.uvs = uvs;
  30474. if (closePath) {
  30475. vertexData._idx = idx;
  30476. }
  30477. return vertexData;
  30478. };
  30479. VertexData.CreateBox = function (options) {
  30480. var normalsSource = [
  30481. new BABYLON.Vector3(0, 0, 1),
  30482. new BABYLON.Vector3(0, 0, -1),
  30483. new BABYLON.Vector3(1, 0, 0),
  30484. new BABYLON.Vector3(-1, 0, 0),
  30485. new BABYLON.Vector3(0, 1, 0),
  30486. new BABYLON.Vector3(0, -1, 0)
  30487. ];
  30488. var indices = [];
  30489. var positions = [];
  30490. var normals = [];
  30491. var uvs = [];
  30492. var width = options.width || options.size || 1;
  30493. var height = options.height || options.size || 1;
  30494. var depth = options.depth || options.size || 1;
  30495. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30496. var faceUV = options.faceUV || new Array(6);
  30497. var faceColors = options.faceColors;
  30498. var colors = [];
  30499. // default face colors and UV if undefined
  30500. for (var f = 0; f < 6; f++) {
  30501. if (faceUV[f] === undefined) {
  30502. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30503. }
  30504. if (faceColors && faceColors[f] === undefined) {
  30505. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30506. }
  30507. }
  30508. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  30509. // Create each face in turn.
  30510. for (var index = 0; index < normalsSource.length; index++) {
  30511. var normal = normalsSource[index];
  30512. // Get two vectors perpendicular to the face normal and to each other.
  30513. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  30514. var side2 = BABYLON.Vector3.Cross(normal, side1);
  30515. // Six indices (two triangles) per face.
  30516. var verticesLength = positions.length / 3;
  30517. indices.push(verticesLength);
  30518. indices.push(verticesLength + 1);
  30519. indices.push(verticesLength + 2);
  30520. indices.push(verticesLength);
  30521. indices.push(verticesLength + 2);
  30522. indices.push(verticesLength + 3);
  30523. // Four vertices per face.
  30524. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  30525. positions.push(vertex.x, vertex.y, vertex.z);
  30526. normals.push(normal.x, normal.y, normal.z);
  30527. uvs.push(faceUV[index].z, faceUV[index].w);
  30528. if (faceColors) {
  30529. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30530. }
  30531. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  30532. positions.push(vertex.x, vertex.y, vertex.z);
  30533. normals.push(normal.x, normal.y, normal.z);
  30534. uvs.push(faceUV[index].x, faceUV[index].w);
  30535. if (faceColors) {
  30536. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30537. }
  30538. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  30539. positions.push(vertex.x, vertex.y, vertex.z);
  30540. normals.push(normal.x, normal.y, normal.z);
  30541. uvs.push(faceUV[index].x, faceUV[index].y);
  30542. if (faceColors) {
  30543. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30544. }
  30545. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  30546. positions.push(vertex.x, vertex.y, vertex.z);
  30547. normals.push(normal.x, normal.y, normal.z);
  30548. uvs.push(faceUV[index].z, faceUV[index].y);
  30549. if (faceColors) {
  30550. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30551. }
  30552. }
  30553. // sides
  30554. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30555. // Result
  30556. var vertexData = new VertexData();
  30557. vertexData.indices = indices;
  30558. vertexData.positions = positions;
  30559. vertexData.normals = normals;
  30560. vertexData.uvs = uvs;
  30561. if (faceColors) {
  30562. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30563. vertexData.colors = totalColors;
  30564. }
  30565. return vertexData;
  30566. };
  30567. VertexData.CreateSphere = function (options) {
  30568. var segments = options.segments || 32;
  30569. var diameterX = options.diameterX || options.diameter || 1;
  30570. var diameterY = options.diameterY || options.diameter || 1;
  30571. var diameterZ = options.diameterZ || options.diameter || 1;
  30572. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30573. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  30574. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30575. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  30576. var totalZRotationSteps = 2 + segments;
  30577. var totalYRotationSteps = 2 * totalZRotationSteps;
  30578. var indices = [];
  30579. var positions = [];
  30580. var normals = [];
  30581. var uvs = [];
  30582. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  30583. var normalizedZ = zRotationStep / totalZRotationSteps;
  30584. var angleZ = normalizedZ * Math.PI * slice;
  30585. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  30586. var normalizedY = yRotationStep / totalYRotationSteps;
  30587. var angleY = normalizedY * Math.PI * 2 * arc;
  30588. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  30589. var rotationY = BABYLON.Matrix.RotationY(angleY);
  30590. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  30591. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  30592. var vertex = complete.multiply(radius);
  30593. var normal = complete.divide(radius).normalize();
  30594. positions.push(vertex.x, vertex.y, vertex.z);
  30595. normals.push(normal.x, normal.y, normal.z);
  30596. uvs.push(normalizedY, normalizedZ);
  30597. }
  30598. if (zRotationStep > 0) {
  30599. var verticesCount = positions.length / 3;
  30600. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  30601. indices.push((firstIndex));
  30602. indices.push((firstIndex + 1));
  30603. indices.push(firstIndex + totalYRotationSteps + 1);
  30604. indices.push((firstIndex + totalYRotationSteps + 1));
  30605. indices.push((firstIndex + 1));
  30606. indices.push((firstIndex + totalYRotationSteps + 2));
  30607. }
  30608. }
  30609. }
  30610. // Sides
  30611. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30612. // Result
  30613. var vertexData = new VertexData();
  30614. vertexData.indices = indices;
  30615. vertexData.positions = positions;
  30616. vertexData.normals = normals;
  30617. vertexData.uvs = uvs;
  30618. return vertexData;
  30619. };
  30620. // Cylinder and cone
  30621. VertexData.CreateCylinder = function (options) {
  30622. var height = options.height || 2;
  30623. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  30624. var diameterBottom = options.diameterBottom || options.diameter || 1;
  30625. var tessellation = options.tessellation || 24;
  30626. var subdivisions = options.subdivisions || 1;
  30627. var hasRings = options.hasRings;
  30628. var enclose = options.enclose;
  30629. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30630. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30631. var faceUV = options.faceUV || new Array(3);
  30632. var faceColors = options.faceColors;
  30633. // default face colors and UV if undefined
  30634. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  30635. var ringNb = (hasRings) ? subdivisions : 1;
  30636. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  30637. var f;
  30638. for (f = 0; f < surfaceNb; f++) {
  30639. if (faceColors && faceColors[f] === undefined) {
  30640. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30641. }
  30642. }
  30643. for (f = 0; f < surfaceNb; f++) {
  30644. if (faceUV && faceUV[f] === undefined) {
  30645. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30646. }
  30647. }
  30648. var indices = [];
  30649. var positions = [];
  30650. var normals = [];
  30651. var uvs = [];
  30652. var colors = [];
  30653. var angle_step = Math.PI * 2 * arc / tessellation;
  30654. var angle;
  30655. var h;
  30656. var radius;
  30657. var tan = (diameterBottom - diameterTop) / 2 / height;
  30658. var ringVertex = BABYLON.Vector3.Zero();
  30659. var ringNormal = BABYLON.Vector3.Zero();
  30660. var ringFirstVertex = BABYLON.Vector3.Zero();
  30661. var ringFirstNormal = BABYLON.Vector3.Zero();
  30662. var quadNormal = BABYLON.Vector3.Zero();
  30663. var Y = BABYLON.Axis.Y;
  30664. // positions, normals, uvs
  30665. var i;
  30666. var j;
  30667. var r;
  30668. var ringIdx = 1;
  30669. var s = 1; // surface index
  30670. var cs = 0;
  30671. var v = 0;
  30672. for (i = 0; i <= subdivisions; i++) {
  30673. h = i / subdivisions;
  30674. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  30675. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  30676. for (r = 0; r < ringIdx; r++) {
  30677. if (hasRings) {
  30678. s += r;
  30679. }
  30680. if (enclose) {
  30681. s += 2 * r;
  30682. }
  30683. for (j = 0; j <= tessellation; j++) {
  30684. angle = j * angle_step;
  30685. // position
  30686. ringVertex.x = Math.cos(-angle) * radius;
  30687. ringVertex.y = -height / 2 + h * height;
  30688. ringVertex.z = Math.sin(-angle) * radius;
  30689. // normal
  30690. if (diameterTop === 0 && i === subdivisions) {
  30691. // if no top cap, reuse former normals
  30692. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  30693. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  30694. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  30695. }
  30696. else {
  30697. ringNormal.x = ringVertex.x;
  30698. ringNormal.z = ringVertex.z;
  30699. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  30700. ringNormal.normalize();
  30701. }
  30702. // keep first ring vertex values for enclose
  30703. if (j === 0) {
  30704. ringFirstVertex.copyFrom(ringVertex);
  30705. ringFirstNormal.copyFrom(ringNormal);
  30706. }
  30707. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30708. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  30709. if (hasRings) {
  30710. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  30711. }
  30712. else {
  30713. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  30714. }
  30715. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  30716. if (faceColors) {
  30717. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  30718. }
  30719. }
  30720. // if enclose, add four vertices and their dedicated normals
  30721. if (arc !== 1 && enclose) {
  30722. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30723. positions.push(0, ringVertex.y, 0);
  30724. positions.push(0, ringVertex.y, 0);
  30725. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  30726. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  30727. quadNormal.normalize();
  30728. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30729. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  30730. quadNormal.normalize();
  30731. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30732. if (hasRings) {
  30733. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  30734. }
  30735. else {
  30736. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  30737. }
  30738. uvs.push(faceUV[s + 1].x, v);
  30739. uvs.push(faceUV[s + 1].z, v);
  30740. if (hasRings) {
  30741. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  30742. }
  30743. else {
  30744. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  30745. }
  30746. uvs.push(faceUV[s + 2].x, v);
  30747. uvs.push(faceUV[s + 2].z, v);
  30748. if (faceColors) {
  30749. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30750. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30751. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30752. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30753. }
  30754. }
  30755. if (cs !== s) {
  30756. cs = s;
  30757. }
  30758. }
  30759. }
  30760. // indices
  30761. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  30762. var s;
  30763. i = 0;
  30764. for (s = 0; s < subdivisions; s++) {
  30765. for (j = 0; j < tessellation; j++) {
  30766. var i0 = i * (e + 1) + j;
  30767. var i1 = (i + 1) * (e + 1) + j;
  30768. var i2 = i * (e + 1) + (j + 1);
  30769. var i3 = (i + 1) * (e + 1) + (j + 1);
  30770. indices.push(i0, i1, i2);
  30771. indices.push(i3, i2, i1);
  30772. }
  30773. if (arc !== 1 && enclose) {
  30774. indices.push(i0 + 2, i1 + 2, i2 + 2);
  30775. indices.push(i3 + 2, i2 + 2, i1 + 2);
  30776. indices.push(i0 + 4, i1 + 4, i2 + 4);
  30777. indices.push(i3 + 4, i2 + 4, i1 + 4);
  30778. }
  30779. i = (hasRings) ? (i + 2) : (i + 1);
  30780. }
  30781. // Caps
  30782. var createCylinderCap = function (isTop) {
  30783. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  30784. if (radius === 0) {
  30785. return;
  30786. }
  30787. // Cap positions, normals & uvs
  30788. var angle;
  30789. var circleVector;
  30790. var i;
  30791. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  30792. var c;
  30793. if (faceColors) {
  30794. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  30795. }
  30796. // cap center
  30797. var vbase = positions.length / 3;
  30798. var offset = isTop ? height / 2 : -height / 2;
  30799. var center = new BABYLON.Vector3(0, offset, 0);
  30800. positions.push(center.x, center.y, center.z);
  30801. normals.push(0, isTop ? 1 : -1, 0);
  30802. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  30803. if (faceColors) {
  30804. colors.push(c.r, c.g, c.b, c.a);
  30805. }
  30806. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  30807. for (i = 0; i <= tessellation; i++) {
  30808. angle = Math.PI * 2 * i * arc / tessellation;
  30809. var cos = Math.cos(-angle);
  30810. var sin = Math.sin(-angle);
  30811. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  30812. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  30813. positions.push(circleVector.x, circleVector.y, circleVector.z);
  30814. normals.push(0, isTop ? 1 : -1, 0);
  30815. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  30816. if (faceColors) {
  30817. colors.push(c.r, c.g, c.b, c.a);
  30818. }
  30819. }
  30820. // Cap indices
  30821. for (i = 0; i < tessellation; i++) {
  30822. if (!isTop) {
  30823. indices.push(vbase);
  30824. indices.push(vbase + (i + 1));
  30825. indices.push(vbase + (i + 2));
  30826. }
  30827. else {
  30828. indices.push(vbase);
  30829. indices.push(vbase + (i + 2));
  30830. indices.push(vbase + (i + 1));
  30831. }
  30832. }
  30833. };
  30834. // add caps to geometry
  30835. createCylinderCap(false);
  30836. createCylinderCap(true);
  30837. // Sides
  30838. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30839. var vertexData = new VertexData();
  30840. vertexData.indices = indices;
  30841. vertexData.positions = positions;
  30842. vertexData.normals = normals;
  30843. vertexData.uvs = uvs;
  30844. if (faceColors) {
  30845. vertexData.colors = colors;
  30846. }
  30847. return vertexData;
  30848. };
  30849. VertexData.CreateTorus = function (options) {
  30850. var indices = [];
  30851. var positions = [];
  30852. var normals = [];
  30853. var uvs = [];
  30854. var diameter = options.diameter || 1;
  30855. var thickness = options.thickness || 0.5;
  30856. var tessellation = options.tessellation || 16;
  30857. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30858. var stride = tessellation + 1;
  30859. for (var i = 0; i <= tessellation; i++) {
  30860. var u = i / tessellation;
  30861. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30862. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30863. for (var j = 0; j <= tessellation; j++) {
  30864. var v = 1 - j / tessellation;
  30865. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30866. var dx = Math.cos(innerAngle);
  30867. var dy = Math.sin(innerAngle);
  30868. // Create a vertex.
  30869. var normal = new BABYLON.Vector3(dx, dy, 0);
  30870. var position = normal.scale(thickness / 2);
  30871. var textureCoordinate = new BABYLON.Vector2(u, v);
  30872. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30873. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30874. positions.push(position.x, position.y, position.z);
  30875. normals.push(normal.x, normal.y, normal.z);
  30876. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30877. // And create indices for two triangles.
  30878. var nextI = (i + 1) % stride;
  30879. var nextJ = (j + 1) % stride;
  30880. indices.push(i * stride + j);
  30881. indices.push(i * stride + nextJ);
  30882. indices.push(nextI * stride + j);
  30883. indices.push(i * stride + nextJ);
  30884. indices.push(nextI * stride + nextJ);
  30885. indices.push(nextI * stride + j);
  30886. }
  30887. }
  30888. // Sides
  30889. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30890. // Result
  30891. var vertexData = new VertexData();
  30892. vertexData.indices = indices;
  30893. vertexData.positions = positions;
  30894. vertexData.normals = normals;
  30895. vertexData.uvs = uvs;
  30896. return vertexData;
  30897. };
  30898. VertexData.CreateLineSystem = function (options) {
  30899. var indices = [];
  30900. var positions = [];
  30901. var lines = options.lines;
  30902. var idx = 0;
  30903. for (var l = 0; l < lines.length; l++) {
  30904. var points = lines[l];
  30905. for (var index = 0; index < points.length; index++) {
  30906. positions.push(points[index].x, points[index].y, points[index].z);
  30907. if (index > 0) {
  30908. indices.push(idx - 1);
  30909. indices.push(idx);
  30910. }
  30911. idx++;
  30912. }
  30913. }
  30914. var vertexData = new VertexData();
  30915. vertexData.indices = indices;
  30916. vertexData.positions = positions;
  30917. return vertexData;
  30918. };
  30919. VertexData.CreateDashedLines = function (options) {
  30920. var dashSize = options.dashSize || 3;
  30921. var gapSize = options.gapSize || 1;
  30922. var dashNb = options.dashNb || 200;
  30923. var points = options.points;
  30924. var positions = new Array();
  30925. var indices = new Array();
  30926. var curvect = BABYLON.Vector3.Zero();
  30927. var lg = 0;
  30928. var nb = 0;
  30929. var shft = 0;
  30930. var dashshft = 0;
  30931. var curshft = 0;
  30932. var idx = 0;
  30933. var i = 0;
  30934. for (i = 0; i < points.length - 1; i++) {
  30935. points[i + 1].subtractToRef(points[i], curvect);
  30936. lg += curvect.length();
  30937. }
  30938. shft = lg / dashNb;
  30939. dashshft = dashSize * shft / (dashSize + gapSize);
  30940. for (i = 0; i < points.length - 1; i++) {
  30941. points[i + 1].subtractToRef(points[i], curvect);
  30942. nb = Math.floor(curvect.length() / shft);
  30943. curvect.normalize();
  30944. for (var j = 0; j < nb; j++) {
  30945. curshft = shft * j;
  30946. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  30947. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  30948. indices.push(idx, idx + 1);
  30949. idx += 2;
  30950. }
  30951. }
  30952. // Result
  30953. var vertexData = new VertexData();
  30954. vertexData.positions = positions;
  30955. vertexData.indices = indices;
  30956. return vertexData;
  30957. };
  30958. VertexData.CreateGround = function (options) {
  30959. var indices = [];
  30960. var positions = [];
  30961. var normals = [];
  30962. var uvs = [];
  30963. var row, col;
  30964. var width = options.width || 1;
  30965. var height = options.height || 1;
  30966. var subdivisions = options.subdivisions || 1;
  30967. for (row = 0; row <= subdivisions; row++) {
  30968. for (col = 0; col <= subdivisions; col++) {
  30969. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  30970. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30971. positions.push(position.x, position.y, position.z);
  30972. normals.push(normal.x, normal.y, normal.z);
  30973. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  30974. }
  30975. }
  30976. for (row = 0; row < subdivisions; row++) {
  30977. for (col = 0; col < subdivisions; col++) {
  30978. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  30979. indices.push(col + 1 + row * (subdivisions + 1));
  30980. indices.push(col + row * (subdivisions + 1));
  30981. indices.push(col + (row + 1) * (subdivisions + 1));
  30982. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  30983. indices.push(col + row * (subdivisions + 1));
  30984. }
  30985. }
  30986. // Result
  30987. var vertexData = new VertexData();
  30988. vertexData.indices = indices;
  30989. vertexData.positions = positions;
  30990. vertexData.normals = normals;
  30991. vertexData.uvs = uvs;
  30992. return vertexData;
  30993. };
  30994. VertexData.CreateTiledGround = function (options) {
  30995. var xmin = options.xmin || -1.0;
  30996. var zmin = options.zmin || -1.0;
  30997. var xmax = options.xmax || 1.0;
  30998. var zmax = options.zmax || 1.0;
  30999. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  31000. var precision = options.precision || { w: 1, h: 1 };
  31001. var indices = [];
  31002. var positions = [];
  31003. var normals = [];
  31004. var uvs = [];
  31005. var row, col, tileRow, tileCol;
  31006. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  31007. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  31008. precision.w = (precision.w < 1) ? 1 : precision.w;
  31009. precision.h = (precision.h < 1) ? 1 : precision.h;
  31010. var tileSize = {
  31011. 'w': (xmax - xmin) / subdivisions.w,
  31012. 'h': (zmax - zmin) / subdivisions.h
  31013. };
  31014. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  31015. // Indices
  31016. var base = positions.length / 3;
  31017. var rowLength = precision.w + 1;
  31018. for (row = 0; row < precision.h; row++) {
  31019. for (col = 0; col < precision.w; col++) {
  31020. var square = [
  31021. base + col + row * rowLength,
  31022. base + (col + 1) + row * rowLength,
  31023. base + (col + 1) + (row + 1) * rowLength,
  31024. base + col + (row + 1) * rowLength
  31025. ];
  31026. indices.push(square[1]);
  31027. indices.push(square[2]);
  31028. indices.push(square[3]);
  31029. indices.push(square[0]);
  31030. indices.push(square[1]);
  31031. indices.push(square[3]);
  31032. }
  31033. }
  31034. // Position, normals and uvs
  31035. var position = BABYLON.Vector3.Zero();
  31036. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31037. for (row = 0; row <= precision.h; row++) {
  31038. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  31039. for (col = 0; col <= precision.w; col++) {
  31040. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  31041. position.y = 0;
  31042. positions.push(position.x, position.y, position.z);
  31043. normals.push(normal.x, normal.y, normal.z);
  31044. uvs.push(col / precision.w, row / precision.h);
  31045. }
  31046. }
  31047. }
  31048. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  31049. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  31050. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  31051. }
  31052. }
  31053. // Result
  31054. var vertexData = new VertexData();
  31055. vertexData.indices = indices;
  31056. vertexData.positions = positions;
  31057. vertexData.normals = normals;
  31058. vertexData.uvs = uvs;
  31059. return vertexData;
  31060. };
  31061. VertexData.CreateGroundFromHeightMap = function (options) {
  31062. var indices = [];
  31063. var positions = [];
  31064. var normals = [];
  31065. var uvs = [];
  31066. var row, col;
  31067. // Vertices
  31068. for (row = 0; row <= options.subdivisions; row++) {
  31069. for (col = 0; col <= options.subdivisions; col++) {
  31070. 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));
  31071. // Compute height
  31072. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  31073. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  31074. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  31075. var r = options.buffer[pos] / 255.0;
  31076. var g = options.buffer[pos + 1] / 255.0;
  31077. var b = options.buffer[pos + 2] / 255.0;
  31078. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  31079. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  31080. // Add vertex
  31081. positions.push(position.x, position.y, position.z);
  31082. normals.push(0, 0, 0);
  31083. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  31084. }
  31085. }
  31086. // Indices
  31087. for (row = 0; row < options.subdivisions; row++) {
  31088. for (col = 0; col < options.subdivisions; col++) {
  31089. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31090. indices.push(col + 1 + row * (options.subdivisions + 1));
  31091. indices.push(col + row * (options.subdivisions + 1));
  31092. indices.push(col + (row + 1) * (options.subdivisions + 1));
  31093. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31094. indices.push(col + row * (options.subdivisions + 1));
  31095. }
  31096. }
  31097. // Normals
  31098. VertexData.ComputeNormals(positions, indices, normals);
  31099. // Result
  31100. var vertexData = new VertexData();
  31101. vertexData.indices = indices;
  31102. vertexData.positions = positions;
  31103. vertexData.normals = normals;
  31104. vertexData.uvs = uvs;
  31105. return vertexData;
  31106. };
  31107. VertexData.CreatePlane = function (options) {
  31108. var indices = [];
  31109. var positions = [];
  31110. var normals = [];
  31111. var uvs = [];
  31112. var width = options.width || options.size || 1;
  31113. var height = options.height || options.size || 1;
  31114. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31115. // Vertices
  31116. var halfWidth = width / 2.0;
  31117. var halfHeight = height / 2.0;
  31118. positions.push(-halfWidth, -halfHeight, 0);
  31119. normals.push(0, 0, -1.0);
  31120. uvs.push(0.0, 0.0);
  31121. positions.push(halfWidth, -halfHeight, 0);
  31122. normals.push(0, 0, -1.0);
  31123. uvs.push(1.0, 0.0);
  31124. positions.push(halfWidth, halfHeight, 0);
  31125. normals.push(0, 0, -1.0);
  31126. uvs.push(1.0, 1.0);
  31127. positions.push(-halfWidth, halfHeight, 0);
  31128. normals.push(0, 0, -1.0);
  31129. uvs.push(0.0, 1.0);
  31130. // Indices
  31131. indices.push(0);
  31132. indices.push(1);
  31133. indices.push(2);
  31134. indices.push(0);
  31135. indices.push(2);
  31136. indices.push(3);
  31137. // Sides
  31138. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31139. // Result
  31140. var vertexData = new VertexData();
  31141. vertexData.indices = indices;
  31142. vertexData.positions = positions;
  31143. vertexData.normals = normals;
  31144. vertexData.uvs = uvs;
  31145. return vertexData;
  31146. };
  31147. VertexData.CreateDisc = function (options) {
  31148. var positions = [];
  31149. var indices = [];
  31150. var normals = [];
  31151. var uvs = [];
  31152. var radius = options.radius || 0.5;
  31153. var tessellation = options.tessellation || 64;
  31154. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31155. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31156. // positions and uvs
  31157. positions.push(0, 0, 0); // disc center first
  31158. uvs.push(0.5, 0.5);
  31159. var theta = Math.PI * 2 * arc;
  31160. var step = theta / tessellation;
  31161. for (var a = 0; a < theta; a += step) {
  31162. var x = Math.cos(a);
  31163. var y = Math.sin(a);
  31164. var u = (x + 1) / 2;
  31165. var v = (1 - y) / 2;
  31166. positions.push(radius * x, radius * y, 0);
  31167. uvs.push(u, v);
  31168. }
  31169. if (arc === 1) {
  31170. positions.push(positions[3], positions[4], positions[5]); // close the circle
  31171. uvs.push(uvs[2], uvs[3]);
  31172. }
  31173. //indices
  31174. var vertexNb = positions.length / 3;
  31175. for (var i = 1; i < vertexNb - 1; i++) {
  31176. indices.push(i + 1, 0, i);
  31177. }
  31178. // result
  31179. VertexData.ComputeNormals(positions, indices, normals);
  31180. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31181. var vertexData = new VertexData();
  31182. vertexData.indices = indices;
  31183. vertexData.positions = positions;
  31184. vertexData.normals = normals;
  31185. vertexData.uvs = uvs;
  31186. return vertexData;
  31187. };
  31188. VertexData.CreateIcoSphere = function (options) {
  31189. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31190. var radius = options.radius || 1;
  31191. var flat = (options.flat === undefined) ? true : options.flat;
  31192. var subdivisions = options.subdivisions || 4;
  31193. var radiusX = options.radiusX || radius;
  31194. var radiusY = options.radiusY || radius;
  31195. var radiusZ = options.radiusZ || radius;
  31196. var t = (1 + Math.sqrt(5)) / 2;
  31197. // 12 vertex x,y,z
  31198. var ico_vertices = [
  31199. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  31200. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  31201. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  31202. ];
  31203. // index of 3 vertex makes a face of icopshere
  31204. var ico_indices = [
  31205. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  31206. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  31207. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  31208. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  31209. ];
  31210. // vertex for uv have aliased position, not for UV
  31211. var vertices_unalias_id = [
  31212. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  31213. // vertex alias
  31214. 0,
  31215. 2,
  31216. 3,
  31217. 3,
  31218. 3,
  31219. 4,
  31220. 7,
  31221. 8,
  31222. 9,
  31223. 9,
  31224. 10,
  31225. 11 // 23: B + 12
  31226. ];
  31227. // uv as integer step (not pixels !)
  31228. var ico_vertexuv = [
  31229. 5, 1, 3, 1, 6, 4, 0, 0,
  31230. 5, 3, 4, 2, 2, 2, 4, 0,
  31231. 2, 0, 1, 1, 6, 0, 6, 2,
  31232. // vertex alias (for same vertex on different faces)
  31233. 0, 4,
  31234. 3, 3,
  31235. 4, 4,
  31236. 3, 1,
  31237. 4, 2,
  31238. 4, 4,
  31239. 0, 2,
  31240. 1, 1,
  31241. 2, 2,
  31242. 3, 3,
  31243. 1, 3,
  31244. 2, 4 // 23: B + 12
  31245. ];
  31246. // Vertices[0, 1, ...9, A, B] : position on UV plane
  31247. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  31248. // First island of uv mapping
  31249. // v = 4h 3+ 2
  31250. // v = 3h 9+ 4
  31251. // v = 2h 9+ 5 B
  31252. // v = 1h 9 1 0
  31253. // v = 0h 3 8 7 A
  31254. // u = 0 1 2 3 4 5 6 *a
  31255. // Second island of uv mapping
  31256. // v = 4h 0+ B+ 4+
  31257. // v = 3h A+ 2+
  31258. // v = 2h 7+ 6 3+
  31259. // v = 1h 8+ 3+
  31260. // v = 0h
  31261. // u = 0 1 2 3 4 5 6 *a
  31262. // Face layout on texture UV mapping
  31263. // ============
  31264. // \ 4 /\ 16 / ======
  31265. // \ / \ / /\ 11 /
  31266. // \/ 7 \/ / \ /
  31267. // ======= / 10 \/
  31268. // /\ 17 /\ =======
  31269. // / \ / \ \ 15 /\
  31270. // / 8 \/ 12 \ \ / \
  31271. // ============ \/ 6 \
  31272. // \ 18 /\ ============
  31273. // \ / \ \ 5 /\ 0 /
  31274. // \/ 13 \ \ / \ /
  31275. // ======= \/ 1 \/
  31276. // =============
  31277. // /\ 19 /\ 2 /\
  31278. // / \ / \ / \
  31279. // / 14 \/ 9 \/ 3 \
  31280. // ===================
  31281. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  31282. var ustep = 138 / 1024;
  31283. var vstep = 239 / 1024;
  31284. var uoffset = 60 / 1024;
  31285. var voffset = 26 / 1024;
  31286. // Second island should have margin, not to touch the first island
  31287. // avoid any borderline artefact in pixel rounding
  31288. var island_u_offset = -40 / 1024;
  31289. var island_v_offset = +20 / 1024;
  31290. // face is either island 0 or 1 :
  31291. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  31292. var island = [
  31293. 0, 0, 0, 0, 1,
  31294. 0, 0, 1, 1, 0,
  31295. 0, 0, 1, 1, 0,
  31296. 0, 1, 1, 1, 0 // 15 - 19
  31297. ];
  31298. var indices = [];
  31299. var positions = [];
  31300. var normals = [];
  31301. var uvs = [];
  31302. var current_indice = 0;
  31303. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  31304. var face_vertex_pos = new Array(3);
  31305. var face_vertex_uv = new Array(3);
  31306. var v012;
  31307. for (v012 = 0; v012 < 3; v012++) {
  31308. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  31309. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  31310. }
  31311. // create all with normals
  31312. for (var face = 0; face < 20; face++) {
  31313. // 3 vertex per face
  31314. for (v012 = 0; v012 < 3; v012++) {
  31315. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  31316. var v_id = ico_indices[3 * face + v012];
  31317. // vertex have 3D position (x,y,z)
  31318. 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]);
  31319. // Normalize to get normal, then scale to radius
  31320. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  31321. // uv Coordinates from vertex ID
  31322. 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);
  31323. }
  31324. // Subdivide the face (interpolate pos, norm, uv)
  31325. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  31326. // - norm is linear interpolation of vertex corner normal
  31327. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  31328. // - uv is linear interpolation
  31329. //
  31330. // Topology is as below for sub-divide by 2
  31331. // vertex shown as v0,v1,v2
  31332. // interp index is i1 to progress in range [v0,v1[
  31333. // interp index is i2 to progress in range [v0,v2[
  31334. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  31335. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31336. //
  31337. //
  31338. // i2 v2
  31339. // ^ ^
  31340. // / / \
  31341. // / / \
  31342. // / / \
  31343. // / / (0,1) \
  31344. // / #---------\
  31345. // / / \ (0,0)'/ \
  31346. // / / \ / \
  31347. // / / \ / \
  31348. // / / (0,0) \ / (1,0) \
  31349. // / #---------#---------\
  31350. // v0 v1
  31351. //
  31352. // --------------------> i1
  31353. //
  31354. // interp of (i1,i2):
  31355. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  31356. // along i1 : lerp(x0,x1, i1/(S-i2))
  31357. //
  31358. // centroid of triangle is needed to get help normal computation
  31359. // (c1,c2) are used for centroid location
  31360. var interp_vertex = function (i1, i2, c1, c2) {
  31361. // vertex is interpolated from
  31362. // - face_vertex_pos[0..2]
  31363. // - face_vertex_uv[0..2]
  31364. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  31365. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  31366. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  31367. pos_interp.normalize();
  31368. var vertex_normal;
  31369. if (flat) {
  31370. // in flat mode, recalculate normal as face centroid normal
  31371. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  31372. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  31373. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  31374. }
  31375. else {
  31376. // in smooth mode, recalculate normal from each single vertex position
  31377. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  31378. }
  31379. // Vertex normal need correction due to X,Y,Z radius scaling
  31380. vertex_normal.x /= radiusX;
  31381. vertex_normal.y /= radiusY;
  31382. vertex_normal.z /= radiusZ;
  31383. vertex_normal.normalize();
  31384. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  31385. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  31386. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  31387. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  31388. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  31389. uvs.push(uv_interp.x, uv_interp.y);
  31390. // push each vertex has member of a face
  31391. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  31392. indices.push(current_indice);
  31393. current_indice++;
  31394. };
  31395. for (var i2 = 0; i2 < subdivisions; i2++) {
  31396. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  31397. // face : (i1,i2) for /\ :
  31398. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  31399. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31400. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31401. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31402. if (i1 + i2 + 1 < subdivisions) {
  31403. // face : (i1,i2)' for \/ :
  31404. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31405. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31406. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31407. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31408. }
  31409. }
  31410. }
  31411. }
  31412. // Sides
  31413. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31414. // Result
  31415. var vertexData = new VertexData();
  31416. vertexData.indices = indices;
  31417. vertexData.positions = positions;
  31418. vertexData.normals = normals;
  31419. vertexData.uvs = uvs;
  31420. return vertexData;
  31421. };
  31422. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  31423. VertexData.CreatePolyhedron = function (options) {
  31424. // provided polyhedron types :
  31425. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  31426. // 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)
  31427. var polyhedra = [];
  31428. 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]] };
  31429. 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]] };
  31430. polyhedra[2] = {
  31431. 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]],
  31432. 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]]
  31433. };
  31434. polyhedra[3] = {
  31435. 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]],
  31436. 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]]
  31437. };
  31438. polyhedra[4] = {
  31439. 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]],
  31440. 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]]
  31441. };
  31442. 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]] };
  31443. 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]] };
  31444. 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]] };
  31445. 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]] };
  31446. 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]] };
  31447. 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]] };
  31448. 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]] };
  31449. 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]] };
  31450. 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]] };
  31451. polyhedra[14] = {
  31452. 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]],
  31453. 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]]
  31454. };
  31455. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  31456. var size = options.size;
  31457. var sizeX = options.sizeX || size || 1;
  31458. var sizeY = options.sizeY || size || 1;
  31459. var sizeZ = options.sizeZ || size || 1;
  31460. var data = options.custom || polyhedra[type];
  31461. var nbfaces = data.face.length;
  31462. var faceUV = options.faceUV || new Array(nbfaces);
  31463. var faceColors = options.faceColors;
  31464. var flat = (options.flat === undefined) ? true : options.flat;
  31465. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31466. var positions = [];
  31467. var indices = [];
  31468. var normals = [];
  31469. var uvs = [];
  31470. var colors = [];
  31471. var index = 0;
  31472. var faceIdx = 0; // face cursor in the array "indexes"
  31473. var indexes = [];
  31474. var i = 0;
  31475. var f = 0;
  31476. var u, v, ang, x, y, tmp;
  31477. // default face colors and UV if undefined
  31478. if (flat) {
  31479. for (f = 0; f < nbfaces; f++) {
  31480. if (faceColors && faceColors[f] === undefined) {
  31481. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31482. }
  31483. if (faceUV && faceUV[f] === undefined) {
  31484. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31485. }
  31486. }
  31487. }
  31488. if (!flat) {
  31489. for (i = 0; i < data.vertex.length; i++) {
  31490. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  31491. uvs.push(0, 0);
  31492. }
  31493. for (f = 0; f < nbfaces; f++) {
  31494. for (i = 0; i < data.face[f].length - 2; i++) {
  31495. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  31496. }
  31497. }
  31498. }
  31499. else {
  31500. for (f = 0; f < nbfaces; f++) {
  31501. var fl = data.face[f].length; // number of vertices of the current face
  31502. ang = 2 * Math.PI / fl;
  31503. x = 0.5 * Math.tan(ang / 2);
  31504. y = 0.5;
  31505. // positions, uvs, colors
  31506. for (i = 0; i < fl; i++) {
  31507. // positions
  31508. 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);
  31509. indexes.push(index);
  31510. index++;
  31511. // uvs
  31512. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  31513. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  31514. uvs.push(u, v);
  31515. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  31516. y = x * Math.sin(ang) + y * Math.cos(ang);
  31517. x = tmp;
  31518. // colors
  31519. if (faceColors) {
  31520. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  31521. }
  31522. }
  31523. // indices from indexes
  31524. for (i = 0; i < fl - 2; i++) {
  31525. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  31526. }
  31527. faceIdx += fl;
  31528. }
  31529. }
  31530. VertexData.ComputeNormals(positions, indices, normals);
  31531. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31532. var vertexData = new VertexData();
  31533. vertexData.positions = positions;
  31534. vertexData.indices = indices;
  31535. vertexData.normals = normals;
  31536. vertexData.uvs = uvs;
  31537. if (faceColors && flat) {
  31538. vertexData.colors = colors;
  31539. }
  31540. return vertexData;
  31541. };
  31542. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  31543. VertexData.CreateTorusKnot = function (options) {
  31544. var indices = [];
  31545. var positions = [];
  31546. var normals = [];
  31547. var uvs = [];
  31548. var radius = options.radius || 2;
  31549. var tube = options.tube || 0.5;
  31550. var radialSegments = options.radialSegments || 32;
  31551. var tubularSegments = options.tubularSegments || 32;
  31552. var p = options.p || 2;
  31553. var q = options.q || 3;
  31554. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31555. // Helper
  31556. var getPos = function (angle) {
  31557. var cu = Math.cos(angle);
  31558. var su = Math.sin(angle);
  31559. var quOverP = q / p * angle;
  31560. var cs = Math.cos(quOverP);
  31561. var tx = radius * (2 + cs) * 0.5 * cu;
  31562. var ty = radius * (2 + cs) * su * 0.5;
  31563. var tz = radius * Math.sin(quOverP) * 0.5;
  31564. return new BABYLON.Vector3(tx, ty, tz);
  31565. };
  31566. // Vertices
  31567. var i;
  31568. var j;
  31569. for (i = 0; i <= radialSegments; i++) {
  31570. var modI = i % radialSegments;
  31571. var u = modI / radialSegments * 2 * p * Math.PI;
  31572. var p1 = getPos(u);
  31573. var p2 = getPos(u + 0.01);
  31574. var tang = p2.subtract(p1);
  31575. var n = p2.add(p1);
  31576. var bitan = BABYLON.Vector3.Cross(tang, n);
  31577. n = BABYLON.Vector3.Cross(bitan, tang);
  31578. bitan.normalize();
  31579. n.normalize();
  31580. for (j = 0; j < tubularSegments; j++) {
  31581. var modJ = j % tubularSegments;
  31582. var v = modJ / tubularSegments * 2 * Math.PI;
  31583. var cx = -tube * Math.cos(v);
  31584. var cy = tube * Math.sin(v);
  31585. positions.push(p1.x + cx * n.x + cy * bitan.x);
  31586. positions.push(p1.y + cx * n.y + cy * bitan.y);
  31587. positions.push(p1.z + cx * n.z + cy * bitan.z);
  31588. uvs.push(i / radialSegments);
  31589. uvs.push(j / tubularSegments);
  31590. }
  31591. }
  31592. for (i = 0; i < radialSegments; i++) {
  31593. for (j = 0; j < tubularSegments; j++) {
  31594. var jNext = (j + 1) % tubularSegments;
  31595. var a = i * tubularSegments + j;
  31596. var b = (i + 1) * tubularSegments + j;
  31597. var c = (i + 1) * tubularSegments + jNext;
  31598. var d = i * tubularSegments + jNext;
  31599. indices.push(d);
  31600. indices.push(b);
  31601. indices.push(a);
  31602. indices.push(d);
  31603. indices.push(c);
  31604. indices.push(b);
  31605. }
  31606. }
  31607. // Normals
  31608. VertexData.ComputeNormals(positions, indices, normals);
  31609. // Sides
  31610. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31611. // Result
  31612. var vertexData = new VertexData();
  31613. vertexData.indices = indices;
  31614. vertexData.positions = positions;
  31615. vertexData.normals = normals;
  31616. vertexData.uvs = uvs;
  31617. return vertexData;
  31618. };
  31619. // Tools
  31620. /**
  31621. * @param {any} - positions (number[] or Float32Array)
  31622. * @param {any} - indices (number[] or Uint16Array)
  31623. * @param {any} - normals (number[] or Float32Array)
  31624. */
  31625. VertexData.ComputeNormals = function (positions, indices, normals) {
  31626. var index = 0;
  31627. var p1p2x = 0.0;
  31628. var p1p2y = 0.0;
  31629. var p1p2z = 0.0;
  31630. var p3p2x = 0.0;
  31631. var p3p2y = 0.0;
  31632. var p3p2z = 0.0;
  31633. var faceNormalx = 0.0;
  31634. var faceNormaly = 0.0;
  31635. var faceNormalz = 0.0;
  31636. var length = 0.0;
  31637. var i1 = 0;
  31638. var i2 = 0;
  31639. var i3 = 0;
  31640. for (index = 0; index < positions.length; index++) {
  31641. normals[index] = 0.0;
  31642. }
  31643. // indice triplet = 1 face
  31644. var nbFaces = indices.length / 3;
  31645. for (index = 0; index < nbFaces; index++) {
  31646. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  31647. i2 = indices[index * 3 + 1];
  31648. i3 = indices[index * 3 + 2];
  31649. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  31650. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  31651. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  31652. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  31653. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  31654. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  31655. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  31656. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  31657. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  31658. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31659. length = (length === 0) ? 1.0 : length;
  31660. faceNormalx /= length; // normalize this normal
  31661. faceNormaly /= length;
  31662. faceNormalz /= length;
  31663. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  31664. normals[i1 * 3 + 1] += faceNormaly;
  31665. normals[i1 * 3 + 2] += faceNormalz;
  31666. normals[i2 * 3] += faceNormalx;
  31667. normals[i2 * 3 + 1] += faceNormaly;
  31668. normals[i2 * 3 + 2] += faceNormalz;
  31669. normals[i3 * 3] += faceNormalx;
  31670. normals[i3 * 3 + 1] += faceNormaly;
  31671. normals[i3 * 3 + 2] += faceNormalz;
  31672. }
  31673. // last normalization of each normal
  31674. for (index = 0; index < normals.length / 3; index++) {
  31675. faceNormalx = normals[index * 3];
  31676. faceNormaly = normals[index * 3 + 1];
  31677. faceNormalz = normals[index * 3 + 2];
  31678. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31679. length = (length === 0) ? 1.0 : length;
  31680. faceNormalx /= length;
  31681. faceNormaly /= length;
  31682. faceNormalz /= length;
  31683. normals[index * 3] = faceNormalx;
  31684. normals[index * 3 + 1] = faceNormaly;
  31685. normals[index * 3 + 2] = faceNormalz;
  31686. }
  31687. };
  31688. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  31689. var li = indices.length;
  31690. var ln = normals.length;
  31691. var i;
  31692. var n;
  31693. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31694. switch (sideOrientation) {
  31695. case BABYLON.Mesh.FRONTSIDE:
  31696. // nothing changed
  31697. break;
  31698. case BABYLON.Mesh.BACKSIDE:
  31699. var tmp;
  31700. // indices
  31701. for (i = 0; i < li; i += 3) {
  31702. tmp = indices[i];
  31703. indices[i] = indices[i + 2];
  31704. indices[i + 2] = tmp;
  31705. }
  31706. // normals
  31707. for (n = 0; n < ln; n++) {
  31708. normals[n] = -normals[n];
  31709. }
  31710. break;
  31711. case BABYLON.Mesh.DOUBLESIDE:
  31712. // positions
  31713. var lp = positions.length;
  31714. var l = lp / 3;
  31715. for (var p = 0; p < lp; p++) {
  31716. positions[lp + p] = positions[p];
  31717. }
  31718. // indices
  31719. for (i = 0; i < li; i += 3) {
  31720. indices[i + li] = indices[i + 2] + l;
  31721. indices[i + 1 + li] = indices[i + 1] + l;
  31722. indices[i + 2 + li] = indices[i] + l;
  31723. }
  31724. // normals
  31725. for (n = 0; n < ln; n++) {
  31726. normals[ln + n] = -normals[n];
  31727. }
  31728. // uvs
  31729. var lu = uvs.length;
  31730. for (var u = 0; u < lu; u++) {
  31731. uvs[u + lu] = uvs[u];
  31732. }
  31733. break;
  31734. }
  31735. };
  31736. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  31737. var vertexData = new VertexData();
  31738. // positions
  31739. var positions = parsedVertexData.positions;
  31740. if (positions) {
  31741. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  31742. }
  31743. // normals
  31744. var normals = parsedVertexData.normals;
  31745. if (normals) {
  31746. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  31747. }
  31748. // uvs
  31749. var uvs = parsedVertexData.uvs;
  31750. if (uvs) {
  31751. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  31752. }
  31753. // uv2s
  31754. var uv2s = parsedVertexData.uv2s;
  31755. if (uv2s) {
  31756. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  31757. }
  31758. // uv3s
  31759. var uv3s = parsedVertexData.uv3s;
  31760. if (uv3s) {
  31761. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  31762. }
  31763. // uv4s
  31764. var uv4s = parsedVertexData.uv4s;
  31765. if (uv4s) {
  31766. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  31767. }
  31768. // uv5s
  31769. var uv5s = parsedVertexData.uv5s;
  31770. if (uv5s) {
  31771. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  31772. }
  31773. // uv6s
  31774. var uv6s = parsedVertexData.uv6s;
  31775. if (uv6s) {
  31776. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  31777. }
  31778. // colors
  31779. var colors = parsedVertexData.colors;
  31780. if (colors) {
  31781. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  31782. }
  31783. // matricesIndices
  31784. var matricesIndices = parsedVertexData.matricesIndices;
  31785. if (matricesIndices) {
  31786. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  31787. }
  31788. // matricesWeights
  31789. var matricesWeights = parsedVertexData.matricesWeights;
  31790. if (matricesWeights) {
  31791. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  31792. }
  31793. // indices
  31794. var indices = parsedVertexData.indices;
  31795. if (indices) {
  31796. vertexData.indices = indices;
  31797. }
  31798. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  31799. };
  31800. return VertexData;
  31801. })();
  31802. BABYLON.VertexData = VertexData;
  31803. })(BABYLON || (BABYLON = {}));
  31804. var BABYLON;
  31805. (function (BABYLON) {
  31806. var Tags = (function () {
  31807. function Tags() {
  31808. }
  31809. Tags.EnableFor = function (obj) {
  31810. obj._tags = obj._tags || {};
  31811. obj.hasTags = function () {
  31812. return Tags.HasTags(obj);
  31813. };
  31814. obj.addTags = function (tagsString) {
  31815. return Tags.AddTagsTo(obj, tagsString);
  31816. };
  31817. obj.removeTags = function (tagsString) {
  31818. return Tags.RemoveTagsFrom(obj, tagsString);
  31819. };
  31820. obj.matchesTagsQuery = function (tagsQuery) {
  31821. return Tags.MatchesQuery(obj, tagsQuery);
  31822. };
  31823. };
  31824. Tags.DisableFor = function (obj) {
  31825. delete obj._tags;
  31826. delete obj.hasTags;
  31827. delete obj.addTags;
  31828. delete obj.removeTags;
  31829. delete obj.matchesTagsQuery;
  31830. };
  31831. Tags.HasTags = function (obj) {
  31832. if (!obj._tags) {
  31833. return false;
  31834. }
  31835. return !BABYLON.Tools.IsEmpty(obj._tags);
  31836. };
  31837. Tags.GetTags = function (obj, asString) {
  31838. if (asString === void 0) { asString = true; }
  31839. if (!obj._tags) {
  31840. return null;
  31841. }
  31842. if (asString) {
  31843. var tagsArray = [];
  31844. for (var tag in obj._tags) {
  31845. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  31846. tagsArray.push(tag);
  31847. }
  31848. }
  31849. return tagsArray.join(" ");
  31850. }
  31851. else {
  31852. return obj._tags;
  31853. }
  31854. };
  31855. // the tags 'true' and 'false' are reserved and cannot be used as tags
  31856. // a tag cannot start with '||', '&&', and '!'
  31857. // it cannot contain whitespaces
  31858. Tags.AddTagsTo = function (obj, tagsString) {
  31859. if (!tagsString) {
  31860. return;
  31861. }
  31862. if (typeof tagsString !== "string") {
  31863. return;
  31864. }
  31865. var tags = tagsString.split(" ");
  31866. for (var t in tags) {
  31867. Tags._AddTagTo(obj, tags[t]);
  31868. }
  31869. };
  31870. Tags._AddTagTo = function (obj, tag) {
  31871. tag = tag.trim();
  31872. if (tag === "" || tag === "true" || tag === "false") {
  31873. return;
  31874. }
  31875. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  31876. return;
  31877. }
  31878. Tags.EnableFor(obj);
  31879. obj._tags[tag] = true;
  31880. };
  31881. Tags.RemoveTagsFrom = function (obj, tagsString) {
  31882. if (!Tags.HasTags(obj)) {
  31883. return;
  31884. }
  31885. var tags = tagsString.split(" ");
  31886. for (var t in tags) {
  31887. Tags._RemoveTagFrom(obj, tags[t]);
  31888. }
  31889. };
  31890. Tags._RemoveTagFrom = function (obj, tag) {
  31891. delete obj._tags[tag];
  31892. };
  31893. Tags.MatchesQuery = function (obj, tagsQuery) {
  31894. if (tagsQuery === undefined) {
  31895. return true;
  31896. }
  31897. if (tagsQuery === "") {
  31898. return Tags.HasTags(obj);
  31899. }
  31900. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  31901. };
  31902. return Tags;
  31903. })();
  31904. BABYLON.Tags = Tags;
  31905. })(BABYLON || (BABYLON = {}));
  31906. var BABYLON;
  31907. (function (BABYLON) {
  31908. var Internals;
  31909. (function (Internals) {
  31910. var AndOrNotEvaluator = (function () {
  31911. function AndOrNotEvaluator() {
  31912. }
  31913. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  31914. if (!query.match(/\([^\(\)]*\)/g)) {
  31915. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  31916. }
  31917. else {
  31918. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  31919. // remove parenthesis
  31920. r = r.slice(1, r.length - 1);
  31921. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  31922. });
  31923. }
  31924. if (query === "true") {
  31925. return true;
  31926. }
  31927. if (query === "false") {
  31928. return false;
  31929. }
  31930. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  31931. };
  31932. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  31933. evaluateCallback = evaluateCallback || (function (r) {
  31934. return r === "true" ? true : false;
  31935. });
  31936. var result;
  31937. var or = parenthesisContent.split("||");
  31938. for (var i in or) {
  31939. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  31940. var and = ori.split("&&");
  31941. if (and.length > 1) {
  31942. for (var j = 0; j < and.length; ++j) {
  31943. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  31944. if (andj !== "true" && andj !== "false") {
  31945. if (andj[0] === "!") {
  31946. result = !evaluateCallback(andj.substring(1));
  31947. }
  31948. else {
  31949. result = evaluateCallback(andj);
  31950. }
  31951. }
  31952. else {
  31953. result = andj === "true" ? true : false;
  31954. }
  31955. if (!result) {
  31956. ori = "false";
  31957. break;
  31958. }
  31959. }
  31960. }
  31961. if (result || ori === "true") {
  31962. result = true;
  31963. break;
  31964. }
  31965. // result equals false (or undefined)
  31966. if (ori !== "true" && ori !== "false") {
  31967. if (ori[0] === "!") {
  31968. result = !evaluateCallback(ori.substring(1));
  31969. }
  31970. else {
  31971. result = evaluateCallback(ori);
  31972. }
  31973. }
  31974. else {
  31975. result = ori === "true" ? true : false;
  31976. }
  31977. }
  31978. // the whole parenthesis scope is replaced by 'true' or 'false'
  31979. return result ? "true" : "false";
  31980. };
  31981. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  31982. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  31983. // remove whitespaces
  31984. r = r.replace(/[\s]/g, function () { return ""; });
  31985. return r.length % 2 ? "!" : "";
  31986. });
  31987. booleanString = booleanString.trim();
  31988. if (booleanString === "!true") {
  31989. booleanString = "false";
  31990. }
  31991. else if (booleanString === "!false") {
  31992. booleanString = "true";
  31993. }
  31994. return booleanString;
  31995. };
  31996. return AndOrNotEvaluator;
  31997. })();
  31998. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  31999. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32000. })(BABYLON || (BABYLON = {}));
  32001. var BABYLON;
  32002. (function (BABYLON) {
  32003. var PostProcessRenderPass = (function () {
  32004. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  32005. this._enabled = true;
  32006. this._refCount = 0;
  32007. this._name = name;
  32008. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  32009. this.setRenderList(renderList);
  32010. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  32011. this._renderTexture.onAfterRenderObservable.add(afterRender);
  32012. this._scene = scene;
  32013. this._renderList = renderList;
  32014. }
  32015. // private
  32016. PostProcessRenderPass.prototype._incRefCount = function () {
  32017. if (this._refCount === 0) {
  32018. this._scene.customRenderTargets.push(this._renderTexture);
  32019. }
  32020. return ++this._refCount;
  32021. };
  32022. PostProcessRenderPass.prototype._decRefCount = function () {
  32023. this._refCount--;
  32024. if (this._refCount <= 0) {
  32025. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  32026. }
  32027. return this._refCount;
  32028. };
  32029. PostProcessRenderPass.prototype._update = function () {
  32030. this.setRenderList(this._renderList);
  32031. };
  32032. // public
  32033. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  32034. this._renderTexture.renderList = renderList;
  32035. };
  32036. PostProcessRenderPass.prototype.getRenderTexture = function () {
  32037. return this._renderTexture;
  32038. };
  32039. return PostProcessRenderPass;
  32040. })();
  32041. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  32042. })(BABYLON || (BABYLON = {}));
  32043. var BABYLON;
  32044. (function (BABYLON) {
  32045. var PostProcessRenderEffect = (function () {
  32046. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  32047. this._engine = engine;
  32048. this._name = name;
  32049. this._singleInstance = singleInstance || true;
  32050. this._getPostProcess = getPostProcess;
  32051. this._cameras = [];
  32052. this._indicesForCamera = [];
  32053. this._postProcesses = {};
  32054. this._renderPasses = {};
  32055. this._renderEffectAsPasses = {};
  32056. }
  32057. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  32058. get: function () {
  32059. for (var index in this._postProcesses) {
  32060. if (!this._postProcesses[index].isSupported) {
  32061. return false;
  32062. }
  32063. }
  32064. return true;
  32065. },
  32066. enumerable: true,
  32067. configurable: true
  32068. });
  32069. PostProcessRenderEffect.prototype._update = function () {
  32070. for (var renderPassName in this._renderPasses) {
  32071. this._renderPasses[renderPassName]._update();
  32072. }
  32073. };
  32074. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  32075. this._renderPasses[renderPass._name] = renderPass;
  32076. this._linkParameters();
  32077. };
  32078. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  32079. delete this._renderPasses[renderPass._name];
  32080. this._linkParameters();
  32081. };
  32082. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  32083. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  32084. this._linkParameters();
  32085. };
  32086. PostProcessRenderEffect.prototype.getPass = function (passName) {
  32087. for (var renderPassName in this._renderPasses) {
  32088. if (renderPassName === passName) {
  32089. return this._renderPasses[passName];
  32090. }
  32091. }
  32092. };
  32093. PostProcessRenderEffect.prototype.emptyPasses = function () {
  32094. this._renderPasses = {};
  32095. this._linkParameters();
  32096. };
  32097. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  32098. var cameraKey;
  32099. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32100. for (var i = 0; i < _cam.length; i++) {
  32101. var camera = _cam[i];
  32102. var cameraName = camera.name;
  32103. if (this._singleInstance) {
  32104. cameraKey = 0;
  32105. }
  32106. else {
  32107. cameraKey = cameraName;
  32108. }
  32109. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  32110. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  32111. if (!this._indicesForCamera[cameraName]) {
  32112. this._indicesForCamera[cameraName] = [];
  32113. }
  32114. this._indicesForCamera[cameraName].push(index);
  32115. if (this._cameras.indexOf(camera) === -1) {
  32116. this._cameras[cameraName] = camera;
  32117. }
  32118. for (var passName in this._renderPasses) {
  32119. this._renderPasses[passName]._incRefCount();
  32120. }
  32121. }
  32122. this._linkParameters();
  32123. };
  32124. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  32125. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32126. for (var i = 0; i < _cam.length; i++) {
  32127. var camera = _cam[i];
  32128. var cameraName = camera.name;
  32129. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  32130. var index = this._cameras.indexOf(cameraName);
  32131. this._indicesForCamera.splice(index, 1);
  32132. this._cameras.splice(index, 1);
  32133. for (var passName in this._renderPasses) {
  32134. this._renderPasses[passName]._decRefCount();
  32135. }
  32136. }
  32137. };
  32138. PostProcessRenderEffect.prototype._enable = function (cameras) {
  32139. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32140. for (var i = 0; i < _cam.length; i++) {
  32141. var camera = _cam[i];
  32142. var cameraName = camera.name;
  32143. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  32144. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  32145. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  32146. }
  32147. }
  32148. for (var passName in this._renderPasses) {
  32149. this._renderPasses[passName]._incRefCount();
  32150. }
  32151. }
  32152. };
  32153. PostProcessRenderEffect.prototype._disable = function (cameras) {
  32154. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32155. for (var i = 0; i < _cam.length; i++) {
  32156. var camera = _cam[i];
  32157. var cameraName = camera.Name;
  32158. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  32159. for (var passName in this._renderPasses) {
  32160. this._renderPasses[passName]._decRefCount();
  32161. }
  32162. }
  32163. };
  32164. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  32165. if (this._singleInstance) {
  32166. return this._postProcesses[0];
  32167. }
  32168. else {
  32169. return this._postProcesses[camera.name];
  32170. }
  32171. };
  32172. PostProcessRenderEffect.prototype._linkParameters = function () {
  32173. var _this = this;
  32174. for (var index in this._postProcesses) {
  32175. if (this.applyParameters) {
  32176. this.applyParameters(this._postProcesses[index]);
  32177. }
  32178. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  32179. _this._linkTextures(effect);
  32180. });
  32181. }
  32182. };
  32183. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  32184. for (var renderPassName in this._renderPasses) {
  32185. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  32186. }
  32187. for (var renderEffectName in this._renderEffectAsPasses) {
  32188. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  32189. }
  32190. };
  32191. return PostProcessRenderEffect;
  32192. })();
  32193. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  32194. })(BABYLON || (BABYLON = {}));
  32195. var BABYLON;
  32196. (function (BABYLON) {
  32197. var PostProcessRenderPipeline = (function () {
  32198. function PostProcessRenderPipeline(engine, name) {
  32199. this._engine = engine;
  32200. this._name = name;
  32201. this._renderEffects = {};
  32202. this._renderEffectsForIsolatedPass = {};
  32203. this._cameras = [];
  32204. }
  32205. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  32206. get: function () {
  32207. for (var renderEffectName in this._renderEffects) {
  32208. if (!this._renderEffects[renderEffectName].isSupported) {
  32209. return false;
  32210. }
  32211. }
  32212. return true;
  32213. },
  32214. enumerable: true,
  32215. configurable: true
  32216. });
  32217. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  32218. this._renderEffects[renderEffect._name] = renderEffect;
  32219. };
  32220. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  32221. var renderEffects = this._renderEffects[renderEffectName];
  32222. if (!renderEffects) {
  32223. return;
  32224. }
  32225. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  32226. };
  32227. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  32228. var renderEffects = this._renderEffects[renderEffectName];
  32229. if (!renderEffects) {
  32230. return;
  32231. }
  32232. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  32233. };
  32234. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  32235. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32236. var indicesToDelete = [];
  32237. var i;
  32238. for (i = 0; i < _cam.length; i++) {
  32239. var camera = _cam[i];
  32240. var cameraName = camera.name;
  32241. if (this._cameras.indexOf(camera) === -1) {
  32242. this._cameras[cameraName] = camera;
  32243. }
  32244. else if (unique) {
  32245. indicesToDelete.push(i);
  32246. }
  32247. }
  32248. for (i = 0; i < indicesToDelete.length; i++) {
  32249. cameras.splice(indicesToDelete[i], 1);
  32250. }
  32251. for (var renderEffectName in this._renderEffects) {
  32252. this._renderEffects[renderEffectName]._attachCameras(_cam);
  32253. }
  32254. };
  32255. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  32256. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32257. for (var renderEffectName in this._renderEffects) {
  32258. this._renderEffects[renderEffectName]._detachCameras(_cam);
  32259. }
  32260. for (var i = 0; i < _cam.length; i++) {
  32261. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  32262. }
  32263. };
  32264. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  32265. var _this = this;
  32266. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32267. var pass = null;
  32268. var renderEffectName;
  32269. for (renderEffectName in this._renderEffects) {
  32270. pass = this._renderEffects[renderEffectName].getPass(passName);
  32271. if (pass != null) {
  32272. break;
  32273. }
  32274. }
  32275. if (pass === null) {
  32276. return;
  32277. }
  32278. for (renderEffectName in this._renderEffects) {
  32279. this._renderEffects[renderEffectName]._disable(_cam);
  32280. }
  32281. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  32282. for (var i = 0; i < _cam.length; i++) {
  32283. var camera = _cam[i];
  32284. var cameraName = camera.name;
  32285. 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); });
  32286. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  32287. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  32288. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  32289. }
  32290. };
  32291. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  32292. var _this = this;
  32293. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32294. for (var i = 0; i < _cam.length; i++) {
  32295. var camera = _cam[i];
  32296. var cameraName = camera.name;
  32297. 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); });
  32298. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  32299. }
  32300. for (var renderEffectName in this._renderEffects) {
  32301. this._renderEffects[renderEffectName]._enable(_cam);
  32302. }
  32303. };
  32304. PostProcessRenderPipeline.prototype._update = function () {
  32305. for (var renderEffectName in this._renderEffects) {
  32306. this._renderEffects[renderEffectName]._update();
  32307. }
  32308. for (var i = 0; i < this._cameras.length; i++) {
  32309. var cameraName = this._cameras[i].name;
  32310. if (this._renderEffectsForIsolatedPass[cameraName]) {
  32311. this._renderEffectsForIsolatedPass[cameraName]._update();
  32312. }
  32313. }
  32314. };
  32315. PostProcessRenderPipeline.prototype.dispose = function () {
  32316. // Must be implemented by children
  32317. };
  32318. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  32319. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  32320. return PostProcessRenderPipeline;
  32321. })();
  32322. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  32323. })(BABYLON || (BABYLON = {}));
  32324. var BABYLON;
  32325. (function (BABYLON) {
  32326. var PostProcessRenderPipelineManager = (function () {
  32327. function PostProcessRenderPipelineManager() {
  32328. this._renderPipelines = {};
  32329. }
  32330. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  32331. this._renderPipelines[renderPipeline._name] = renderPipeline;
  32332. };
  32333. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  32334. var renderPipeline = this._renderPipelines[renderPipelineName];
  32335. if (!renderPipeline) {
  32336. return;
  32337. }
  32338. renderPipeline._attachCameras(cameras, unique);
  32339. };
  32340. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  32341. var renderPipeline = this._renderPipelines[renderPipelineName];
  32342. if (!renderPipeline) {
  32343. return;
  32344. }
  32345. renderPipeline._detachCameras(cameras);
  32346. };
  32347. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  32348. var renderPipeline = this._renderPipelines[renderPipelineName];
  32349. if (!renderPipeline) {
  32350. return;
  32351. }
  32352. renderPipeline._enableEffect(renderEffectName, cameras);
  32353. };
  32354. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  32355. var renderPipeline = this._renderPipelines[renderPipelineName];
  32356. if (!renderPipeline) {
  32357. return;
  32358. }
  32359. renderPipeline._disableEffect(renderEffectName, cameras);
  32360. };
  32361. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  32362. var renderPipeline = this._renderPipelines[renderPipelineName];
  32363. if (!renderPipeline) {
  32364. return;
  32365. }
  32366. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  32367. };
  32368. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  32369. var renderPipeline = this._renderPipelines[renderPipelineName];
  32370. if (!renderPipeline) {
  32371. return;
  32372. }
  32373. renderPipeline._disableDisplayOnlyPass(cameras);
  32374. };
  32375. PostProcessRenderPipelineManager.prototype.update = function () {
  32376. for (var renderPipelineName in this._renderPipelines) {
  32377. var pipeline = this._renderPipelines[renderPipelineName];
  32378. if (!pipeline.isSupported) {
  32379. pipeline.dispose();
  32380. delete this._renderPipelines[renderPipelineName];
  32381. }
  32382. else {
  32383. pipeline._update();
  32384. }
  32385. }
  32386. };
  32387. return PostProcessRenderPipelineManager;
  32388. })();
  32389. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  32390. })(BABYLON || (BABYLON = {}));
  32391. var BABYLON;
  32392. (function (BABYLON) {
  32393. var BoundingBoxRenderer = (function () {
  32394. function BoundingBoxRenderer(scene) {
  32395. this.frontColor = new BABYLON.Color3(1, 1, 1);
  32396. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  32397. this.showBackLines = true;
  32398. this.renderList = new BABYLON.SmartArray(32);
  32399. this._vertexBuffers = {};
  32400. this._scene = scene;
  32401. }
  32402. BoundingBoxRenderer.prototype._prepareRessources = function () {
  32403. if (this._colorShader) {
  32404. return;
  32405. }
  32406. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  32407. attributes: [BABYLON.VertexBuffer.PositionKind],
  32408. uniforms: ["worldViewProjection", "color"]
  32409. });
  32410. var engine = this._scene.getEngine();
  32411. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  32412. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  32413. 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]);
  32414. };
  32415. BoundingBoxRenderer.prototype.reset = function () {
  32416. this.renderList.reset();
  32417. };
  32418. BoundingBoxRenderer.prototype.render = function () {
  32419. if (this.renderList.length === 0) {
  32420. return;
  32421. }
  32422. this._prepareRessources();
  32423. if (!this._colorShader.isReady()) {
  32424. return;
  32425. }
  32426. var engine = this._scene.getEngine();
  32427. engine.setDepthWrite(false);
  32428. this._colorShader._preBind();
  32429. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  32430. var boundingBox = this.renderList.data[boundingBoxIndex];
  32431. var min = boundingBox.minimum;
  32432. var max = boundingBox.maximum;
  32433. var diff = max.subtract(min);
  32434. var median = min.add(diff.scale(0.5));
  32435. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  32436. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  32437. .multiply(boundingBox.getWorldMatrix());
  32438. // VBOs
  32439. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  32440. if (this.showBackLines) {
  32441. // Back
  32442. engine.setDepthFunctionToGreaterOrEqual();
  32443. this._scene.resetCachedMaterial();
  32444. this._colorShader.setColor4("color", this.backColor.toColor4());
  32445. this._colorShader.bind(worldMatrix);
  32446. // Draw order
  32447. engine.draw(false, 0, 24);
  32448. }
  32449. // Front
  32450. engine.setDepthFunctionToLess();
  32451. this._scene.resetCachedMaterial();
  32452. this._colorShader.setColor4("color", this.frontColor.toColor4());
  32453. this._colorShader.bind(worldMatrix);
  32454. // Draw order
  32455. engine.draw(false, 0, 24);
  32456. }
  32457. this._colorShader.unbind();
  32458. engine.setDepthFunctionToLessOrEqual();
  32459. engine.setDepthWrite(true);
  32460. };
  32461. BoundingBoxRenderer.prototype.dispose = function () {
  32462. if (!this._colorShader) {
  32463. return;
  32464. }
  32465. this._colorShader.dispose();
  32466. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32467. if (buffer) {
  32468. buffer.dispose();
  32469. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32470. }
  32471. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32472. };
  32473. return BoundingBoxRenderer;
  32474. })();
  32475. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  32476. })(BABYLON || (BABYLON = {}));
  32477. var BABYLON;
  32478. (function (BABYLON) {
  32479. var Condition = (function () {
  32480. function Condition(actionManager) {
  32481. this._actionManager = actionManager;
  32482. }
  32483. Condition.prototype.isValid = function () {
  32484. return true;
  32485. };
  32486. Condition.prototype._getProperty = function (propertyPath) {
  32487. return this._actionManager._getProperty(propertyPath);
  32488. };
  32489. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  32490. return this._actionManager._getEffectiveTarget(target, propertyPath);
  32491. };
  32492. Condition.prototype.serialize = function () {
  32493. };
  32494. Condition.prototype._serialize = function (serializedCondition) {
  32495. return {
  32496. type: 2,
  32497. children: [],
  32498. name: serializedCondition.name,
  32499. properties: serializedCondition.properties
  32500. };
  32501. };
  32502. return Condition;
  32503. })();
  32504. BABYLON.Condition = Condition;
  32505. var ValueCondition = (function (_super) {
  32506. __extends(ValueCondition, _super);
  32507. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  32508. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  32509. _super.call(this, actionManager);
  32510. this.propertyPath = propertyPath;
  32511. this.value = value;
  32512. this.operator = operator;
  32513. this._target = target;
  32514. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  32515. this._property = this._getProperty(this.propertyPath);
  32516. }
  32517. Object.defineProperty(ValueCondition, "IsEqual", {
  32518. get: function () {
  32519. return ValueCondition._IsEqual;
  32520. },
  32521. enumerable: true,
  32522. configurable: true
  32523. });
  32524. Object.defineProperty(ValueCondition, "IsDifferent", {
  32525. get: function () {
  32526. return ValueCondition._IsDifferent;
  32527. },
  32528. enumerable: true,
  32529. configurable: true
  32530. });
  32531. Object.defineProperty(ValueCondition, "IsGreater", {
  32532. get: function () {
  32533. return ValueCondition._IsGreater;
  32534. },
  32535. enumerable: true,
  32536. configurable: true
  32537. });
  32538. Object.defineProperty(ValueCondition, "IsLesser", {
  32539. get: function () {
  32540. return ValueCondition._IsLesser;
  32541. },
  32542. enumerable: true,
  32543. configurable: true
  32544. });
  32545. // Methods
  32546. ValueCondition.prototype.isValid = function () {
  32547. switch (this.operator) {
  32548. case ValueCondition.IsGreater:
  32549. return this._effectiveTarget[this._property] > this.value;
  32550. case ValueCondition.IsLesser:
  32551. return this._effectiveTarget[this._property] < this.value;
  32552. case ValueCondition.IsEqual:
  32553. case ValueCondition.IsDifferent:
  32554. var check;
  32555. if (this.value.equals) {
  32556. check = this.value.equals(this._effectiveTarget[this._property]);
  32557. }
  32558. else {
  32559. check = this.value === this._effectiveTarget[this._property];
  32560. }
  32561. return this.operator === ValueCondition.IsEqual ? check : !check;
  32562. }
  32563. return false;
  32564. };
  32565. ValueCondition.prototype.serialize = function () {
  32566. return this._serialize({
  32567. name: "ValueCondition",
  32568. properties: [
  32569. BABYLON.Action._GetTargetProperty(this._target),
  32570. { name: "propertyPath", value: this.propertyPath },
  32571. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  32572. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  32573. ]
  32574. });
  32575. };
  32576. ValueCondition.GetOperatorName = function (operator) {
  32577. switch (operator) {
  32578. case ValueCondition._IsEqual: return "IsEqual";
  32579. case ValueCondition._IsDifferent: return "IsDifferent";
  32580. case ValueCondition._IsGreater: return "IsGreater";
  32581. case ValueCondition._IsLesser: return "IsLesser";
  32582. default: return "";
  32583. }
  32584. };
  32585. // Statics
  32586. ValueCondition._IsEqual = 0;
  32587. ValueCondition._IsDifferent = 1;
  32588. ValueCondition._IsGreater = 2;
  32589. ValueCondition._IsLesser = 3;
  32590. return ValueCondition;
  32591. })(Condition);
  32592. BABYLON.ValueCondition = ValueCondition;
  32593. var PredicateCondition = (function (_super) {
  32594. __extends(PredicateCondition, _super);
  32595. function PredicateCondition(actionManager, predicate) {
  32596. _super.call(this, actionManager);
  32597. this.predicate = predicate;
  32598. }
  32599. PredicateCondition.prototype.isValid = function () {
  32600. return this.predicate();
  32601. };
  32602. return PredicateCondition;
  32603. })(Condition);
  32604. BABYLON.PredicateCondition = PredicateCondition;
  32605. var StateCondition = (function (_super) {
  32606. __extends(StateCondition, _super);
  32607. function StateCondition(actionManager, target, value) {
  32608. _super.call(this, actionManager);
  32609. this.value = value;
  32610. this._target = target;
  32611. }
  32612. // Methods
  32613. StateCondition.prototype.isValid = function () {
  32614. return this._target.state === this.value;
  32615. };
  32616. StateCondition.prototype.serialize = function () {
  32617. return this._serialize({
  32618. name: "StateCondition",
  32619. properties: [
  32620. BABYLON.Action._GetTargetProperty(this._target),
  32621. { name: "value", value: this.value }
  32622. ]
  32623. });
  32624. };
  32625. return StateCondition;
  32626. })(Condition);
  32627. BABYLON.StateCondition = StateCondition;
  32628. })(BABYLON || (BABYLON = {}));
  32629. var BABYLON;
  32630. (function (BABYLON) {
  32631. var Action = (function () {
  32632. function Action(triggerOptions, condition) {
  32633. this.triggerOptions = triggerOptions;
  32634. if (triggerOptions.parameter) {
  32635. this.trigger = triggerOptions.trigger;
  32636. this._triggerParameter = triggerOptions.parameter;
  32637. }
  32638. else {
  32639. this.trigger = triggerOptions;
  32640. }
  32641. this._nextActiveAction = this;
  32642. this._condition = condition;
  32643. }
  32644. // Methods
  32645. Action.prototype._prepare = function () {
  32646. };
  32647. Action.prototype.getTriggerParameter = function () {
  32648. return this._triggerParameter;
  32649. };
  32650. Action.prototype._executeCurrent = function (evt) {
  32651. if (this._nextActiveAction._condition) {
  32652. var condition = this._nextActiveAction._condition;
  32653. var currentRenderId = this._actionManager.getScene().getRenderId();
  32654. // We cache the current evaluation for the current frame
  32655. if (condition._evaluationId === currentRenderId) {
  32656. if (!condition._currentResult) {
  32657. return;
  32658. }
  32659. }
  32660. else {
  32661. condition._evaluationId = currentRenderId;
  32662. if (!condition.isValid()) {
  32663. condition._currentResult = false;
  32664. return;
  32665. }
  32666. condition._currentResult = true;
  32667. }
  32668. }
  32669. this._nextActiveAction.execute(evt);
  32670. this.skipToNextActiveAction();
  32671. };
  32672. Action.prototype.execute = function (evt) {
  32673. };
  32674. Action.prototype.skipToNextActiveAction = function () {
  32675. if (this._nextActiveAction._child) {
  32676. if (!this._nextActiveAction._child._actionManager) {
  32677. this._nextActiveAction._child._actionManager = this._actionManager;
  32678. }
  32679. this._nextActiveAction = this._nextActiveAction._child;
  32680. }
  32681. else {
  32682. this._nextActiveAction = this;
  32683. }
  32684. };
  32685. Action.prototype.then = function (action) {
  32686. this._child = action;
  32687. action._actionManager = this._actionManager;
  32688. action._prepare();
  32689. return action;
  32690. };
  32691. Action.prototype._getProperty = function (propertyPath) {
  32692. return this._actionManager._getProperty(propertyPath);
  32693. };
  32694. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  32695. return this._actionManager._getEffectiveTarget(target, propertyPath);
  32696. };
  32697. Action.prototype.serialize = function (parent) {
  32698. };
  32699. // Called by BABYLON.Action objects in serialize(...). Internal use
  32700. Action.prototype._serialize = function (serializedAction, parent) {
  32701. var serializationObject = {
  32702. type: 1,
  32703. children: [],
  32704. name: serializedAction.name,
  32705. properties: serializedAction.properties || []
  32706. };
  32707. // Serialize child
  32708. if (this._child) {
  32709. this._child.serialize(serializationObject);
  32710. }
  32711. // Check if "this" has a condition
  32712. if (this._condition) {
  32713. var serializedCondition = this._condition.serialize();
  32714. serializedCondition.children.push(serializationObject);
  32715. if (parent) {
  32716. parent.children.push(serializedCondition);
  32717. }
  32718. return serializedCondition;
  32719. }
  32720. if (parent) {
  32721. parent.children.push(serializationObject);
  32722. }
  32723. return serializationObject;
  32724. };
  32725. Action._SerializeValueAsString = function (value) {
  32726. if (typeof value === "number") {
  32727. return value.toString();
  32728. }
  32729. if (typeof value === "boolean") {
  32730. return value ? "true" : "false";
  32731. }
  32732. if (value instanceof BABYLON.Vector2) {
  32733. return value.x + ", " + value.y;
  32734. }
  32735. if (value instanceof BABYLON.Vector3) {
  32736. return value.x + ", " + value.y + ", " + value.z;
  32737. }
  32738. if (value instanceof BABYLON.Color3) {
  32739. return value.r + ", " + value.g + ", " + value.b;
  32740. }
  32741. if (value instanceof BABYLON.Color4) {
  32742. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  32743. }
  32744. return value; // string
  32745. };
  32746. Action._GetTargetProperty = function (target) {
  32747. return {
  32748. name: "target",
  32749. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  32750. : target instanceof BABYLON.Light ? "LightProperties"
  32751. : target instanceof BABYLON.Camera ? "CameraProperties"
  32752. : "SceneProperties",
  32753. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  32754. };
  32755. };
  32756. return Action;
  32757. })();
  32758. BABYLON.Action = Action;
  32759. })(BABYLON || (BABYLON = {}));
  32760. var BABYLON;
  32761. (function (BABYLON) {
  32762. /**
  32763. * ActionEvent is the event beint sent when an action is triggered.
  32764. */
  32765. var ActionEvent = (function () {
  32766. /**
  32767. * @constructor
  32768. * @param source The mesh or sprite that triggered the action.
  32769. * @param pointerX The X mouse cursor position at the time of the event
  32770. * @param pointerY The Y mouse cursor position at the time of the event
  32771. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  32772. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  32773. */
  32774. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  32775. this.source = source;
  32776. this.pointerX = pointerX;
  32777. this.pointerY = pointerY;
  32778. this.meshUnderPointer = meshUnderPointer;
  32779. this.sourceEvent = sourceEvent;
  32780. this.additionalData = additionalData;
  32781. }
  32782. /**
  32783. * Helper function to auto-create an ActionEvent from a source mesh.
  32784. * @param source The source mesh that triggered the event
  32785. * @param evt {Event} The original (browser) event
  32786. */
  32787. ActionEvent.CreateNew = function (source, evt, additionalData) {
  32788. var scene = source.getScene();
  32789. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  32790. };
  32791. /**
  32792. * Helper function to auto-create an ActionEvent from a source mesh.
  32793. * @param source The source sprite that triggered the event
  32794. * @param scene Scene associated with the sprite
  32795. * @param evt {Event} The original (browser) event
  32796. */
  32797. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  32798. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  32799. };
  32800. /**
  32801. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  32802. * @param scene the scene where the event occurred
  32803. * @param evt {Event} The original (browser) event
  32804. */
  32805. ActionEvent.CreateNewFromScene = function (scene, evt) {
  32806. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  32807. };
  32808. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  32809. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  32810. };
  32811. return ActionEvent;
  32812. })();
  32813. BABYLON.ActionEvent = ActionEvent;
  32814. /**
  32815. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  32816. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  32817. */
  32818. var ActionManager = (function () {
  32819. function ActionManager(scene) {
  32820. // Members
  32821. this.actions = new Array();
  32822. this._scene = scene;
  32823. scene._actionManagers.push(this);
  32824. }
  32825. Object.defineProperty(ActionManager, "NothingTrigger", {
  32826. get: function () {
  32827. return ActionManager._NothingTrigger;
  32828. },
  32829. enumerable: true,
  32830. configurable: true
  32831. });
  32832. Object.defineProperty(ActionManager, "OnPickTrigger", {
  32833. get: function () {
  32834. return ActionManager._OnPickTrigger;
  32835. },
  32836. enumerable: true,
  32837. configurable: true
  32838. });
  32839. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  32840. get: function () {
  32841. return ActionManager._OnLeftPickTrigger;
  32842. },
  32843. enumerable: true,
  32844. configurable: true
  32845. });
  32846. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  32847. get: function () {
  32848. return ActionManager._OnRightPickTrigger;
  32849. },
  32850. enumerable: true,
  32851. configurable: true
  32852. });
  32853. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  32854. get: function () {
  32855. return ActionManager._OnCenterPickTrigger;
  32856. },
  32857. enumerable: true,
  32858. configurable: true
  32859. });
  32860. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  32861. get: function () {
  32862. return ActionManager._OnPickDownTrigger;
  32863. },
  32864. enumerable: true,
  32865. configurable: true
  32866. });
  32867. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  32868. get: function () {
  32869. return ActionManager._OnPickUpTrigger;
  32870. },
  32871. enumerable: true,
  32872. configurable: true
  32873. });
  32874. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  32875. /// This trigger will only be raised if you also declared a OnPickDown
  32876. get: function () {
  32877. return ActionManager._OnPickOutTrigger;
  32878. },
  32879. enumerable: true,
  32880. configurable: true
  32881. });
  32882. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  32883. get: function () {
  32884. return ActionManager._OnLongPressTrigger;
  32885. },
  32886. enumerable: true,
  32887. configurable: true
  32888. });
  32889. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  32890. get: function () {
  32891. return ActionManager._OnPointerOverTrigger;
  32892. },
  32893. enumerable: true,
  32894. configurable: true
  32895. });
  32896. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  32897. get: function () {
  32898. return ActionManager._OnPointerOutTrigger;
  32899. },
  32900. enumerable: true,
  32901. configurable: true
  32902. });
  32903. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  32904. get: function () {
  32905. return ActionManager._OnEveryFrameTrigger;
  32906. },
  32907. enumerable: true,
  32908. configurable: true
  32909. });
  32910. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  32911. get: function () {
  32912. return ActionManager._OnIntersectionEnterTrigger;
  32913. },
  32914. enumerable: true,
  32915. configurable: true
  32916. });
  32917. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  32918. get: function () {
  32919. return ActionManager._OnIntersectionExitTrigger;
  32920. },
  32921. enumerable: true,
  32922. configurable: true
  32923. });
  32924. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  32925. get: function () {
  32926. return ActionManager._OnKeyDownTrigger;
  32927. },
  32928. enumerable: true,
  32929. configurable: true
  32930. });
  32931. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  32932. get: function () {
  32933. return ActionManager._OnKeyUpTrigger;
  32934. },
  32935. enumerable: true,
  32936. configurable: true
  32937. });
  32938. // Methods
  32939. ActionManager.prototype.dispose = function () {
  32940. var index = this._scene._actionManagers.indexOf(this);
  32941. if (index > -1) {
  32942. this._scene._actionManagers.splice(index, 1);
  32943. }
  32944. };
  32945. ActionManager.prototype.getScene = function () {
  32946. return this._scene;
  32947. };
  32948. /**
  32949. * Does this action manager handles actions of any of the given triggers
  32950. * @param {number[]} triggers - the triggers to be tested
  32951. * @return {boolean} whether one (or more) of the triggers is handeled
  32952. */
  32953. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  32954. for (var index = 0; index < this.actions.length; index++) {
  32955. var action = this.actions[index];
  32956. if (triggers.indexOf(action.trigger) > -1) {
  32957. return true;
  32958. }
  32959. }
  32960. return false;
  32961. };
  32962. /**
  32963. * Does this action manager handles actions of a given trigger
  32964. * @param {number} trigger - the trigger to be tested
  32965. * @return {boolean} whether the trigger is handeled
  32966. */
  32967. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  32968. for (var index = 0; index < this.actions.length; index++) {
  32969. var action = this.actions[index];
  32970. if (action.trigger === trigger) {
  32971. return true;
  32972. }
  32973. }
  32974. return false;
  32975. };
  32976. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  32977. /**
  32978. * Does this action manager has pointer triggers
  32979. * @return {boolean} whether or not it has pointer triggers
  32980. */
  32981. get: function () {
  32982. for (var index = 0; index < this.actions.length; index++) {
  32983. var action = this.actions[index];
  32984. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  32985. return true;
  32986. }
  32987. }
  32988. return false;
  32989. },
  32990. enumerable: true,
  32991. configurable: true
  32992. });
  32993. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  32994. /**
  32995. * Does this action manager has pick triggers
  32996. * @return {boolean} whether or not it has pick triggers
  32997. */
  32998. get: function () {
  32999. for (var index = 0; index < this.actions.length; index++) {
  33000. var action = this.actions[index];
  33001. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  33002. return true;
  33003. }
  33004. }
  33005. return false;
  33006. },
  33007. enumerable: true,
  33008. configurable: true
  33009. });
  33010. /**
  33011. * Registers an action to this action manager
  33012. * @param {BABYLON.Action} action - the action to be registered
  33013. * @return {BABYLON.Action} the action amended (prepared) after registration
  33014. */
  33015. ActionManager.prototype.registerAction = function (action) {
  33016. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  33017. if (this.getScene().actionManager !== this) {
  33018. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  33019. return null;
  33020. }
  33021. }
  33022. this.actions.push(action);
  33023. action._actionManager = this;
  33024. action._prepare();
  33025. return action;
  33026. };
  33027. /**
  33028. * Process a specific trigger
  33029. * @param {number} trigger - the trigger to process
  33030. * @param evt {BABYLON.ActionEvent} the event details to be processed
  33031. */
  33032. ActionManager.prototype.processTrigger = function (trigger, evt) {
  33033. for (var index = 0; index < this.actions.length; index++) {
  33034. var action = this.actions[index];
  33035. if (action.trigger === trigger) {
  33036. if (trigger === ActionManager.OnKeyUpTrigger
  33037. || trigger === ActionManager.OnKeyDownTrigger) {
  33038. var parameter = action.getTriggerParameter();
  33039. if (parameter) {
  33040. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  33041. var actualkey = String.fromCharCode(unicode).toLowerCase();
  33042. if (actualkey !== parameter.toLowerCase()) {
  33043. continue;
  33044. }
  33045. }
  33046. }
  33047. action._executeCurrent(evt);
  33048. }
  33049. }
  33050. };
  33051. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  33052. var properties = propertyPath.split(".");
  33053. for (var index = 0; index < properties.length - 1; index++) {
  33054. target = target[properties[index]];
  33055. }
  33056. return target;
  33057. };
  33058. ActionManager.prototype._getProperty = function (propertyPath) {
  33059. var properties = propertyPath.split(".");
  33060. return properties[properties.length - 1];
  33061. };
  33062. ActionManager.prototype.serialize = function (name) {
  33063. var root = {
  33064. children: [],
  33065. name: name,
  33066. type: 3,
  33067. properties: [] // Empty for root but required
  33068. };
  33069. for (var i = 0; i < this.actions.length; i++) {
  33070. var triggerObject = {
  33071. type: 0,
  33072. children: [],
  33073. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  33074. properties: []
  33075. };
  33076. var triggerOptions = this.actions[i].triggerOptions;
  33077. if (triggerOptions && typeof triggerOptions !== "number") {
  33078. if (triggerOptions.parameter instanceof BABYLON.Node) {
  33079. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  33080. }
  33081. else {
  33082. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  33083. }
  33084. }
  33085. // Serialize child action, recursively
  33086. this.actions[i].serialize(triggerObject);
  33087. // Add serialized trigger
  33088. root.children.push(triggerObject);
  33089. }
  33090. return root;
  33091. };
  33092. ActionManager.Parse = function (parsedActions, object, scene) {
  33093. var actionManager = new BABYLON.ActionManager(scene);
  33094. if (object === null)
  33095. scene.actionManager = actionManager;
  33096. else
  33097. object.actionManager = actionManager;
  33098. // instanciate a new object
  33099. var instanciate = function (name, params) {
  33100. var newInstance = Object.create(BABYLON[name].prototype);
  33101. newInstance.constructor.apply(newInstance, params);
  33102. return newInstance;
  33103. };
  33104. var parseParameter = function (name, value, target, propertyPath) {
  33105. if (propertyPath === null) {
  33106. // String, boolean or float
  33107. var floatValue = parseFloat(value);
  33108. if (value === "true" || value === "false")
  33109. return value === "true";
  33110. else
  33111. return isNaN(floatValue) ? value : floatValue;
  33112. }
  33113. var effectiveTarget = propertyPath.split(".");
  33114. var values = value.split(",");
  33115. // Get effective Target
  33116. for (var i = 0; i < effectiveTarget.length; i++) {
  33117. target = target[effectiveTarget[i]];
  33118. }
  33119. // Return appropriate value with its type
  33120. if (typeof (target) === "boolean")
  33121. return values[0] === "true";
  33122. if (typeof (target) === "string")
  33123. return values[0];
  33124. // Parameters with multiple values such as Vector3 etc.
  33125. var split = new Array();
  33126. for (var i = 0; i < values.length; i++)
  33127. split.push(parseFloat(values[i]));
  33128. if (target instanceof BABYLON.Vector3)
  33129. return BABYLON.Vector3.FromArray(split);
  33130. if (target instanceof BABYLON.Vector4)
  33131. return BABYLON.Vector4.FromArray(split);
  33132. if (target instanceof BABYLON.Color3)
  33133. return BABYLON.Color3.FromArray(split);
  33134. if (target instanceof BABYLON.Color4)
  33135. return BABYLON.Color4.FromArray(split);
  33136. return parseFloat(values[0]);
  33137. };
  33138. // traverse graph per trigger
  33139. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  33140. if (combineArray === void 0) { combineArray = null; }
  33141. if (parsedAction.detached)
  33142. return;
  33143. var parameters = new Array();
  33144. var target = null;
  33145. var propertyPath = null;
  33146. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  33147. // Parameters
  33148. if (parsedAction.type === 2)
  33149. parameters.push(actionManager);
  33150. else
  33151. parameters.push(trigger);
  33152. if (combine) {
  33153. var actions = new Array();
  33154. for (var j = 0; j < parsedAction.combine.length; j++) {
  33155. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  33156. }
  33157. parameters.push(actions);
  33158. }
  33159. else {
  33160. for (var i = 0; i < parsedAction.properties.length; i++) {
  33161. var value = parsedAction.properties[i].value;
  33162. var name = parsedAction.properties[i].name;
  33163. var targetType = parsedAction.properties[i].targetType;
  33164. if (name === "target")
  33165. if (targetType !== null && targetType === "SceneProperties")
  33166. value = target = scene;
  33167. else
  33168. value = target = scene.getNodeByName(value);
  33169. else if (name === "parent")
  33170. value = scene.getNodeByName(value);
  33171. else if (name === "sound")
  33172. value = scene.getSoundByName(value);
  33173. else if (name !== "propertyPath") {
  33174. if (parsedAction.type === 2 && name === "operator")
  33175. value = BABYLON.ValueCondition[value];
  33176. else
  33177. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  33178. }
  33179. else {
  33180. propertyPath = value;
  33181. }
  33182. parameters.push(value);
  33183. }
  33184. }
  33185. if (combineArray === null) {
  33186. parameters.push(condition);
  33187. }
  33188. else {
  33189. parameters.push(null);
  33190. }
  33191. // If interpolate value action
  33192. if (parsedAction.name === "InterpolateValueAction") {
  33193. var param = parameters[parameters.length - 2];
  33194. parameters[parameters.length - 1] = param;
  33195. parameters[parameters.length - 2] = condition;
  33196. }
  33197. // Action or condition(s) and not CombineAction
  33198. var newAction = instanciate(parsedAction.name, parameters);
  33199. if (newAction instanceof BABYLON.Condition && condition !== null) {
  33200. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  33201. if (action)
  33202. action.then(nothing);
  33203. else
  33204. actionManager.registerAction(nothing);
  33205. action = nothing;
  33206. }
  33207. if (combineArray === null) {
  33208. if (newAction instanceof BABYLON.Condition) {
  33209. condition = newAction;
  33210. newAction = action;
  33211. }
  33212. else {
  33213. condition = null;
  33214. if (action)
  33215. action.then(newAction);
  33216. else
  33217. actionManager.registerAction(newAction);
  33218. }
  33219. }
  33220. else {
  33221. combineArray.push(newAction);
  33222. }
  33223. for (var i = 0; i < parsedAction.children.length; i++)
  33224. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  33225. };
  33226. // triggers
  33227. for (var i = 0; i < parsedActions.children.length; i++) {
  33228. var triggerParams;
  33229. var trigger = parsedActions.children[i];
  33230. if (trigger.properties.length > 0) {
  33231. var param = trigger.properties[0].value;
  33232. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  33233. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  33234. }
  33235. else
  33236. triggerParams = BABYLON.ActionManager[trigger.name];
  33237. for (var j = 0; j < trigger.children.length; j++) {
  33238. if (!trigger.detached)
  33239. traverse(trigger.children[j], triggerParams, null, null);
  33240. }
  33241. }
  33242. };
  33243. ActionManager.GetTriggerName = function (trigger) {
  33244. switch (trigger) {
  33245. case 0: return "NothingTrigger";
  33246. case 1: return "OnPickTrigger";
  33247. case 2: return "OnLeftPickTrigger";
  33248. case 3: return "OnRightPickTrigger";
  33249. case 4: return "OnCenterPickTrigger";
  33250. case 5: return "OnPickDownTrigger";
  33251. case 6: return "OnPickUpTrigger";
  33252. case 7: return "OnLongPressTrigger";
  33253. case 8: return "OnPointerOverTrigger";
  33254. case 9: return "OnPointerOutTrigger";
  33255. case 10: return "OnEveryFrameTrigger";
  33256. case 11: return "OnIntersectionEnterTrigger";
  33257. case 12: return "OnIntersectionExitTrigger";
  33258. case 13: return "OnKeyDownTrigger";
  33259. case 14: return "OnKeyUpTrigger";
  33260. case 15: return "OnPickOutTrigger";
  33261. default: return "";
  33262. }
  33263. };
  33264. // Statics
  33265. ActionManager._NothingTrigger = 0;
  33266. ActionManager._OnPickTrigger = 1;
  33267. ActionManager._OnLeftPickTrigger = 2;
  33268. ActionManager._OnRightPickTrigger = 3;
  33269. ActionManager._OnCenterPickTrigger = 4;
  33270. ActionManager._OnPickDownTrigger = 5;
  33271. ActionManager._OnPickUpTrigger = 6;
  33272. ActionManager._OnLongPressTrigger = 7;
  33273. ActionManager._OnPointerOverTrigger = 8;
  33274. ActionManager._OnPointerOutTrigger = 9;
  33275. ActionManager._OnEveryFrameTrigger = 10;
  33276. ActionManager._OnIntersectionEnterTrigger = 11;
  33277. ActionManager._OnIntersectionExitTrigger = 12;
  33278. ActionManager._OnKeyDownTrigger = 13;
  33279. ActionManager._OnKeyUpTrigger = 14;
  33280. ActionManager._OnPickOutTrigger = 15;
  33281. ActionManager.DragMovementThreshold = 10; // in pixels
  33282. ActionManager.LongPressDelay = 500; // in milliseconds
  33283. return ActionManager;
  33284. })();
  33285. BABYLON.ActionManager = ActionManager;
  33286. })(BABYLON || (BABYLON = {}));
  33287. var BABYLON;
  33288. (function (BABYLON) {
  33289. var InterpolateValueAction = (function (_super) {
  33290. __extends(InterpolateValueAction, _super);
  33291. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  33292. if (duration === void 0) { duration = 1000; }
  33293. _super.call(this, triggerOptions, condition);
  33294. this.propertyPath = propertyPath;
  33295. this.value = value;
  33296. this.duration = duration;
  33297. this.stopOtherAnimations = stopOtherAnimations;
  33298. this.onInterpolationDone = onInterpolationDone;
  33299. this._target = this._effectiveTarget = target;
  33300. }
  33301. InterpolateValueAction.prototype._prepare = function () {
  33302. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33303. this._property = this._getProperty(this.propertyPath);
  33304. };
  33305. InterpolateValueAction.prototype.execute = function () {
  33306. var scene = this._actionManager.getScene();
  33307. var keys = [
  33308. {
  33309. frame: 0,
  33310. value: this._effectiveTarget[this._property]
  33311. }, {
  33312. frame: 100,
  33313. value: this.value
  33314. }
  33315. ];
  33316. var dataType;
  33317. if (typeof this.value === "number") {
  33318. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  33319. }
  33320. else if (this.value instanceof BABYLON.Color3) {
  33321. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  33322. }
  33323. else if (this.value instanceof BABYLON.Vector3) {
  33324. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  33325. }
  33326. else if (this.value instanceof BABYLON.Matrix) {
  33327. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  33328. }
  33329. else if (this.value instanceof BABYLON.Quaternion) {
  33330. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  33331. }
  33332. else {
  33333. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  33334. return;
  33335. }
  33336. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  33337. animation.setKeys(keys);
  33338. if (this.stopOtherAnimations) {
  33339. scene.stopAnimation(this._effectiveTarget);
  33340. }
  33341. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  33342. };
  33343. InterpolateValueAction.prototype.serialize = function (parent) {
  33344. return _super.prototype._serialize.call(this, {
  33345. name: "InterpolateValueAction",
  33346. properties: [
  33347. BABYLON.Action._GetTargetProperty(this._target),
  33348. { name: "propertyPath", value: this.propertyPath },
  33349. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  33350. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  33351. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  33352. ]
  33353. }, parent);
  33354. };
  33355. return InterpolateValueAction;
  33356. })(BABYLON.Action);
  33357. BABYLON.InterpolateValueAction = InterpolateValueAction;
  33358. })(BABYLON || (BABYLON = {}));
  33359. var BABYLON;
  33360. (function (BABYLON) {
  33361. var SwitchBooleanAction = (function (_super) {
  33362. __extends(SwitchBooleanAction, _super);
  33363. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  33364. _super.call(this, triggerOptions, condition);
  33365. this.propertyPath = propertyPath;
  33366. this._target = this._effectiveTarget = target;
  33367. }
  33368. SwitchBooleanAction.prototype._prepare = function () {
  33369. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33370. this._property = this._getProperty(this.propertyPath);
  33371. };
  33372. SwitchBooleanAction.prototype.execute = function () {
  33373. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  33374. };
  33375. SwitchBooleanAction.prototype.serialize = function (parent) {
  33376. return _super.prototype._serialize.call(this, {
  33377. name: "SwitchBooleanAction",
  33378. properties: [
  33379. BABYLON.Action._GetTargetProperty(this._target),
  33380. { name: "propertyPath", value: this.propertyPath }
  33381. ]
  33382. }, parent);
  33383. };
  33384. return SwitchBooleanAction;
  33385. })(BABYLON.Action);
  33386. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  33387. var SetStateAction = (function (_super) {
  33388. __extends(SetStateAction, _super);
  33389. function SetStateAction(triggerOptions, target, value, condition) {
  33390. _super.call(this, triggerOptions, condition);
  33391. this.value = value;
  33392. this._target = target;
  33393. }
  33394. SetStateAction.prototype.execute = function () {
  33395. this._target.state = this.value;
  33396. };
  33397. SetStateAction.prototype.serialize = function (parent) {
  33398. return _super.prototype._serialize.call(this, {
  33399. name: "SetStateAction",
  33400. properties: [
  33401. BABYLON.Action._GetTargetProperty(this._target),
  33402. { name: "value", value: this.value }
  33403. ]
  33404. }, parent);
  33405. };
  33406. return SetStateAction;
  33407. })(BABYLON.Action);
  33408. BABYLON.SetStateAction = SetStateAction;
  33409. var SetValueAction = (function (_super) {
  33410. __extends(SetValueAction, _super);
  33411. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  33412. _super.call(this, triggerOptions, condition);
  33413. this.propertyPath = propertyPath;
  33414. this.value = value;
  33415. this._target = this._effectiveTarget = target;
  33416. }
  33417. SetValueAction.prototype._prepare = function () {
  33418. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33419. this._property = this._getProperty(this.propertyPath);
  33420. };
  33421. SetValueAction.prototype.execute = function () {
  33422. this._effectiveTarget[this._property] = this.value;
  33423. if (this._target.markAsDirty) {
  33424. this._target.markAsDirty(this._property);
  33425. }
  33426. };
  33427. SetValueAction.prototype.serialize = function (parent) {
  33428. return _super.prototype._serialize.call(this, {
  33429. name: "SetValueAction",
  33430. properties: [
  33431. BABYLON.Action._GetTargetProperty(this._target),
  33432. { name: "propertyPath", value: this.propertyPath },
  33433. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  33434. ]
  33435. }, parent);
  33436. };
  33437. return SetValueAction;
  33438. })(BABYLON.Action);
  33439. BABYLON.SetValueAction = SetValueAction;
  33440. var IncrementValueAction = (function (_super) {
  33441. __extends(IncrementValueAction, _super);
  33442. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  33443. _super.call(this, triggerOptions, condition);
  33444. this.propertyPath = propertyPath;
  33445. this.value = value;
  33446. this._target = this._effectiveTarget = target;
  33447. }
  33448. IncrementValueAction.prototype._prepare = function () {
  33449. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33450. this._property = this._getProperty(this.propertyPath);
  33451. if (typeof this._effectiveTarget[this._property] !== "number") {
  33452. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  33453. }
  33454. };
  33455. IncrementValueAction.prototype.execute = function () {
  33456. this._effectiveTarget[this._property] += this.value;
  33457. if (this._target.markAsDirty) {
  33458. this._target.markAsDirty(this._property);
  33459. }
  33460. };
  33461. IncrementValueAction.prototype.serialize = function (parent) {
  33462. return _super.prototype._serialize.call(this, {
  33463. name: "IncrementValueAction",
  33464. properties: [
  33465. BABYLON.Action._GetTargetProperty(this._target),
  33466. { name: "propertyPath", value: this.propertyPath },
  33467. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  33468. ]
  33469. }, parent);
  33470. };
  33471. return IncrementValueAction;
  33472. })(BABYLON.Action);
  33473. BABYLON.IncrementValueAction = IncrementValueAction;
  33474. var PlayAnimationAction = (function (_super) {
  33475. __extends(PlayAnimationAction, _super);
  33476. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  33477. _super.call(this, triggerOptions, condition);
  33478. this.from = from;
  33479. this.to = to;
  33480. this.loop = loop;
  33481. this._target = target;
  33482. }
  33483. PlayAnimationAction.prototype._prepare = function () {
  33484. };
  33485. PlayAnimationAction.prototype.execute = function () {
  33486. var scene = this._actionManager.getScene();
  33487. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  33488. };
  33489. PlayAnimationAction.prototype.serialize = function (parent) {
  33490. return _super.prototype._serialize.call(this, {
  33491. name: "PlayAnimationAction",
  33492. properties: [
  33493. BABYLON.Action._GetTargetProperty(this._target),
  33494. { name: "from", value: String(this.from) },
  33495. { name: "to", value: String(this.to) },
  33496. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  33497. ]
  33498. }, parent);
  33499. };
  33500. return PlayAnimationAction;
  33501. })(BABYLON.Action);
  33502. BABYLON.PlayAnimationAction = PlayAnimationAction;
  33503. var StopAnimationAction = (function (_super) {
  33504. __extends(StopAnimationAction, _super);
  33505. function StopAnimationAction(triggerOptions, target, condition) {
  33506. _super.call(this, triggerOptions, condition);
  33507. this._target = target;
  33508. }
  33509. StopAnimationAction.prototype._prepare = function () {
  33510. };
  33511. StopAnimationAction.prototype.execute = function () {
  33512. var scene = this._actionManager.getScene();
  33513. scene.stopAnimation(this._target);
  33514. };
  33515. StopAnimationAction.prototype.serialize = function (parent) {
  33516. return _super.prototype._serialize.call(this, {
  33517. name: "StopAnimationAction",
  33518. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  33519. }, parent);
  33520. };
  33521. return StopAnimationAction;
  33522. })(BABYLON.Action);
  33523. BABYLON.StopAnimationAction = StopAnimationAction;
  33524. var DoNothingAction = (function (_super) {
  33525. __extends(DoNothingAction, _super);
  33526. function DoNothingAction(triggerOptions, condition) {
  33527. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  33528. _super.call(this, triggerOptions, condition);
  33529. }
  33530. DoNothingAction.prototype.execute = function () {
  33531. };
  33532. DoNothingAction.prototype.serialize = function (parent) {
  33533. return _super.prototype._serialize.call(this, {
  33534. name: "DoNothingAction",
  33535. properties: []
  33536. }, parent);
  33537. };
  33538. return DoNothingAction;
  33539. })(BABYLON.Action);
  33540. BABYLON.DoNothingAction = DoNothingAction;
  33541. var CombineAction = (function (_super) {
  33542. __extends(CombineAction, _super);
  33543. function CombineAction(triggerOptions, children, condition) {
  33544. _super.call(this, triggerOptions, condition);
  33545. this.children = children;
  33546. }
  33547. CombineAction.prototype._prepare = function () {
  33548. for (var index = 0; index < this.children.length; index++) {
  33549. this.children[index]._actionManager = this._actionManager;
  33550. this.children[index]._prepare();
  33551. }
  33552. };
  33553. CombineAction.prototype.execute = function (evt) {
  33554. for (var index = 0; index < this.children.length; index++) {
  33555. this.children[index].execute(evt);
  33556. }
  33557. };
  33558. CombineAction.prototype.serialize = function (parent) {
  33559. var serializationObject = _super.prototype._serialize.call(this, {
  33560. name: "CombineAction",
  33561. properties: [],
  33562. combine: []
  33563. }, parent);
  33564. for (var i = 0; i < this.children.length; i++) {
  33565. serializationObject.combine.push(this.children[i].serialize(null));
  33566. }
  33567. return serializationObject;
  33568. };
  33569. return CombineAction;
  33570. })(BABYLON.Action);
  33571. BABYLON.CombineAction = CombineAction;
  33572. var ExecuteCodeAction = (function (_super) {
  33573. __extends(ExecuteCodeAction, _super);
  33574. function ExecuteCodeAction(triggerOptions, func, condition) {
  33575. _super.call(this, triggerOptions, condition);
  33576. this.func = func;
  33577. }
  33578. ExecuteCodeAction.prototype.execute = function (evt) {
  33579. this.func(evt);
  33580. };
  33581. return ExecuteCodeAction;
  33582. })(BABYLON.Action);
  33583. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  33584. var SetParentAction = (function (_super) {
  33585. __extends(SetParentAction, _super);
  33586. function SetParentAction(triggerOptions, target, parent, condition) {
  33587. _super.call(this, triggerOptions, condition);
  33588. this._target = target;
  33589. this._parent = parent;
  33590. }
  33591. SetParentAction.prototype._prepare = function () {
  33592. };
  33593. SetParentAction.prototype.execute = function () {
  33594. if (this._target.parent === this._parent) {
  33595. return;
  33596. }
  33597. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  33598. invertParentWorldMatrix.invert();
  33599. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  33600. this._target.parent = this._parent;
  33601. };
  33602. SetParentAction.prototype.serialize = function (parent) {
  33603. return _super.prototype._serialize.call(this, {
  33604. name: "SetParentAction",
  33605. properties: [
  33606. BABYLON.Action._GetTargetProperty(this._target),
  33607. BABYLON.Action._GetTargetProperty(this._parent),
  33608. ]
  33609. }, parent);
  33610. };
  33611. return SetParentAction;
  33612. })(BABYLON.Action);
  33613. BABYLON.SetParentAction = SetParentAction;
  33614. var PlaySoundAction = (function (_super) {
  33615. __extends(PlaySoundAction, _super);
  33616. function PlaySoundAction(triggerOptions, sound, condition) {
  33617. _super.call(this, triggerOptions, condition);
  33618. this._sound = sound;
  33619. }
  33620. PlaySoundAction.prototype._prepare = function () {
  33621. };
  33622. PlaySoundAction.prototype.execute = function () {
  33623. if (this._sound !== undefined)
  33624. this._sound.play();
  33625. };
  33626. PlaySoundAction.prototype.serialize = function (parent) {
  33627. return _super.prototype._serialize.call(this, {
  33628. name: "PlaySoundAction",
  33629. properties: [{ name: "sound", value: this._sound.name }]
  33630. }, parent);
  33631. };
  33632. return PlaySoundAction;
  33633. })(BABYLON.Action);
  33634. BABYLON.PlaySoundAction = PlaySoundAction;
  33635. var StopSoundAction = (function (_super) {
  33636. __extends(StopSoundAction, _super);
  33637. function StopSoundAction(triggerOptions, sound, condition) {
  33638. _super.call(this, triggerOptions, condition);
  33639. this._sound = sound;
  33640. }
  33641. StopSoundAction.prototype._prepare = function () {
  33642. };
  33643. StopSoundAction.prototype.execute = function () {
  33644. if (this._sound !== undefined)
  33645. this._sound.stop();
  33646. };
  33647. StopSoundAction.prototype.serialize = function (parent) {
  33648. return _super.prototype._serialize.call(this, {
  33649. name: "StopSoundAction",
  33650. properties: [{ name: "sound", value: this._sound.name }]
  33651. }, parent);
  33652. };
  33653. return StopSoundAction;
  33654. })(BABYLON.Action);
  33655. BABYLON.StopSoundAction = StopSoundAction;
  33656. })(BABYLON || (BABYLON = {}));
  33657. var BABYLON;
  33658. (function (BABYLON) {
  33659. var Geometry = (function () {
  33660. function Geometry(id, scene, vertexData, updatable, mesh) {
  33661. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33662. this._totalVertices = 0;
  33663. this._isDisposed = false;
  33664. this.id = id;
  33665. this._engine = scene.getEngine();
  33666. this._meshes = [];
  33667. this._scene = scene;
  33668. //Init vertex buffer cache
  33669. this._vertexBuffers = {};
  33670. this._indices = [];
  33671. // vertexData
  33672. if (vertexData) {
  33673. this.setAllVerticesData(vertexData, updatable);
  33674. }
  33675. else {
  33676. this._totalVertices = 0;
  33677. this._indices = [];
  33678. }
  33679. // applyToMesh
  33680. if (mesh) {
  33681. if (mesh instanceof BABYLON.LinesMesh) {
  33682. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  33683. this.updateExtend();
  33684. }
  33685. this.applyToMesh(mesh);
  33686. mesh.computeWorldMatrix(true);
  33687. }
  33688. }
  33689. Object.defineProperty(Geometry.prototype, "boundingBias", {
  33690. /**
  33691. * 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
  33692. * @returns The Bias Vector
  33693. */
  33694. get: function () {
  33695. return this._boundingBias;
  33696. },
  33697. set: function (value) {
  33698. if (this._boundingBias && this._boundingBias.equals(value)) {
  33699. return;
  33700. }
  33701. this._boundingBias = value.clone();
  33702. this.updateBoundingInfo(true, null);
  33703. },
  33704. enumerable: true,
  33705. configurable: true
  33706. });
  33707. Object.defineProperty(Geometry.prototype, "extend", {
  33708. get: function () {
  33709. return this._extend;
  33710. },
  33711. enumerable: true,
  33712. configurable: true
  33713. });
  33714. Geometry.prototype.getScene = function () {
  33715. return this._scene;
  33716. };
  33717. Geometry.prototype.getEngine = function () {
  33718. return this._engine;
  33719. };
  33720. Geometry.prototype.isReady = function () {
  33721. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  33722. };
  33723. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  33724. vertexData.applyToGeometry(this, updatable);
  33725. this.notifyUpdate();
  33726. };
  33727. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  33728. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  33729. this.setVerticesBuffer(buffer);
  33730. };
  33731. Geometry.prototype.setVerticesBuffer = function (buffer) {
  33732. var kind = buffer.getKind();
  33733. if (this._vertexBuffers[kind]) {
  33734. this._vertexBuffers[kind].dispose();
  33735. }
  33736. this._vertexBuffers[kind] = buffer;
  33737. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33738. var data = buffer.getData();
  33739. var stride = buffer.getStrideSize();
  33740. this._totalVertices = data.length / stride;
  33741. this.updateExtend(data, stride);
  33742. var meshes = this._meshes;
  33743. var numOfMeshes = meshes.length;
  33744. for (var index = 0; index < numOfMeshes; index++) {
  33745. var mesh = meshes[index];
  33746. mesh._resetPointsArrayCache();
  33747. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33748. mesh._createGlobalSubMesh();
  33749. mesh.computeWorldMatrix(true);
  33750. }
  33751. }
  33752. this.notifyUpdate(kind);
  33753. };
  33754. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  33755. var vertexBuffer = this.getVertexBuffer(kind);
  33756. if (!vertexBuffer) {
  33757. return;
  33758. }
  33759. vertexBuffer.updateDirectly(data, offset);
  33760. this.notifyUpdate(kind);
  33761. };
  33762. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  33763. var vertexBuffer = this.getVertexBuffer(kind);
  33764. if (!vertexBuffer) {
  33765. return;
  33766. }
  33767. vertexBuffer.update(data);
  33768. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33769. var stride = vertexBuffer.getStrideSize();
  33770. this._totalVertices = data.length / stride;
  33771. this.updateBoundingInfo(updateExtends, data);
  33772. }
  33773. this.notifyUpdate(kind);
  33774. };
  33775. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  33776. if (updateExtends) {
  33777. this.updateExtend(data);
  33778. }
  33779. var meshes = this._meshes;
  33780. var numOfMeshes = meshes.length;
  33781. for (var index = 0; index < numOfMeshes; index++) {
  33782. var mesh = meshes[index];
  33783. mesh._resetPointsArrayCache();
  33784. if (updateExtends) {
  33785. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33786. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  33787. var subMesh = mesh.subMeshes[subIndex];
  33788. subMesh.refreshBoundingInfo();
  33789. }
  33790. }
  33791. }
  33792. };
  33793. Geometry.prototype.getTotalVertices = function () {
  33794. if (!this.isReady()) {
  33795. return 0;
  33796. }
  33797. return this._totalVertices;
  33798. };
  33799. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  33800. var vertexBuffer = this.getVertexBuffer(kind);
  33801. if (!vertexBuffer) {
  33802. return null;
  33803. }
  33804. var orig = vertexBuffer.getData();
  33805. if (!copyWhenShared || this._meshes.length === 1) {
  33806. return orig;
  33807. }
  33808. else {
  33809. var len = orig.length;
  33810. var copy = [];
  33811. for (var i = 0; i < len; i++) {
  33812. copy.push(orig[i]);
  33813. }
  33814. return copy;
  33815. }
  33816. };
  33817. Geometry.prototype.getVertexBuffer = function (kind) {
  33818. if (!this.isReady()) {
  33819. return null;
  33820. }
  33821. return this._vertexBuffers[kind];
  33822. };
  33823. Geometry.prototype.getVertexBuffers = function () {
  33824. if (!this.isReady()) {
  33825. return null;
  33826. }
  33827. return this._vertexBuffers;
  33828. };
  33829. Geometry.prototype.isVerticesDataPresent = function (kind) {
  33830. if (!this._vertexBuffers) {
  33831. if (this._delayInfo) {
  33832. return this._delayInfo.indexOf(kind) !== -1;
  33833. }
  33834. return false;
  33835. }
  33836. return this._vertexBuffers[kind] !== undefined;
  33837. };
  33838. Geometry.prototype.getVerticesDataKinds = function () {
  33839. var result = [];
  33840. var kind;
  33841. if (!this._vertexBuffers && this._delayInfo) {
  33842. for (kind in this._delayInfo) {
  33843. result.push(kind);
  33844. }
  33845. }
  33846. else {
  33847. for (kind in this._vertexBuffers) {
  33848. result.push(kind);
  33849. }
  33850. }
  33851. return result;
  33852. };
  33853. Geometry.prototype.setIndices = function (indices, totalVertices) {
  33854. if (this._indexBuffer) {
  33855. this._engine._releaseBuffer(this._indexBuffer);
  33856. }
  33857. this._indices = indices;
  33858. if (this._meshes.length !== 0 && this._indices) {
  33859. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33860. }
  33861. if (totalVertices !== undefined) {
  33862. this._totalVertices = totalVertices;
  33863. }
  33864. var meshes = this._meshes;
  33865. var numOfMeshes = meshes.length;
  33866. for (var index = 0; index < numOfMeshes; index++) {
  33867. meshes[index]._createGlobalSubMesh();
  33868. }
  33869. this.notifyUpdate();
  33870. };
  33871. Geometry.prototype.getTotalIndices = function () {
  33872. if (!this.isReady()) {
  33873. return 0;
  33874. }
  33875. return this._indices.length;
  33876. };
  33877. Geometry.prototype.getIndices = function (copyWhenShared) {
  33878. if (!this.isReady()) {
  33879. return null;
  33880. }
  33881. var orig = this._indices;
  33882. if (!copyWhenShared || this._meshes.length === 1) {
  33883. return orig;
  33884. }
  33885. else {
  33886. var len = orig.length;
  33887. var copy = [];
  33888. for (var i = 0; i < len; i++) {
  33889. copy.push(orig[i]);
  33890. }
  33891. return copy;
  33892. }
  33893. };
  33894. Geometry.prototype.getIndexBuffer = function () {
  33895. if (!this.isReady()) {
  33896. return null;
  33897. }
  33898. return this._indexBuffer;
  33899. };
  33900. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  33901. var meshes = this._meshes;
  33902. var index = meshes.indexOf(mesh);
  33903. if (index === -1) {
  33904. return;
  33905. }
  33906. for (var kind in this._vertexBuffers) {
  33907. this._vertexBuffers[kind].dispose();
  33908. }
  33909. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  33910. this._indexBuffer = null;
  33911. }
  33912. meshes.splice(index, 1);
  33913. mesh._geometry = null;
  33914. if (meshes.length === 0 && shouldDispose) {
  33915. this.dispose();
  33916. }
  33917. };
  33918. Geometry.prototype.applyToMesh = function (mesh) {
  33919. if (mesh._geometry === this) {
  33920. return;
  33921. }
  33922. var previousGeometry = mesh._geometry;
  33923. if (previousGeometry) {
  33924. previousGeometry.releaseForMesh(mesh);
  33925. }
  33926. var meshes = this._meshes;
  33927. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  33928. mesh._geometry = this;
  33929. this._scene.pushGeometry(this);
  33930. meshes.push(mesh);
  33931. if (this.isReady()) {
  33932. this._applyToMesh(mesh);
  33933. }
  33934. else {
  33935. mesh._boundingInfo = this._boundingInfo;
  33936. }
  33937. };
  33938. Geometry.prototype.updateExtend = function (data, stride) {
  33939. if (data === void 0) { data = null; }
  33940. if (!data) {
  33941. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  33942. }
  33943. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  33944. };
  33945. Geometry.prototype._applyToMesh = function (mesh) {
  33946. var numOfMeshes = this._meshes.length;
  33947. // vertexBuffers
  33948. for (var kind in this._vertexBuffers) {
  33949. if (numOfMeshes === 1) {
  33950. this._vertexBuffers[kind].create();
  33951. }
  33952. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  33953. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33954. mesh._resetPointsArrayCache();
  33955. if (!this._extend) {
  33956. this.updateExtend(this._vertexBuffers[kind].getData());
  33957. }
  33958. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33959. mesh._createGlobalSubMesh();
  33960. //bounding info was just created again, world matrix should be applied again.
  33961. mesh._updateBoundingInfo();
  33962. }
  33963. }
  33964. // indexBuffer
  33965. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  33966. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33967. }
  33968. if (this._indexBuffer) {
  33969. this._indexBuffer.references = numOfMeshes;
  33970. }
  33971. };
  33972. Geometry.prototype.notifyUpdate = function (kind) {
  33973. if (this.onGeometryUpdated) {
  33974. this.onGeometryUpdated(this, kind);
  33975. }
  33976. };
  33977. Geometry.prototype.load = function (scene, onLoaded) {
  33978. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33979. return;
  33980. }
  33981. if (this.isReady()) {
  33982. if (onLoaded) {
  33983. onLoaded();
  33984. }
  33985. return;
  33986. }
  33987. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33988. this._queueLoad(scene, onLoaded);
  33989. };
  33990. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  33991. var _this = this;
  33992. scene._addPendingData(this);
  33993. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  33994. _this._delayLoadingFunction(JSON.parse(data), _this);
  33995. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33996. _this._delayInfo = [];
  33997. scene._removePendingData(_this);
  33998. var meshes = _this._meshes;
  33999. var numOfMeshes = meshes.length;
  34000. for (var index = 0; index < numOfMeshes; index++) {
  34001. _this._applyToMesh(meshes[index]);
  34002. }
  34003. if (onLoaded) {
  34004. onLoaded();
  34005. }
  34006. }, function () { }, scene.database);
  34007. };
  34008. /**
  34009. * Invert the geometry to move from a right handed system to a left handed one.
  34010. */
  34011. Geometry.prototype.toLeftHanded = function () {
  34012. // Flip faces
  34013. var tIndices = this.getIndices(false);
  34014. if (tIndices != null && tIndices.length > 0) {
  34015. for (var i = 0; i < tIndices.length; i += 3) {
  34016. var tTemp = tIndices[i + 0];
  34017. tIndices[i + 0] = tIndices[i + 2];
  34018. tIndices[i + 2] = tTemp;
  34019. }
  34020. this.setIndices(tIndices);
  34021. }
  34022. // Negate position.z
  34023. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34024. if (tPositions != null && tPositions.length > 0) {
  34025. for (var i = 0; i < tPositions.length; i += 3) {
  34026. tPositions[i + 2] = -tPositions[i + 2];
  34027. }
  34028. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34029. }
  34030. // Negate normal.z
  34031. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34032. if (tNormals != null && tNormals.length > 0) {
  34033. for (var i = 0; i < tNormals.length; i += 3) {
  34034. tNormals[i + 2] = -tNormals[i + 2];
  34035. }
  34036. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34037. }
  34038. };
  34039. Geometry.prototype.isDisposed = function () {
  34040. return this._isDisposed;
  34041. };
  34042. Geometry.prototype.dispose = function () {
  34043. var meshes = this._meshes;
  34044. var numOfMeshes = meshes.length;
  34045. var index;
  34046. for (index = 0; index < numOfMeshes; index++) {
  34047. this.releaseForMesh(meshes[index]);
  34048. }
  34049. this._meshes = [];
  34050. for (var kind in this._vertexBuffers) {
  34051. this._vertexBuffers[kind].dispose();
  34052. }
  34053. this._vertexBuffers = {};
  34054. this._totalVertices = 0;
  34055. if (this._indexBuffer) {
  34056. this._engine._releaseBuffer(this._indexBuffer);
  34057. }
  34058. this._indexBuffer = null;
  34059. this._indices = [];
  34060. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34061. this.delayLoadingFile = null;
  34062. this._delayLoadingFunction = null;
  34063. this._delayInfo = [];
  34064. this._boundingInfo = null;
  34065. this._scene.removeGeometry(this);
  34066. this._isDisposed = true;
  34067. };
  34068. Geometry.prototype.copy = function (id) {
  34069. var vertexData = new BABYLON.VertexData();
  34070. vertexData.indices = [];
  34071. var indices = this.getIndices();
  34072. for (var index = 0; index < indices.length; index++) {
  34073. vertexData.indices.push(indices[index]);
  34074. }
  34075. var updatable = false;
  34076. var stopChecking = false;
  34077. var kind;
  34078. for (kind in this._vertexBuffers) {
  34079. // using slice() to make a copy of the array and not just reference it
  34080. var data = this.getVerticesData(kind);
  34081. if (data instanceof Float32Array) {
  34082. vertexData.set(new Float32Array(data), kind);
  34083. }
  34084. else {
  34085. vertexData.set(data.slice(0), kind);
  34086. }
  34087. if (!stopChecking) {
  34088. updatable = this.getVertexBuffer(kind).isUpdatable();
  34089. stopChecking = !updatable;
  34090. }
  34091. }
  34092. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  34093. geometry.delayLoadState = this.delayLoadState;
  34094. geometry.delayLoadingFile = this.delayLoadingFile;
  34095. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34096. for (kind in this._delayInfo) {
  34097. geometry._delayInfo = geometry._delayInfo || [];
  34098. geometry._delayInfo.push(kind);
  34099. }
  34100. // Bounding info
  34101. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34102. return geometry;
  34103. };
  34104. Geometry.prototype.serialize = function () {
  34105. var serializationObject = {};
  34106. serializationObject.id = this.id;
  34107. if (BABYLON.Tags.HasTags(this)) {
  34108. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34109. }
  34110. return serializationObject;
  34111. };
  34112. Geometry.prototype.serializeVerticeData = function () {
  34113. var serializationObject = this.serialize();
  34114. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34115. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34116. }
  34117. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34118. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34119. }
  34120. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34121. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34122. }
  34123. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34124. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  34125. }
  34126. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34127. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  34128. }
  34129. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34130. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  34131. }
  34132. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34133. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  34134. }
  34135. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34136. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  34137. }
  34138. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34139. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  34140. }
  34141. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34142. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34143. serializationObject.matricesIndices._isExpanded = true;
  34144. }
  34145. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34146. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34147. }
  34148. serializationObject.indices = this.getIndices();
  34149. return serializationObject;
  34150. };
  34151. // Statics
  34152. Geometry.ExtractFromMesh = function (mesh, id) {
  34153. var geometry = mesh._geometry;
  34154. if (!geometry) {
  34155. return null;
  34156. }
  34157. return geometry.copy(id);
  34158. };
  34159. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  34160. // be aware Math.random() could cause collisions
  34161. Geometry.RandomId = function () {
  34162. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  34163. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  34164. return v.toString(16);
  34165. });
  34166. };
  34167. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  34168. var scene = mesh.getScene();
  34169. // Geometry
  34170. var geometryId = parsedGeometry.geometryId;
  34171. if (geometryId) {
  34172. var geometry = scene.getGeometryByID(geometryId);
  34173. if (geometry) {
  34174. geometry.applyToMesh(mesh);
  34175. }
  34176. }
  34177. else if (parsedGeometry instanceof ArrayBuffer) {
  34178. var binaryInfo = mesh._binaryInfo;
  34179. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  34180. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  34181. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  34182. }
  34183. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  34184. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  34185. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  34186. }
  34187. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  34188. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  34189. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  34190. }
  34191. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  34192. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  34193. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  34194. }
  34195. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  34196. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  34197. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  34198. }
  34199. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  34200. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  34201. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  34202. }
  34203. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  34204. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  34205. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  34206. }
  34207. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  34208. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  34209. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  34210. }
  34211. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  34212. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  34213. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  34214. }
  34215. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  34216. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  34217. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  34218. }
  34219. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  34220. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  34221. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  34222. }
  34223. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  34224. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  34225. mesh.setIndices(indicesData);
  34226. }
  34227. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  34228. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  34229. mesh.subMeshes = [];
  34230. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  34231. var materialIndex = subMeshesData[(i * 5) + 0];
  34232. var verticesStart = subMeshesData[(i * 5) + 1];
  34233. var verticesCount = subMeshesData[(i * 5) + 2];
  34234. var indexStart = subMeshesData[(i * 5) + 3];
  34235. var indexCount = subMeshesData[(i * 5) + 4];
  34236. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  34237. }
  34238. }
  34239. }
  34240. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  34241. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  34242. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  34243. if (parsedGeometry.uvs) {
  34244. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  34245. }
  34246. if (parsedGeometry.uvs2) {
  34247. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  34248. }
  34249. if (parsedGeometry.uvs3) {
  34250. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  34251. }
  34252. if (parsedGeometry.uvs4) {
  34253. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  34254. }
  34255. if (parsedGeometry.uvs5) {
  34256. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  34257. }
  34258. if (parsedGeometry.uvs6) {
  34259. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  34260. }
  34261. if (parsedGeometry.colors) {
  34262. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  34263. }
  34264. if (parsedGeometry.matricesIndices) {
  34265. if (!parsedGeometry.matricesIndices._isExpanded) {
  34266. var floatIndices = [];
  34267. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  34268. var matricesIndex = parsedGeometry.matricesIndices[i];
  34269. floatIndices.push(matricesIndex & 0x000000FF);
  34270. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34271. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34272. floatIndices.push(matricesIndex >> 24);
  34273. }
  34274. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  34275. }
  34276. else {
  34277. delete parsedGeometry.matricesIndices._isExpanded;
  34278. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  34279. }
  34280. }
  34281. if (parsedGeometry.matricesIndicesExtra) {
  34282. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  34283. var floatIndices = [];
  34284. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  34285. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  34286. floatIndices.push(matricesIndex & 0x000000FF);
  34287. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34288. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34289. floatIndices.push(matricesIndex >> 24);
  34290. }
  34291. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  34292. }
  34293. else {
  34294. delete parsedGeometry.matricesIndices._isExpanded;
  34295. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  34296. }
  34297. }
  34298. if (parsedGeometry.matricesWeights) {
  34299. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  34300. }
  34301. if (parsedGeometry.matricesWeightsExtra) {
  34302. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  34303. }
  34304. mesh.setIndices(parsedGeometry.indices);
  34305. }
  34306. // SubMeshes
  34307. if (parsedGeometry.subMeshes) {
  34308. mesh.subMeshes = [];
  34309. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  34310. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  34311. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  34312. }
  34313. }
  34314. // Flat shading
  34315. if (mesh._shouldGenerateFlatShading) {
  34316. mesh.convertToFlatShadedMesh();
  34317. delete mesh._shouldGenerateFlatShading;
  34318. }
  34319. // Update
  34320. mesh.computeWorldMatrix(true);
  34321. // Octree
  34322. if (scene['_selectionOctree']) {
  34323. scene['_selectionOctree'].addMesh(mesh);
  34324. }
  34325. };
  34326. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  34327. if (scene.getGeometryByID(parsedVertexData.id)) {
  34328. return null; // null since geometry could be something else than a box...
  34329. }
  34330. var geometry = new Geometry(parsedVertexData.id, scene);
  34331. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  34332. if (parsedVertexData.delayLoadingFile) {
  34333. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  34334. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  34335. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  34336. geometry._delayInfo = [];
  34337. if (parsedVertexData.hasUVs) {
  34338. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  34339. }
  34340. if (parsedVertexData.hasUVs2) {
  34341. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  34342. }
  34343. if (parsedVertexData.hasUVs3) {
  34344. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  34345. }
  34346. if (parsedVertexData.hasUVs4) {
  34347. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  34348. }
  34349. if (parsedVertexData.hasUVs5) {
  34350. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  34351. }
  34352. if (parsedVertexData.hasUVs6) {
  34353. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  34354. }
  34355. if (parsedVertexData.hasColors) {
  34356. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  34357. }
  34358. if (parsedVertexData.hasMatricesIndices) {
  34359. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34360. }
  34361. if (parsedVertexData.hasMatricesWeights) {
  34362. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34363. }
  34364. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  34365. }
  34366. else {
  34367. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  34368. }
  34369. scene.pushGeometry(geometry, true);
  34370. return geometry;
  34371. };
  34372. return Geometry;
  34373. })();
  34374. BABYLON.Geometry = Geometry;
  34375. /////// Primitives //////////////////////////////////////////////
  34376. var Geometry;
  34377. (function (Geometry) {
  34378. var Primitives;
  34379. (function (Primitives) {
  34380. /// Abstract class
  34381. var _Primitive = (function (_super) {
  34382. __extends(_Primitive, _super);
  34383. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  34384. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  34385. this._canBeRegenerated = _canBeRegenerated;
  34386. this._beingRegenerated = true;
  34387. this.regenerate();
  34388. this._beingRegenerated = false;
  34389. }
  34390. _Primitive.prototype.canBeRegenerated = function () {
  34391. return this._canBeRegenerated;
  34392. };
  34393. _Primitive.prototype.regenerate = function () {
  34394. if (!this._canBeRegenerated) {
  34395. return;
  34396. }
  34397. this._beingRegenerated = true;
  34398. this.setAllVerticesData(this._regenerateVertexData(), false);
  34399. this._beingRegenerated = false;
  34400. };
  34401. _Primitive.prototype.asNewGeometry = function (id) {
  34402. return _super.prototype.copy.call(this, id);
  34403. };
  34404. // overrides
  34405. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  34406. if (!this._beingRegenerated) {
  34407. return;
  34408. }
  34409. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  34410. };
  34411. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  34412. if (!this._beingRegenerated) {
  34413. return;
  34414. }
  34415. _super.prototype.setVerticesData.call(this, kind, data, false);
  34416. };
  34417. // to override
  34418. // protected
  34419. _Primitive.prototype._regenerateVertexData = function () {
  34420. throw new Error("Abstract method");
  34421. };
  34422. _Primitive.prototype.copy = function (id) {
  34423. throw new Error("Must be overriden in sub-classes.");
  34424. };
  34425. _Primitive.prototype.serialize = function () {
  34426. var serializationObject = _super.prototype.serialize.call(this);
  34427. serializationObject.canBeRegenerated = this.canBeRegenerated();
  34428. return serializationObject;
  34429. };
  34430. return _Primitive;
  34431. })(Geometry);
  34432. Primitives._Primitive = _Primitive;
  34433. var Ribbon = (function (_super) {
  34434. __extends(Ribbon, _super);
  34435. // Members
  34436. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  34437. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34438. _super.call(this, id, scene, canBeRegenerated, mesh);
  34439. this.pathArray = pathArray;
  34440. this.closeArray = closeArray;
  34441. this.closePath = closePath;
  34442. this.offset = offset;
  34443. this.side = side;
  34444. }
  34445. Ribbon.prototype._regenerateVertexData = function () {
  34446. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  34447. };
  34448. Ribbon.prototype.copy = function (id) {
  34449. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  34450. };
  34451. return Ribbon;
  34452. })(_Primitive);
  34453. Primitives.Ribbon = Ribbon;
  34454. var Box = (function (_super) {
  34455. __extends(Box, _super);
  34456. // Members
  34457. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  34458. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34459. _super.call(this, id, scene, canBeRegenerated, mesh);
  34460. this.size = size;
  34461. this.side = side;
  34462. }
  34463. Box.prototype._regenerateVertexData = function () {
  34464. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  34465. };
  34466. Box.prototype.copy = function (id) {
  34467. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  34468. };
  34469. Box.prototype.serialize = function () {
  34470. var serializationObject = _super.prototype.serialize.call(this);
  34471. serializationObject.size = this.size;
  34472. return serializationObject;
  34473. };
  34474. Box.Parse = function (parsedBox, scene) {
  34475. if (scene.getGeometryByID(parsedBox.id)) {
  34476. return null; // null since geometry could be something else than a box...
  34477. }
  34478. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  34479. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  34480. scene.pushGeometry(box, true);
  34481. return box;
  34482. };
  34483. return Box;
  34484. })(_Primitive);
  34485. Primitives.Box = Box;
  34486. var Sphere = (function (_super) {
  34487. __extends(Sphere, _super);
  34488. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  34489. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34490. _super.call(this, id, scene, canBeRegenerated, mesh);
  34491. this.segments = segments;
  34492. this.diameter = diameter;
  34493. this.side = side;
  34494. }
  34495. Sphere.prototype._regenerateVertexData = function () {
  34496. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  34497. };
  34498. Sphere.prototype.copy = function (id) {
  34499. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  34500. };
  34501. Sphere.prototype.serialize = function () {
  34502. var serializationObject = _super.prototype.serialize.call(this);
  34503. serializationObject.segments = this.segments;
  34504. serializationObject.diameter = this.diameter;
  34505. return serializationObject;
  34506. };
  34507. Sphere.Parse = function (parsedSphere, scene) {
  34508. if (scene.getGeometryByID(parsedSphere.id)) {
  34509. return null; // null since geometry could be something else than a sphere...
  34510. }
  34511. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  34512. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  34513. scene.pushGeometry(sphere, true);
  34514. return sphere;
  34515. };
  34516. return Sphere;
  34517. })(_Primitive);
  34518. Primitives.Sphere = Sphere;
  34519. var Disc = (function (_super) {
  34520. __extends(Disc, _super);
  34521. // Members
  34522. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  34523. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34524. _super.call(this, id, scene, canBeRegenerated, mesh);
  34525. this.radius = radius;
  34526. this.tessellation = tessellation;
  34527. this.side = side;
  34528. }
  34529. Disc.prototype._regenerateVertexData = function () {
  34530. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  34531. };
  34532. Disc.prototype.copy = function (id) {
  34533. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  34534. };
  34535. return Disc;
  34536. })(_Primitive);
  34537. Primitives.Disc = Disc;
  34538. var Cylinder = (function (_super) {
  34539. __extends(Cylinder, _super);
  34540. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  34541. if (subdivisions === void 0) { subdivisions = 1; }
  34542. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34543. _super.call(this, id, scene, canBeRegenerated, mesh);
  34544. this.height = height;
  34545. this.diameterTop = diameterTop;
  34546. this.diameterBottom = diameterBottom;
  34547. this.tessellation = tessellation;
  34548. this.subdivisions = subdivisions;
  34549. this.side = side;
  34550. }
  34551. Cylinder.prototype._regenerateVertexData = function () {
  34552. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  34553. };
  34554. Cylinder.prototype.copy = function (id) {
  34555. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  34556. };
  34557. Cylinder.prototype.serialize = function () {
  34558. var serializationObject = _super.prototype.serialize.call(this);
  34559. serializationObject.height = this.height;
  34560. serializationObject.diameterTop = this.diameterTop;
  34561. serializationObject.diameterBottom = this.diameterBottom;
  34562. serializationObject.tessellation = this.tessellation;
  34563. return serializationObject;
  34564. };
  34565. Cylinder.Parse = function (parsedCylinder, scene) {
  34566. if (scene.getGeometryByID(parsedCylinder.id)) {
  34567. return null; // null since geometry could be something else than a cylinder...
  34568. }
  34569. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  34570. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  34571. scene.pushGeometry(cylinder, true);
  34572. return cylinder;
  34573. };
  34574. return Cylinder;
  34575. })(_Primitive);
  34576. Primitives.Cylinder = Cylinder;
  34577. var Torus = (function (_super) {
  34578. __extends(Torus, _super);
  34579. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  34580. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34581. _super.call(this, id, scene, canBeRegenerated, mesh);
  34582. this.diameter = diameter;
  34583. this.thickness = thickness;
  34584. this.tessellation = tessellation;
  34585. this.side = side;
  34586. }
  34587. Torus.prototype._regenerateVertexData = function () {
  34588. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  34589. };
  34590. Torus.prototype.copy = function (id) {
  34591. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  34592. };
  34593. Torus.prototype.serialize = function () {
  34594. var serializationObject = _super.prototype.serialize.call(this);
  34595. serializationObject.diameter = this.diameter;
  34596. serializationObject.thickness = this.thickness;
  34597. serializationObject.tessellation = this.tessellation;
  34598. return serializationObject;
  34599. };
  34600. Torus.Parse = function (parsedTorus, scene) {
  34601. if (scene.getGeometryByID(parsedTorus.id)) {
  34602. return null; // null since geometry could be something else than a torus...
  34603. }
  34604. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  34605. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  34606. scene.pushGeometry(torus, true);
  34607. return torus;
  34608. };
  34609. return Torus;
  34610. })(_Primitive);
  34611. Primitives.Torus = Torus;
  34612. var Ground = (function (_super) {
  34613. __extends(Ground, _super);
  34614. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  34615. _super.call(this, id, scene, canBeRegenerated, mesh);
  34616. this.width = width;
  34617. this.height = height;
  34618. this.subdivisions = subdivisions;
  34619. }
  34620. Ground.prototype._regenerateVertexData = function () {
  34621. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  34622. };
  34623. Ground.prototype.copy = function (id) {
  34624. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  34625. };
  34626. Ground.prototype.serialize = function () {
  34627. var serializationObject = _super.prototype.serialize.call(this);
  34628. serializationObject.width = this.width;
  34629. serializationObject.height = this.height;
  34630. serializationObject.subdivisions = this.subdivisions;
  34631. return serializationObject;
  34632. };
  34633. Ground.Parse = function (parsedGround, scene) {
  34634. if (scene.getGeometryByID(parsedGround.id)) {
  34635. return null; // null since geometry could be something else than a ground...
  34636. }
  34637. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  34638. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  34639. scene.pushGeometry(ground, true);
  34640. return ground;
  34641. };
  34642. return Ground;
  34643. })(_Primitive);
  34644. Primitives.Ground = Ground;
  34645. var TiledGround = (function (_super) {
  34646. __extends(TiledGround, _super);
  34647. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  34648. _super.call(this, id, scene, canBeRegenerated, mesh);
  34649. this.xmin = xmin;
  34650. this.zmin = zmin;
  34651. this.xmax = xmax;
  34652. this.zmax = zmax;
  34653. this.subdivisions = subdivisions;
  34654. this.precision = precision;
  34655. }
  34656. TiledGround.prototype._regenerateVertexData = function () {
  34657. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  34658. };
  34659. TiledGround.prototype.copy = function (id) {
  34660. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  34661. };
  34662. return TiledGround;
  34663. })(_Primitive);
  34664. Primitives.TiledGround = TiledGround;
  34665. var Plane = (function (_super) {
  34666. __extends(Plane, _super);
  34667. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  34668. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34669. _super.call(this, id, scene, canBeRegenerated, mesh);
  34670. this.size = size;
  34671. this.side = side;
  34672. }
  34673. Plane.prototype._regenerateVertexData = function () {
  34674. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  34675. };
  34676. Plane.prototype.copy = function (id) {
  34677. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  34678. };
  34679. Plane.prototype.serialize = function () {
  34680. var serializationObject = _super.prototype.serialize.call(this);
  34681. serializationObject.size = this.size;
  34682. return serializationObject;
  34683. };
  34684. Plane.Parse = function (parsedPlane, scene) {
  34685. if (scene.getGeometryByID(parsedPlane.id)) {
  34686. return null; // null since geometry could be something else than a ground...
  34687. }
  34688. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  34689. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  34690. scene.pushGeometry(plane, true);
  34691. return plane;
  34692. };
  34693. return Plane;
  34694. })(_Primitive);
  34695. Primitives.Plane = Plane;
  34696. var TorusKnot = (function (_super) {
  34697. __extends(TorusKnot, _super);
  34698. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  34699. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34700. _super.call(this, id, scene, canBeRegenerated, mesh);
  34701. this.radius = radius;
  34702. this.tube = tube;
  34703. this.radialSegments = radialSegments;
  34704. this.tubularSegments = tubularSegments;
  34705. this.p = p;
  34706. this.q = q;
  34707. this.side = side;
  34708. }
  34709. TorusKnot.prototype._regenerateVertexData = function () {
  34710. 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 });
  34711. };
  34712. TorusKnot.prototype.copy = function (id) {
  34713. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  34714. };
  34715. TorusKnot.prototype.serialize = function () {
  34716. var serializationObject = _super.prototype.serialize.call(this);
  34717. serializationObject.radius = this.radius;
  34718. serializationObject.tube = this.tube;
  34719. serializationObject.radialSegments = this.radialSegments;
  34720. serializationObject.tubularSegments = this.tubularSegments;
  34721. serializationObject.p = this.p;
  34722. serializationObject.q = this.q;
  34723. return serializationObject;
  34724. };
  34725. ;
  34726. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  34727. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  34728. return null; // null since geometry could be something else than a ground...
  34729. }
  34730. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  34731. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  34732. scene.pushGeometry(torusKnot, true);
  34733. return torusKnot;
  34734. };
  34735. return TorusKnot;
  34736. })(_Primitive);
  34737. Primitives.TorusKnot = TorusKnot;
  34738. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  34739. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  34740. })(BABYLON || (BABYLON = {}));
  34741. var BABYLON;
  34742. (function (BABYLON) {
  34743. var GroundMesh = (function (_super) {
  34744. __extends(GroundMesh, _super);
  34745. function GroundMesh(name, scene) {
  34746. _super.call(this, name, scene);
  34747. this.generateOctree = false;
  34748. this._worldInverse = new BABYLON.Matrix();
  34749. }
  34750. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  34751. get: function () {
  34752. return this._subdivisions;
  34753. },
  34754. enumerable: true,
  34755. configurable: true
  34756. });
  34757. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  34758. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  34759. this._subdivisions = chunksCount;
  34760. this.subdivide(this._subdivisions);
  34761. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  34762. };
  34763. /**
  34764. * Returns a height (y) value in the Worl system :
  34765. * the ground altitude at the coordinates (x, z) expressed in the World system.
  34766. * Returns the ground y position if (x, z) are outside the ground surface.
  34767. * Not pertinent if the ground is rotated.
  34768. */
  34769. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  34770. // express x and y in the ground local system
  34771. x -= this.position.x;
  34772. z -= this.position.z;
  34773. x /= this.scaling.x;
  34774. z /= this.scaling.z;
  34775. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  34776. return this.position.y;
  34777. }
  34778. if (!this._heightQuads || this._heightQuads.length == 0) {
  34779. this._initHeightQuads();
  34780. this._computeHeightQuads();
  34781. }
  34782. var facet = this._getFacetAt(x, z);
  34783. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  34784. // return y in the World system
  34785. return y * this.scaling.y + this.position.y;
  34786. };
  34787. /**
  34788. * Returns a normalized vector (Vector3) orthogonal to the ground
  34789. * at the ground coordinates (x, z) expressed in the World system.
  34790. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  34791. * Not pertinent if the ground is rotated.
  34792. */
  34793. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  34794. var normal = new BABYLON.Vector3(0, 1, 0);
  34795. this.getNormalAtCoordinatesToRef(x, z, normal);
  34796. return normal;
  34797. };
  34798. /**
  34799. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  34800. * at the ground coordinates (x, z) expressed in the World system.
  34801. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  34802. * Not pertinent if the ground is rotated.
  34803. */
  34804. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  34805. // express x and y in the ground local system
  34806. x -= this.position.x;
  34807. z -= this.position.z;
  34808. x /= this.scaling.x;
  34809. z /= this.scaling.z;
  34810. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  34811. return;
  34812. }
  34813. if (!this._heightQuads || this._heightQuads.length == 0) {
  34814. this._initHeightQuads();
  34815. this._computeHeightQuads();
  34816. }
  34817. var facet = this._getFacetAt(x, z);
  34818. ref.x = facet.x;
  34819. ref.y = facet.y;
  34820. ref.z = facet.z;
  34821. };
  34822. /**
  34823. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  34824. * if the ground has been updated.
  34825. * This can be used in the render loop
  34826. */
  34827. GroundMesh.prototype.updateCoordinateHeights = function () {
  34828. if (!this._heightQuads || this._heightQuads.length == 0) {
  34829. this._initHeightQuads();
  34830. }
  34831. this._computeHeightQuads();
  34832. };
  34833. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  34834. GroundMesh.prototype._getFacetAt = function (x, z) {
  34835. // retrieve col and row from x, z coordinates in the ground local system
  34836. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  34837. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  34838. var quad = this._heightQuads[row * this._subdivisions + col];
  34839. var facet;
  34840. if (z < quad.slope.x * x + quad.slope.y) {
  34841. facet = quad.facet1;
  34842. }
  34843. else {
  34844. facet = quad.facet2;
  34845. }
  34846. return facet;
  34847. };
  34848. // Creates and populates the heightMap array with "facet" elements :
  34849. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  34850. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34851. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34852. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34853. GroundMesh.prototype._initHeightQuads = function () {
  34854. this._heightQuads = new Array();
  34855. for (var row = 0; row < this._subdivisions; row++) {
  34856. for (var col = 0; col < this._subdivisions; col++) {
  34857. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  34858. this._heightQuads[row * this._subdivisions + col] = quad;
  34859. }
  34860. }
  34861. };
  34862. // Compute each quad element values and update the the heightMap array :
  34863. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34864. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34865. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34866. GroundMesh.prototype._computeHeightQuads = function () {
  34867. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34868. var v1 = BABYLON.Tmp.Vector3[3];
  34869. var v2 = BABYLON.Tmp.Vector3[2];
  34870. var v3 = BABYLON.Tmp.Vector3[1];
  34871. var v4 = BABYLON.Tmp.Vector3[0];
  34872. var v1v2 = BABYLON.Tmp.Vector3[4];
  34873. var v1v3 = BABYLON.Tmp.Vector3[5];
  34874. var v1v4 = BABYLON.Tmp.Vector3[6];
  34875. var norm1 = BABYLON.Tmp.Vector3[7];
  34876. var norm2 = BABYLON.Tmp.Vector3[8];
  34877. var i = 0;
  34878. var j = 0;
  34879. var k = 0;
  34880. var cd = 0; // 2D slope coefficient : z = cd * x + h
  34881. var h = 0;
  34882. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  34883. var d2 = 0;
  34884. for (var row = 0; row < this._subdivisions; row++) {
  34885. for (var col = 0; col < this._subdivisions; col++) {
  34886. i = col * 3;
  34887. j = row * (this._subdivisions + 1) * 3;
  34888. k = (row + 1) * (this._subdivisions + 1) * 3;
  34889. v1.x = positions[j + i];
  34890. v1.y = positions[j + i + 1];
  34891. v1.z = positions[j + i + 2];
  34892. v2.x = positions[j + i + 3];
  34893. v2.y = positions[j + i + 4];
  34894. v2.z = positions[j + i + 5];
  34895. v3.x = positions[k + i];
  34896. v3.y = positions[k + i + 1];
  34897. v3.z = positions[k + i + 2];
  34898. v4.x = positions[k + i + 3];
  34899. v4.y = positions[k + i + 4];
  34900. v4.z = positions[k + i + 5];
  34901. // 2D slope V1V4
  34902. cd = (v4.z - v1.z) / (v4.x - v1.x);
  34903. h = v1.z - cd * v1.x; // v1 belongs to the slope
  34904. // facet equations :
  34905. // we compute each facet normal vector
  34906. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  34907. // we compute the value d by applying the equation to v1 which belongs to the plane
  34908. // then we store the facet equation in a Vector4
  34909. v2.subtractToRef(v1, v1v2);
  34910. v3.subtractToRef(v1, v1v3);
  34911. v4.subtractToRef(v1, v1v4);
  34912. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  34913. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  34914. norm1.normalize();
  34915. norm2.normalize();
  34916. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  34917. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  34918. var quad = this._heightQuads[row * this._subdivisions + col];
  34919. quad.slope.copyFromFloats(cd, h);
  34920. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  34921. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  34922. }
  34923. }
  34924. };
  34925. return GroundMesh;
  34926. })(BABYLON.Mesh);
  34927. BABYLON.GroundMesh = GroundMesh;
  34928. })(BABYLON || (BABYLON = {}));
  34929. var BABYLON;
  34930. (function (BABYLON) {
  34931. var LinesMesh = (function (_super) {
  34932. __extends(LinesMesh, _super);
  34933. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  34934. if (parent === void 0) { parent = null; }
  34935. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  34936. this.color = new BABYLON.Color3(1, 1, 1);
  34937. this.alpha = 1;
  34938. this._positionBuffer = {};
  34939. if (source) {
  34940. this.color = source.color.clone();
  34941. this.alpha = source.alpha;
  34942. }
  34943. this._intersectionThreshold = 0.1;
  34944. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  34945. attributes: [BABYLON.VertexBuffer.PositionKind],
  34946. uniforms: ["worldViewProjection", "color"],
  34947. needAlphaBlending: true
  34948. });
  34949. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  34950. }
  34951. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  34952. /**
  34953. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  34954. * This margin is expressed in world space coordinates, so its value may vary.
  34955. * Default value is 0.1
  34956. * @returns the intersection Threshold value.
  34957. */
  34958. get: function () {
  34959. return this._intersectionThreshold;
  34960. },
  34961. /**
  34962. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  34963. * This margin is expressed in world space coordinates, so its value may vary.
  34964. * @param value the new threshold to apply
  34965. */
  34966. set: function (value) {
  34967. if (this._intersectionThreshold === value) {
  34968. return;
  34969. }
  34970. this._intersectionThreshold = value;
  34971. if (this.geometry) {
  34972. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  34973. }
  34974. },
  34975. enumerable: true,
  34976. configurable: true
  34977. });
  34978. Object.defineProperty(LinesMesh.prototype, "material", {
  34979. get: function () {
  34980. return this._colorShader;
  34981. },
  34982. enumerable: true,
  34983. configurable: true
  34984. });
  34985. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  34986. get: function () {
  34987. return false;
  34988. },
  34989. enumerable: true,
  34990. configurable: true
  34991. });
  34992. LinesMesh.prototype.createInstance = function (name) {
  34993. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  34994. return null;
  34995. };
  34996. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  34997. var engine = this.getScene().getEngine();
  34998. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  34999. // VBOs
  35000. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  35001. // Color
  35002. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  35003. };
  35004. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  35005. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  35006. return;
  35007. }
  35008. var engine = this.getScene().getEngine();
  35009. // Draw order
  35010. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  35011. };
  35012. LinesMesh.prototype.dispose = function (doNotRecurse) {
  35013. this._colorShader.dispose();
  35014. _super.prototype.dispose.call(this, doNotRecurse);
  35015. };
  35016. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  35017. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  35018. };
  35019. return LinesMesh;
  35020. })(BABYLON.Mesh);
  35021. BABYLON.LinesMesh = LinesMesh;
  35022. })(BABYLON || (BABYLON = {}));
  35023. var BABYLON;
  35024. (function (BABYLON) {
  35025. var DefaultLoadingScreen = (function () {
  35026. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  35027. var _this = this;
  35028. if (_loadingText === void 0) { _loadingText = ""; }
  35029. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  35030. this._renderingCanvas = _renderingCanvas;
  35031. this._loadingText = _loadingText;
  35032. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  35033. // Resize
  35034. this._resizeLoadingUI = function () {
  35035. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  35036. _this._loadingDiv.style.position = "absolute";
  35037. _this._loadingDiv.style.left = canvasRect.left + "px";
  35038. _this._loadingDiv.style.top = canvasRect.top + "px";
  35039. _this._loadingDiv.style.width = canvasRect.width + "px";
  35040. _this._loadingDiv.style.height = canvasRect.height + "px";
  35041. };
  35042. }
  35043. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  35044. var _this = this;
  35045. if (this._loadingDiv) {
  35046. // Do not add a loading screen if there is already one
  35047. return;
  35048. }
  35049. this._loadingDiv = document.createElement("div");
  35050. this._loadingDiv.id = "babylonjsLoadingDiv";
  35051. this._loadingDiv.style.opacity = "0";
  35052. this._loadingDiv.style.transition = "opacity 1.5s ease";
  35053. // Loading text
  35054. this._loadingTextDiv = document.createElement("div");
  35055. this._loadingTextDiv.style.position = "absolute";
  35056. this._loadingTextDiv.style.left = "0";
  35057. this._loadingTextDiv.style.top = "50%";
  35058. this._loadingTextDiv.style.marginTop = "80px";
  35059. this._loadingTextDiv.style.width = "100%";
  35060. this._loadingTextDiv.style.height = "20px";
  35061. this._loadingTextDiv.style.fontFamily = "Arial";
  35062. this._loadingTextDiv.style.fontSize = "14px";
  35063. this._loadingTextDiv.style.color = "white";
  35064. this._loadingTextDiv.style.textAlign = "center";
  35065. this._loadingTextDiv.innerHTML = "Loading";
  35066. this._loadingDiv.appendChild(this._loadingTextDiv);
  35067. //set the predefined text
  35068. this._loadingTextDiv.innerHTML = this._loadingText;
  35069. // Loading img
  35070. var imgBack = new Image();
  35071. 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==";
  35072. imgBack.style.position = "absolute";
  35073. imgBack.style.left = "50%";
  35074. imgBack.style.top = "50%";
  35075. imgBack.style.marginLeft = "-50px";
  35076. imgBack.style.marginTop = "-50px";
  35077. imgBack.style.transition = "transform 1.0s ease";
  35078. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  35079. var deg = 360;
  35080. var onTransitionEnd = function () {
  35081. deg += 360;
  35082. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  35083. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  35084. };
  35085. imgBack.addEventListener("transitionend", onTransitionEnd);
  35086. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  35087. this._loadingDiv.appendChild(imgBack);
  35088. // front image
  35089. var imgFront = new Image();
  35090. 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=";
  35091. imgFront.style.position = "absolute";
  35092. imgFront.style.left = "50%";
  35093. imgFront.style.top = "50%";
  35094. imgFront.style.marginLeft = "-50px";
  35095. imgFront.style.marginTop = "-50px";
  35096. this._loadingDiv.appendChild(imgFront);
  35097. this._resizeLoadingUI();
  35098. window.addEventListener("resize", this._resizeLoadingUI);
  35099. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  35100. document.body.appendChild(this._loadingDiv);
  35101. setTimeout(function () {
  35102. _this._loadingDiv.style.opacity = "1";
  35103. imgBack.style.transform = "rotateZ(360deg)";
  35104. imgBack.style.webkitTransform = "rotateZ(360deg)";
  35105. }, 0);
  35106. };
  35107. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  35108. var _this = this;
  35109. if (!this._loadingDiv) {
  35110. return;
  35111. }
  35112. var onTransitionEnd = function () {
  35113. if (!_this._loadingDiv) {
  35114. return;
  35115. }
  35116. document.body.removeChild(_this._loadingDiv);
  35117. window.removeEventListener("resize", _this._resizeLoadingUI);
  35118. _this._loadingDiv = null;
  35119. };
  35120. this._loadingDiv.style.opacity = "0";
  35121. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  35122. };
  35123. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  35124. set: function (text) {
  35125. this._loadingText = text;
  35126. if (this._loadingTextDiv) {
  35127. this._loadingTextDiv.innerHTML = this._loadingText;
  35128. }
  35129. },
  35130. enumerable: true,
  35131. configurable: true
  35132. });
  35133. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  35134. get: function () {
  35135. return this._loadingDivBackgroundColor;
  35136. },
  35137. set: function (color) {
  35138. this._loadingDivBackgroundColor = color;
  35139. if (!this._loadingDiv) {
  35140. return;
  35141. }
  35142. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  35143. },
  35144. enumerable: true,
  35145. configurable: true
  35146. });
  35147. return DefaultLoadingScreen;
  35148. })();
  35149. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  35150. })(BABYLON || (BABYLON = {}));
  35151. var BABYLON;
  35152. (function (BABYLON) {
  35153. var AudioEngine = (function () {
  35154. function AudioEngine() {
  35155. this._audioContext = null;
  35156. this._audioContextInitialized = false;
  35157. this.canUseWebAudio = false;
  35158. this.WarnedWebAudioUnsupported = false;
  35159. this.unlocked = false;
  35160. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  35161. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  35162. this.canUseWebAudio = true;
  35163. }
  35164. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  35165. this._unlockiOSaudio();
  35166. }
  35167. else {
  35168. this.unlocked = true;
  35169. }
  35170. }
  35171. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  35172. get: function () {
  35173. if (!this._audioContextInitialized) {
  35174. this._initializeAudioContext();
  35175. }
  35176. return this._audioContext;
  35177. },
  35178. enumerable: true,
  35179. configurable: true
  35180. });
  35181. AudioEngine.prototype._unlockiOSaudio = function () {
  35182. var _this = this;
  35183. var unlockaudio = function () {
  35184. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  35185. var source = _this.audioContext.createBufferSource();
  35186. source.buffer = buffer;
  35187. source.connect(_this.audioContext.destination);
  35188. source.start(0);
  35189. setTimeout(function () {
  35190. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  35191. _this.unlocked = true;
  35192. window.removeEventListener('touchend', unlockaudio, false);
  35193. if (_this.onAudioUnlocked) {
  35194. _this.onAudioUnlocked();
  35195. }
  35196. }
  35197. }, 0);
  35198. };
  35199. window.addEventListener('touchend', unlockaudio, false);
  35200. };
  35201. AudioEngine.prototype._initializeAudioContext = function () {
  35202. try {
  35203. if (this.canUseWebAudio) {
  35204. this._audioContext = new AudioContext();
  35205. // create a global volume gain node
  35206. this.masterGain = this._audioContext.createGain();
  35207. this.masterGain.gain.value = 1;
  35208. this.masterGain.connect(this._audioContext.destination);
  35209. this._audioContextInitialized = true;
  35210. }
  35211. }
  35212. catch (e) {
  35213. this.canUseWebAudio = false;
  35214. BABYLON.Tools.Error("Web Audio: " + e.message);
  35215. }
  35216. };
  35217. AudioEngine.prototype.dispose = function () {
  35218. if (this.canUseWebAudio && this._audioContextInitialized) {
  35219. if (this._connectedAnalyser) {
  35220. this._connectedAnalyser.stopDebugCanvas();
  35221. this._connectedAnalyser.dispose();
  35222. this.masterGain.disconnect();
  35223. this.masterGain.connect(this._audioContext.destination);
  35224. this._connectedAnalyser = null;
  35225. }
  35226. this.masterGain.gain.value = 1;
  35227. }
  35228. this.WarnedWebAudioUnsupported = false;
  35229. };
  35230. AudioEngine.prototype.getGlobalVolume = function () {
  35231. if (this.canUseWebAudio && this._audioContextInitialized) {
  35232. return this.masterGain.gain.value;
  35233. }
  35234. else {
  35235. return -1;
  35236. }
  35237. };
  35238. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  35239. if (this.canUseWebAudio && this._audioContextInitialized) {
  35240. this.masterGain.gain.value = newVolume;
  35241. }
  35242. };
  35243. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  35244. if (this._connectedAnalyser) {
  35245. this._connectedAnalyser.stopDebugCanvas();
  35246. }
  35247. if (this.canUseWebAudio && this._audioContextInitialized) {
  35248. this._connectedAnalyser = analyser;
  35249. this.masterGain.disconnect();
  35250. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  35251. }
  35252. };
  35253. return AudioEngine;
  35254. })();
  35255. BABYLON.AudioEngine = AudioEngine;
  35256. })(BABYLON || (BABYLON = {}));
  35257. var BABYLON;
  35258. (function (BABYLON) {
  35259. var Sound = (function () {
  35260. /**
  35261. * Create a sound and attach it to a scene
  35262. * @param name Name of your sound
  35263. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  35264. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  35265. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  35266. */
  35267. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  35268. var _this = this;
  35269. this.autoplay = false;
  35270. this.loop = false;
  35271. this.useCustomAttenuation = false;
  35272. this.spatialSound = false;
  35273. this.refDistance = 1;
  35274. this.rolloffFactor = 1;
  35275. this.maxDistance = 100;
  35276. this.distanceModel = "linear";
  35277. this._panningModel = "equalpower";
  35278. this._playbackRate = 1;
  35279. this._streaming = false;
  35280. this._startTime = 0;
  35281. this._startOffset = 0;
  35282. this._position = BABYLON.Vector3.Zero();
  35283. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  35284. this._volume = 1;
  35285. this._isLoaded = false;
  35286. this._isReadyToPlay = false;
  35287. this.isPlaying = false;
  35288. this.isPaused = false;
  35289. this._isDirectional = false;
  35290. // Used if you'd like to create a directional sound.
  35291. // If not set, the sound will be omnidirectional
  35292. this._coneInnerAngle = 360;
  35293. this._coneOuterAngle = 360;
  35294. this._coneOuterGain = 0;
  35295. this._isOutputConnected = false;
  35296. this.name = name;
  35297. this._scene = scene;
  35298. this._readyToPlayCallback = readyToPlayCallback;
  35299. // Default custom attenuation function is a linear attenuation
  35300. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  35301. if (currentDistance < maxDistance) {
  35302. return currentVolume * (1 - currentDistance / maxDistance);
  35303. }
  35304. else {
  35305. return 0;
  35306. }
  35307. };
  35308. if (options) {
  35309. this.autoplay = options.autoplay || false;
  35310. this.loop = options.loop || false;
  35311. // if volume === 0, we need another way to check this option
  35312. if (options.volume !== undefined) {
  35313. this._volume = options.volume;
  35314. }
  35315. this.spatialSound = options.spatialSound || false;
  35316. this.maxDistance = options.maxDistance || 100;
  35317. this.useCustomAttenuation = options.useCustomAttenuation || false;
  35318. this.rolloffFactor = options.rolloffFactor || 1;
  35319. this.refDistance = options.refDistance || 1;
  35320. this.distanceModel = options.distanceModel || "linear";
  35321. this._playbackRate = options.playbackRate || 1;
  35322. this._streaming = options.streaming || false;
  35323. }
  35324. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35325. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  35326. this._soundGain.gain.value = this._volume;
  35327. this._inputAudioNode = this._soundGain;
  35328. this._ouputAudioNode = this._soundGain;
  35329. if (this.spatialSound) {
  35330. this._createSpatialParameters();
  35331. }
  35332. this._scene.mainSoundTrack.AddSound(this);
  35333. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  35334. if (urlOrArrayBuffer) {
  35335. // If it's an URL
  35336. if (typeof (urlOrArrayBuffer) === "string") {
  35337. // Loading sound using XHR2
  35338. if (!this._streaming) {
  35339. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  35340. }
  35341. else {
  35342. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  35343. this._htmlAudioElement.controls = false;
  35344. this._htmlAudioElement.loop = this.loop;
  35345. this._htmlAudioElement.crossOrigin = "anonymous";
  35346. this._htmlAudioElement.preload = "auto";
  35347. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  35348. _this._isReadyToPlay = true;
  35349. if (_this.autoplay) {
  35350. _this.play();
  35351. }
  35352. if (_this._readyToPlayCallback) {
  35353. _this._readyToPlayCallback();
  35354. }
  35355. });
  35356. document.body.appendChild(this._htmlAudioElement);
  35357. }
  35358. }
  35359. else {
  35360. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  35361. if (urlOrArrayBuffer.byteLength > 0) {
  35362. this._soundLoaded(urlOrArrayBuffer);
  35363. }
  35364. }
  35365. else {
  35366. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  35367. }
  35368. }
  35369. }
  35370. }
  35371. else {
  35372. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  35373. this._scene.mainSoundTrack.AddSound(this);
  35374. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  35375. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  35376. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  35377. }
  35378. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  35379. if (this._readyToPlayCallback) {
  35380. window.setTimeout(function () {
  35381. _this._readyToPlayCallback();
  35382. }, 1000);
  35383. }
  35384. }
  35385. }
  35386. Sound.prototype.dispose = function () {
  35387. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  35388. if (this.isPlaying) {
  35389. this.stop();
  35390. }
  35391. this._isReadyToPlay = false;
  35392. if (this.soundTrackId === -1) {
  35393. this._scene.mainSoundTrack.RemoveSound(this);
  35394. }
  35395. else {
  35396. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  35397. }
  35398. if (this._soundGain) {
  35399. this._soundGain.disconnect();
  35400. this._soundGain = null;
  35401. }
  35402. if (this._soundPanner) {
  35403. this._soundPanner.disconnect();
  35404. this._soundPanner = null;
  35405. }
  35406. if (this._soundSource) {
  35407. this._soundSource.disconnect();
  35408. this._soundSource = null;
  35409. }
  35410. this._audioBuffer = null;
  35411. if (this._htmlAudioElement) {
  35412. this._htmlAudioElement.pause();
  35413. this._htmlAudioElement.src = "";
  35414. document.body.removeChild(this._htmlAudioElement);
  35415. }
  35416. if (this._connectedMesh) {
  35417. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35418. this._connectedMesh = null;
  35419. }
  35420. }
  35421. };
  35422. Sound.prototype._soundLoaded = function (audioData) {
  35423. var _this = this;
  35424. this._isLoaded = true;
  35425. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  35426. _this._audioBuffer = buffer;
  35427. _this._isReadyToPlay = true;
  35428. if (_this.autoplay) {
  35429. _this.play();
  35430. }
  35431. if (_this._readyToPlayCallback) {
  35432. _this._readyToPlayCallback();
  35433. }
  35434. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  35435. };
  35436. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  35437. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35438. this._audioBuffer = audioBuffer;
  35439. this._isReadyToPlay = true;
  35440. }
  35441. };
  35442. Sound.prototype.updateOptions = function (options) {
  35443. if (options) {
  35444. this.loop = options.loop || this.loop;
  35445. this.maxDistance = options.maxDistance || this.maxDistance;
  35446. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  35447. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  35448. this.refDistance = options.refDistance || this.refDistance;
  35449. this.distanceModel = options.distanceModel || this.distanceModel;
  35450. this._playbackRate = options.playbackRate || this._playbackRate;
  35451. this._updateSpatialParameters();
  35452. if (this.isPlaying) {
  35453. if (this._streaming) {
  35454. this._htmlAudioElement.playbackRate = this._playbackRate;
  35455. }
  35456. else {
  35457. this._soundSource.playbackRate.value = this._playbackRate;
  35458. }
  35459. }
  35460. }
  35461. };
  35462. Sound.prototype._createSpatialParameters = function () {
  35463. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35464. if (this._scene.headphone) {
  35465. this._panningModel = "HRTF";
  35466. }
  35467. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  35468. this._updateSpatialParameters();
  35469. this._soundPanner.connect(this._ouputAudioNode);
  35470. this._inputAudioNode = this._soundPanner;
  35471. }
  35472. };
  35473. Sound.prototype._updateSpatialParameters = function () {
  35474. if (this.spatialSound) {
  35475. if (this.useCustomAttenuation) {
  35476. // Tricks to disable in a way embedded Web Audio attenuation
  35477. this._soundPanner.distanceModel = "linear";
  35478. this._soundPanner.maxDistance = Number.MAX_VALUE;
  35479. this._soundPanner.refDistance = 1;
  35480. this._soundPanner.rolloffFactor = 1;
  35481. this._soundPanner.panningModel = this._panningModel;
  35482. }
  35483. else {
  35484. this._soundPanner.distanceModel = this.distanceModel;
  35485. this._soundPanner.maxDistance = this.maxDistance;
  35486. this._soundPanner.refDistance = this.refDistance;
  35487. this._soundPanner.rolloffFactor = this.rolloffFactor;
  35488. this._soundPanner.panningModel = this._panningModel;
  35489. }
  35490. }
  35491. };
  35492. Sound.prototype.switchPanningModelToHRTF = function () {
  35493. this._panningModel = "HRTF";
  35494. this._switchPanningModel();
  35495. };
  35496. Sound.prototype.switchPanningModelToEqualPower = function () {
  35497. this._panningModel = "equalpower";
  35498. this._switchPanningModel();
  35499. };
  35500. Sound.prototype._switchPanningModel = function () {
  35501. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  35502. this._soundPanner.panningModel = this._panningModel;
  35503. }
  35504. };
  35505. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  35506. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35507. if (this._isOutputConnected) {
  35508. this._ouputAudioNode.disconnect();
  35509. }
  35510. this._ouputAudioNode.connect(soundTrackAudioNode);
  35511. this._isOutputConnected = true;
  35512. }
  35513. };
  35514. /**
  35515. * Transform this sound into a directional source
  35516. * @param coneInnerAngle Size of the inner cone in degree
  35517. * @param coneOuterAngle Size of the outer cone in degree
  35518. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  35519. */
  35520. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  35521. if (coneOuterAngle < coneInnerAngle) {
  35522. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  35523. return;
  35524. }
  35525. this._coneInnerAngle = coneInnerAngle;
  35526. this._coneOuterAngle = coneOuterAngle;
  35527. this._coneOuterGain = coneOuterGain;
  35528. this._isDirectional = true;
  35529. if (this.isPlaying && this.loop) {
  35530. this.stop();
  35531. this.play();
  35532. }
  35533. };
  35534. Sound.prototype.setPosition = function (newPosition) {
  35535. this._position = newPosition;
  35536. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  35537. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35538. }
  35539. };
  35540. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  35541. this._localDirection = newLocalDirection;
  35542. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  35543. this._updateDirection();
  35544. }
  35545. };
  35546. Sound.prototype._updateDirection = function () {
  35547. var mat = this._connectedMesh.getWorldMatrix();
  35548. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  35549. direction.normalize();
  35550. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  35551. };
  35552. Sound.prototype.updateDistanceFromListener = function () {
  35553. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  35554. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  35555. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  35556. }
  35557. };
  35558. Sound.prototype.setAttenuationFunction = function (callback) {
  35559. this._customAttenuationFunction = callback;
  35560. };
  35561. /**
  35562. * Play the sound
  35563. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  35564. * @param offset (optional) Start the sound setting it at a specific time
  35565. */
  35566. Sound.prototype.play = function (time, offset) {
  35567. var _this = this;
  35568. if (this._isReadyToPlay && this._scene.audioEnabled) {
  35569. try {
  35570. if (this._startOffset < 0) {
  35571. time = -this._startOffset;
  35572. this._startOffset = 0;
  35573. }
  35574. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35575. if (!this._soundSource || !this._streamingSource) {
  35576. if (this.spatialSound) {
  35577. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35578. if (this._isDirectional) {
  35579. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  35580. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  35581. this._soundPanner.coneOuterGain = this._coneOuterGain;
  35582. if (this._connectedMesh) {
  35583. this._updateDirection();
  35584. }
  35585. else {
  35586. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  35587. }
  35588. }
  35589. }
  35590. }
  35591. if (this._streaming) {
  35592. if (!this._streamingSource) {
  35593. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  35594. this._htmlAudioElement.onended = function () { _this._onended(); };
  35595. this._htmlAudioElement.playbackRate = this._playbackRate;
  35596. }
  35597. this._streamingSource.disconnect();
  35598. this._streamingSource.connect(this._inputAudioNode);
  35599. this._htmlAudioElement.play();
  35600. }
  35601. else {
  35602. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  35603. this._soundSource.buffer = this._audioBuffer;
  35604. this._soundSource.connect(this._inputAudioNode);
  35605. this._soundSource.loop = this.loop;
  35606. this._soundSource.playbackRate.value = this._playbackRate;
  35607. this._soundSource.onended = function () { _this._onended(); };
  35608. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  35609. }
  35610. this._startTime = startTime;
  35611. this.isPlaying = true;
  35612. this.isPaused = false;
  35613. }
  35614. catch (ex) {
  35615. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  35616. }
  35617. }
  35618. };
  35619. Sound.prototype._onended = function () {
  35620. this.isPlaying = false;
  35621. if (this.onended) {
  35622. this.onended();
  35623. }
  35624. };
  35625. /**
  35626. * Stop the sound
  35627. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  35628. */
  35629. Sound.prototype.stop = function (time) {
  35630. if (this.isPlaying) {
  35631. if (this._streaming) {
  35632. this._htmlAudioElement.pause();
  35633. // Test needed for Firefox or it will generate an Invalid State Error
  35634. if (this._htmlAudioElement.currentTime > 0) {
  35635. this._htmlAudioElement.currentTime = 0;
  35636. }
  35637. }
  35638. else {
  35639. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35640. this._soundSource.stop(stopTime);
  35641. this._soundSource.onended = null;
  35642. if (!this.isPaused) {
  35643. this._startOffset = 0;
  35644. }
  35645. }
  35646. this.isPlaying = false;
  35647. }
  35648. };
  35649. Sound.prototype.pause = function () {
  35650. if (this.isPlaying) {
  35651. this.isPaused = true;
  35652. if (this._streaming) {
  35653. this._htmlAudioElement.pause();
  35654. }
  35655. else {
  35656. this.stop(0);
  35657. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  35658. }
  35659. }
  35660. };
  35661. Sound.prototype.setVolume = function (newVolume, time) {
  35662. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35663. if (time) {
  35664. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  35665. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  35666. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  35667. }
  35668. else {
  35669. this._soundGain.gain.value = newVolume;
  35670. }
  35671. }
  35672. this._volume = newVolume;
  35673. };
  35674. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  35675. this._playbackRate = newPlaybackRate;
  35676. if (this.isPlaying) {
  35677. if (this._streaming) {
  35678. this._htmlAudioElement.playbackRate = this._playbackRate;
  35679. }
  35680. else {
  35681. this._soundSource.playbackRate.value = this._playbackRate;
  35682. }
  35683. }
  35684. };
  35685. Sound.prototype.getVolume = function () {
  35686. return this._volume;
  35687. };
  35688. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  35689. var _this = this;
  35690. if (this._connectedMesh) {
  35691. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35692. this._registerFunc = null;
  35693. }
  35694. this._connectedMesh = meshToConnectTo;
  35695. if (!this.spatialSound) {
  35696. this.spatialSound = true;
  35697. this._createSpatialParameters();
  35698. if (this.isPlaying && this.loop) {
  35699. this.stop();
  35700. this.play();
  35701. }
  35702. }
  35703. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  35704. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  35705. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  35706. };
  35707. Sound.prototype.detachFromMesh = function () {
  35708. if (this._connectedMesh) {
  35709. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35710. this._registerFunc = null;
  35711. this._connectedMesh = null;
  35712. }
  35713. };
  35714. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  35715. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  35716. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  35717. this._updateDirection();
  35718. }
  35719. };
  35720. Sound.prototype.clone = function () {
  35721. var _this = this;
  35722. if (!this._streaming) {
  35723. var setBufferAndRun = function () {
  35724. if (_this._isReadyToPlay) {
  35725. clonedSound._audioBuffer = _this.getAudioBuffer();
  35726. clonedSound._isReadyToPlay = true;
  35727. if (clonedSound.autoplay) {
  35728. clonedSound.play();
  35729. }
  35730. }
  35731. else {
  35732. window.setTimeout(setBufferAndRun, 300);
  35733. }
  35734. };
  35735. var currentOptions = {
  35736. autoplay: this.autoplay, loop: this.loop,
  35737. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  35738. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  35739. refDistance: this.refDistance, distanceModel: this.distanceModel
  35740. };
  35741. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  35742. if (this.useCustomAttenuation) {
  35743. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  35744. }
  35745. clonedSound.setPosition(this._position);
  35746. clonedSound.setPlaybackRate(this._playbackRate);
  35747. setBufferAndRun();
  35748. return clonedSound;
  35749. }
  35750. else {
  35751. return null;
  35752. }
  35753. };
  35754. Sound.prototype.getAudioBuffer = function () {
  35755. return this._audioBuffer;
  35756. };
  35757. Sound.prototype.serialize = function () {
  35758. var serializationObject = {
  35759. name: this.name,
  35760. url: this.name,
  35761. autoplay: this.autoplay,
  35762. loop: this.loop,
  35763. volume: this._volume,
  35764. spatialSound: this.spatialSound,
  35765. maxDistance: this.maxDistance,
  35766. rolloffFactor: this.rolloffFactor,
  35767. refDistance: this.refDistance,
  35768. distanceModel: this.distanceModel,
  35769. playbackRate: this._playbackRate,
  35770. panningModel: this._panningModel,
  35771. soundTrackId: this.soundTrackId
  35772. };
  35773. if (this.spatialSound) {
  35774. if (this._connectedMesh)
  35775. serializationObject.connectedMeshId = this._connectedMesh.id;
  35776. serializationObject.position = this._position.asArray();
  35777. serializationObject.refDistance = this.refDistance;
  35778. serializationObject.distanceModel = this.distanceModel;
  35779. serializationObject.isDirectional = this._isDirectional;
  35780. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  35781. serializationObject.coneInnerAngle = this._coneInnerAngle;
  35782. serializationObject.coneOuterAngle = this._coneOuterAngle;
  35783. serializationObject.coneOuterGain = this._coneOuterGain;
  35784. }
  35785. return serializationObject;
  35786. };
  35787. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  35788. var soundName = parsedSound.name;
  35789. var soundUrl;
  35790. if (parsedSound.url) {
  35791. soundUrl = rootUrl + parsedSound.url;
  35792. }
  35793. else {
  35794. soundUrl = rootUrl + soundName;
  35795. }
  35796. var options = {
  35797. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  35798. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  35799. rolloffFactor: parsedSound.rolloffFactor,
  35800. refDistance: parsedSound.refDistance,
  35801. distanceModel: parsedSound.distanceModel,
  35802. playbackRate: parsedSound.playbackRate
  35803. };
  35804. var newSound;
  35805. if (!sourceSound) {
  35806. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  35807. scene._addPendingData(newSound);
  35808. }
  35809. else {
  35810. var setBufferAndRun = function () {
  35811. if (sourceSound._isReadyToPlay) {
  35812. newSound._audioBuffer = sourceSound.getAudioBuffer();
  35813. newSound._isReadyToPlay = true;
  35814. if (newSound.autoplay) {
  35815. newSound.play();
  35816. }
  35817. }
  35818. else {
  35819. window.setTimeout(setBufferAndRun, 300);
  35820. }
  35821. };
  35822. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  35823. setBufferAndRun();
  35824. }
  35825. if (parsedSound.position) {
  35826. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  35827. newSound.setPosition(soundPosition);
  35828. }
  35829. if (parsedSound.isDirectional) {
  35830. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  35831. if (parsedSound.localDirectionToMesh) {
  35832. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  35833. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  35834. }
  35835. }
  35836. if (parsedSound.connectedMeshId) {
  35837. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  35838. if (connectedMesh) {
  35839. newSound.attachToMesh(connectedMesh);
  35840. }
  35841. }
  35842. return newSound;
  35843. };
  35844. return Sound;
  35845. })();
  35846. BABYLON.Sound = Sound;
  35847. })(BABYLON || (BABYLON = {}));
  35848. var BABYLON;
  35849. (function (BABYLON) {
  35850. var SoundTrack = (function () {
  35851. function SoundTrack(scene, options) {
  35852. this.id = -1;
  35853. this._isMainTrack = false;
  35854. this._isInitialized = false;
  35855. this._scene = scene;
  35856. this.soundCollection = new Array();
  35857. this._options = options;
  35858. if (!this._isMainTrack) {
  35859. this._scene.soundTracks.push(this);
  35860. this.id = this._scene.soundTracks.length - 1;
  35861. }
  35862. }
  35863. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  35864. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35865. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  35866. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  35867. if (this._options) {
  35868. if (this._options.volume) {
  35869. this._outputAudioNode.gain.value = this._options.volume;
  35870. }
  35871. if (this._options.mainTrack) {
  35872. this._isMainTrack = this._options.mainTrack;
  35873. }
  35874. }
  35875. this._isInitialized = true;
  35876. }
  35877. };
  35878. SoundTrack.prototype.dispose = function () {
  35879. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35880. if (this._connectedAnalyser) {
  35881. this._connectedAnalyser.stopDebugCanvas();
  35882. }
  35883. while (this.soundCollection.length) {
  35884. this.soundCollection[0].dispose();
  35885. }
  35886. if (this._outputAudioNode) {
  35887. this._outputAudioNode.disconnect();
  35888. }
  35889. this._outputAudioNode = null;
  35890. }
  35891. };
  35892. SoundTrack.prototype.AddSound = function (sound) {
  35893. if (!this._isInitialized) {
  35894. this._initializeSoundTrackAudioGraph();
  35895. }
  35896. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35897. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  35898. }
  35899. if (sound.soundTrackId) {
  35900. if (sound.soundTrackId === -1) {
  35901. this._scene.mainSoundTrack.RemoveSound(sound);
  35902. }
  35903. else {
  35904. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  35905. }
  35906. }
  35907. this.soundCollection.push(sound);
  35908. sound.soundTrackId = this.id;
  35909. };
  35910. SoundTrack.prototype.RemoveSound = function (sound) {
  35911. var index = this.soundCollection.indexOf(sound);
  35912. if (index !== -1) {
  35913. this.soundCollection.splice(index, 1);
  35914. }
  35915. };
  35916. SoundTrack.prototype.setVolume = function (newVolume) {
  35917. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35918. this._outputAudioNode.gain.value = newVolume;
  35919. }
  35920. };
  35921. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  35922. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35923. for (var i = 0; i < this.soundCollection.length; i++) {
  35924. this.soundCollection[i].switchPanningModelToHRTF();
  35925. }
  35926. }
  35927. };
  35928. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  35929. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35930. for (var i = 0; i < this.soundCollection.length; i++) {
  35931. this.soundCollection[i].switchPanningModelToEqualPower();
  35932. }
  35933. }
  35934. };
  35935. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  35936. if (this._connectedAnalyser) {
  35937. this._connectedAnalyser.stopDebugCanvas();
  35938. }
  35939. this._connectedAnalyser = analyser;
  35940. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35941. this._outputAudioNode.disconnect();
  35942. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  35943. }
  35944. };
  35945. return SoundTrack;
  35946. })();
  35947. BABYLON.SoundTrack = SoundTrack;
  35948. })(BABYLON || (BABYLON = {}));
  35949. var BABYLON;
  35950. (function (BABYLON) {
  35951. var DebugLayer = (function () {
  35952. function DebugLayer(scene) {
  35953. var _this = this;
  35954. this._transformationMatrix = BABYLON.Matrix.Identity();
  35955. this._enabled = false;
  35956. this._labelsEnabled = false;
  35957. this._displayStatistics = true;
  35958. this._displayTree = false;
  35959. this._displayLogs = false;
  35960. this._skeletonViewers = new Array();
  35961. this._identityMatrix = BABYLON.Matrix.Identity();
  35962. this.axisRatio = 0.02;
  35963. this.accentColor = "orange";
  35964. this._scene = scene;
  35965. this._syncPositions = function () {
  35966. var engine = _this._scene.getEngine();
  35967. var canvasRect = engine.getRenderingCanvasClientRect();
  35968. if (_this._showUI) {
  35969. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  35970. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  35971. _this._statsDiv.style.width = "400px";
  35972. _this._statsDiv.style.height = "auto";
  35973. _this._statsSubsetDiv.style.maxHeight = "240px";
  35974. _this._optionsDiv.style.left = "0px";
  35975. _this._optionsDiv.style.top = "10px";
  35976. _this._optionsDiv.style.width = "200px";
  35977. _this._optionsDiv.style.height = "auto";
  35978. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  35979. _this._logDiv.style.left = "0px";
  35980. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  35981. _this._logDiv.style.width = "600px";
  35982. _this._logDiv.style.height = "160px";
  35983. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  35984. _this._treeDiv.style.top = "10px";
  35985. _this._treeDiv.style.width = "300px";
  35986. _this._treeDiv.style.height = "auto";
  35987. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  35988. }
  35989. _this._globalDiv.style.left = canvasRect.left + "px";
  35990. _this._globalDiv.style.top = canvasRect.top + "px";
  35991. _this._drawingCanvas.style.left = "0px";
  35992. _this._drawingCanvas.style.top = "0px";
  35993. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  35994. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  35995. var devicePixelRatio = window.devicePixelRatio || 1;
  35996. var context = _this._drawingContext;
  35997. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  35998. context.mozBackingStorePixelRatio ||
  35999. context.msBackingStorePixelRatio ||
  36000. context.oBackingStorePixelRatio ||
  36001. context.backingStorePixelRatio || 1;
  36002. _this._ratio = devicePixelRatio / backingStoreRatio;
  36003. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  36004. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  36005. };
  36006. this._onCanvasClick = function (evt) {
  36007. _this._clickPosition = {
  36008. x: evt.clientX * _this._ratio,
  36009. y: evt.clientY * _this._ratio
  36010. };
  36011. };
  36012. this._syncUI = function () {
  36013. if (_this._showUI) {
  36014. if (_this._displayStatistics) {
  36015. _this._displayStats();
  36016. _this._statsDiv.style.display = "";
  36017. }
  36018. else {
  36019. _this._statsDiv.style.display = "none";
  36020. }
  36021. if (_this._displayLogs) {
  36022. _this._logDiv.style.display = "";
  36023. }
  36024. else {
  36025. _this._logDiv.style.display = "none";
  36026. }
  36027. if (_this._displayTree) {
  36028. _this._treeDiv.style.display = "";
  36029. if (_this._needToRefreshMeshesTree) {
  36030. _this._needToRefreshMeshesTree = false;
  36031. _this._refreshMeshesTreeContent();
  36032. }
  36033. }
  36034. else {
  36035. _this._treeDiv.style.display = "none";
  36036. }
  36037. }
  36038. };
  36039. this._syncData = function () {
  36040. if (_this._labelsEnabled || !_this._showUI) {
  36041. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  36042. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  36043. var engine = _this._scene.getEngine();
  36044. var viewport = _this._camera.viewport;
  36045. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  36046. // Meshes
  36047. var meshes = _this._camera.getActiveMeshes();
  36048. var index;
  36049. var projectedPosition;
  36050. for (index = 0; index < meshes.length; index++) {
  36051. var mesh = meshes.data[index];
  36052. var position = mesh.getBoundingInfo().boundingSphere.center;
  36053. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  36054. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  36055. _this._renderAxis(projectedPosition, mesh, globalViewport);
  36056. }
  36057. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  36058. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  36059. }
  36060. }
  36061. // Cameras
  36062. var cameras = _this._scene.cameras;
  36063. for (index = 0; index < cameras.length; index++) {
  36064. var camera = cameras[index];
  36065. if (camera === _this._camera) {
  36066. continue;
  36067. }
  36068. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  36069. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  36070. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  36071. _this._camera.detachControl(engine.getRenderingCanvas());
  36072. _this._camera = camera;
  36073. _this._camera.attachControl(engine.getRenderingCanvas());
  36074. }, function () { return "purple"; });
  36075. }
  36076. }
  36077. // Lights
  36078. var lights = _this._scene.lights;
  36079. for (index = 0; index < lights.length; index++) {
  36080. var light = lights[index];
  36081. if (light.position) {
  36082. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  36083. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  36084. _this._renderLabel(light.name, projectedPosition, -20, function () {
  36085. light.setEnabled(!light.isEnabled());
  36086. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  36087. }
  36088. }
  36089. }
  36090. }
  36091. _this._clickPosition = undefined;
  36092. };
  36093. }
  36094. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  36095. while (this._treeSubsetDiv.hasChildNodes()) {
  36096. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  36097. }
  36098. // Add meshes
  36099. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  36100. sortedArray.sort(function (a, b) {
  36101. if (a.name === b.name) {
  36102. return 0;
  36103. }
  36104. return (a.name > b.name) ? 1 : -1;
  36105. });
  36106. for (var index = 0; index < sortedArray.length; index++) {
  36107. var mesh = sortedArray[index];
  36108. if (!mesh.isEnabled()) {
  36109. continue;
  36110. }
  36111. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  36112. m.isVisible = element.checked;
  36113. }, mesh);
  36114. }
  36115. };
  36116. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  36117. this._drawingContext.beginPath();
  36118. this._drawingContext.moveTo(zero.x, zero.y);
  36119. this._drawingContext.lineTo(unit.x, unit.y);
  36120. this._drawingContext.strokeStyle = color;
  36121. this._drawingContext.lineWidth = 4;
  36122. this._drawingContext.stroke();
  36123. this._drawingContext.font = "normal 14px Segoe UI";
  36124. this._drawingContext.fillStyle = color;
  36125. this._drawingContext.fillText(label, unitText.x, unitText.y);
  36126. };
  36127. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  36128. var position = mesh.getBoundingInfo().boundingSphere.center;
  36129. var worldMatrix = mesh.getWorldMatrix();
  36130. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  36131. var unit = (unprojectedVector.subtract(position)).length();
  36132. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36133. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36134. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  36135. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36136. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36137. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  36138. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  36139. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  36140. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  36141. };
  36142. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  36143. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  36144. this._drawingContext.font = "normal 12px Segoe UI";
  36145. var textMetrics = this._drawingContext.measureText(text);
  36146. var centerX = projectedPosition.x - textMetrics.width / 2;
  36147. var centerY = projectedPosition.y;
  36148. var clientRect = this._drawingCanvas.getBoundingClientRect();
  36149. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  36150. onClick();
  36151. }
  36152. this._drawingContext.beginPath();
  36153. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  36154. this._drawingContext.fillStyle = getFillStyle();
  36155. this._drawingContext.globalAlpha = 0.5;
  36156. this._drawingContext.fill();
  36157. this._drawingContext.globalAlpha = 1.0;
  36158. this._drawingContext.strokeStyle = '#FFFFFF';
  36159. this._drawingContext.lineWidth = 1;
  36160. this._drawingContext.stroke();
  36161. this._drawingContext.fillStyle = "#FFFFFF";
  36162. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  36163. this._drawingContext.beginPath();
  36164. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  36165. this._drawingContext.fill();
  36166. }
  36167. };
  36168. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  36169. if (!this._clickPosition) {
  36170. return false;
  36171. }
  36172. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  36173. return false;
  36174. }
  36175. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  36176. return false;
  36177. }
  36178. return true;
  36179. };
  36180. DebugLayer.prototype.isVisible = function () {
  36181. return this._enabled;
  36182. };
  36183. DebugLayer.prototype.hide = function () {
  36184. if (!this._enabled) {
  36185. return;
  36186. }
  36187. this._enabled = false;
  36188. var engine = this._scene.getEngine();
  36189. this._scene.unregisterBeforeRender(this._syncData);
  36190. this._scene.unregisterAfterRender(this._syncUI);
  36191. this._rootElement.removeChild(this._globalDiv);
  36192. this._scene.forceShowBoundingBoxes = false;
  36193. this._scene.forceWireframe = false;
  36194. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  36195. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  36196. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  36197. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  36198. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  36199. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  36200. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  36201. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  36202. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  36203. BABYLON.StandardMaterial.ColorGradingTextureEnabled = true;
  36204. this._scene.shadowsEnabled = true;
  36205. this._scene.particlesEnabled = true;
  36206. this._scene.postProcessesEnabled = true;
  36207. this._scene.collisionsEnabled = true;
  36208. this._scene.lightsEnabled = true;
  36209. this._scene.texturesEnabled = true;
  36210. this._scene.lensFlaresEnabled = true;
  36211. this._scene.proceduralTexturesEnabled = true;
  36212. this._scene.renderTargetsEnabled = true;
  36213. this._scene.probesEnabled = true;
  36214. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  36215. this._clearSkeletonViewers();
  36216. };
  36217. DebugLayer.prototype._clearSkeletonViewers = function () {
  36218. for (var index = 0; index < this._skeletonViewers.length; index++) {
  36219. this._skeletonViewers[index].dispose();
  36220. }
  36221. this._skeletonViewers = [];
  36222. };
  36223. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  36224. if (showUI === void 0) { showUI = true; }
  36225. if (camera === void 0) { camera = null; }
  36226. if (rootElement === void 0) { rootElement = null; }
  36227. if (this._enabled) {
  36228. return;
  36229. }
  36230. this._enabled = true;
  36231. if (camera) {
  36232. this._camera = camera;
  36233. }
  36234. else {
  36235. this._camera = this._scene.activeCamera;
  36236. }
  36237. this._showUI = showUI;
  36238. var engine = this._scene.getEngine();
  36239. this._globalDiv = document.createElement("div");
  36240. this._rootElement = rootElement || document.body;
  36241. this._rootElement.appendChild(this._globalDiv);
  36242. this._generateDOMelements();
  36243. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  36244. this._syncPositions();
  36245. this._scene.registerBeforeRender(this._syncData);
  36246. this._scene.registerAfterRender(this._syncUI);
  36247. };
  36248. DebugLayer.prototype._clearLabels = function () {
  36249. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  36250. for (var index = 0; index < this._scene.meshes.length; index++) {
  36251. var mesh = this._scene.meshes[index];
  36252. mesh.renderOverlay = false;
  36253. }
  36254. };
  36255. DebugLayer.prototype._generateheader = function (root, text) {
  36256. var header = document.createElement("div");
  36257. header.innerHTML = text + "&nbsp;";
  36258. header.style.textAlign = "right";
  36259. header.style.width = "100%";
  36260. header.style.color = "white";
  36261. header.style.backgroundColor = "Black";
  36262. header.style.padding = "5px 5px 4px 0px";
  36263. header.style.marginLeft = "-5px";
  36264. header.style.fontWeight = "bold";
  36265. root.appendChild(header);
  36266. };
  36267. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  36268. var label = document.createElement("label");
  36269. label.style.display = "inline";
  36270. label.innerHTML = title;
  36271. label.style.color = color;
  36272. root.appendChild(label);
  36273. root.appendChild(document.createElement("br"));
  36274. };
  36275. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  36276. if (tag === void 0) { tag = null; }
  36277. var label = document.createElement("label");
  36278. label.style.display = "inline";
  36279. var boundingBoxesCheckbox = document.createElement("input");
  36280. boundingBoxesCheckbox.type = "checkbox";
  36281. boundingBoxesCheckbox.checked = initialState;
  36282. boundingBoxesCheckbox.style.display = "inline";
  36283. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  36284. boundingBoxesCheckbox.style.verticalAlign = "sub";
  36285. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  36286. task(evt.target, tag);
  36287. });
  36288. label.appendChild(boundingBoxesCheckbox);
  36289. var container = document.createElement("span");
  36290. var leftPart = document.createElement("span");
  36291. var rightPart = document.createElement("span");
  36292. rightPart.style.cssFloat = "right";
  36293. leftPart.innerHTML = leftTitle;
  36294. rightPart.innerHTML = rightTitle;
  36295. rightPart.style.fontSize = "12px";
  36296. rightPart.style.maxWidth = "200px";
  36297. container.appendChild(leftPart);
  36298. container.appendChild(rightPart);
  36299. label.appendChild(container);
  36300. root.appendChild(label);
  36301. root.appendChild(document.createElement("br"));
  36302. };
  36303. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  36304. if (tag === void 0) { tag = null; }
  36305. var label = document.createElement("label");
  36306. label.style.display = "inline";
  36307. var checkBox = document.createElement("input");
  36308. checkBox.type = "checkbox";
  36309. checkBox.checked = initialState;
  36310. checkBox.style.display = "inline";
  36311. checkBox.style.margin = "0px 5px 0px 0px";
  36312. checkBox.style.verticalAlign = "sub";
  36313. checkBox.addEventListener("change", function (evt) {
  36314. task(evt.target, tag);
  36315. });
  36316. label.appendChild(checkBox);
  36317. label.appendChild(document.createTextNode(title));
  36318. root.appendChild(label);
  36319. root.appendChild(document.createElement("br"));
  36320. };
  36321. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  36322. if (tag === void 0) { tag = null; }
  36323. var button = document.createElement("button");
  36324. button.innerHTML = title;
  36325. button.style.height = "24px";
  36326. button.style.width = "150px";
  36327. button.style.marginBottom = "5px";
  36328. button.style.color = "#444444";
  36329. button.style.border = "1px solid white";
  36330. button.className = "debugLayerButton";
  36331. button.addEventListener("click", function (evt) {
  36332. task(evt.target, tag);
  36333. });
  36334. root.appendChild(button);
  36335. root.appendChild(document.createElement("br"));
  36336. };
  36337. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  36338. if (tag === void 0) { tag = null; }
  36339. var label = document.createElement("label");
  36340. label.style.display = "inline";
  36341. var boundingBoxesRadio = document.createElement("input");
  36342. boundingBoxesRadio.type = "radio";
  36343. boundingBoxesRadio.name = name;
  36344. boundingBoxesRadio.checked = initialState;
  36345. boundingBoxesRadio.style.display = "inline";
  36346. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  36347. boundingBoxesRadio.style.verticalAlign = "sub";
  36348. boundingBoxesRadio.addEventListener("change", function (evt) {
  36349. task(evt.target, tag);
  36350. });
  36351. label.appendChild(boundingBoxesRadio);
  36352. label.appendChild(document.createTextNode(title));
  36353. root.appendChild(label);
  36354. root.appendChild(document.createElement("br"));
  36355. };
  36356. DebugLayer.prototype._generateDOMelements = function () {
  36357. var _this = this;
  36358. this._globalDiv.id = "DebugLayer";
  36359. this._globalDiv.style.position = "absolute";
  36360. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  36361. this._globalDiv.style.fontSize = "14px";
  36362. this._globalDiv.style.color = "white";
  36363. // Drawing canvas
  36364. this._drawingCanvas = document.createElement("canvas");
  36365. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  36366. this._drawingCanvas.style.position = "absolute";
  36367. this._drawingCanvas.style.pointerEvents = "none";
  36368. this._drawingCanvas.style.backgroundColor = "transparent";
  36369. this._drawingContext = this._drawingCanvas.getContext("2d");
  36370. this._globalDiv.appendChild(this._drawingCanvas);
  36371. if (this._showUI) {
  36372. var background = "rgba(128, 128, 128, 0.4)";
  36373. var border = "rgb(180, 180, 180) solid 1px";
  36374. // Stats
  36375. this._statsDiv = document.createElement("div");
  36376. this._statsDiv.id = "DebugLayerStats";
  36377. this._statsDiv.style.border = border;
  36378. this._statsDiv.style.position = "absolute";
  36379. this._statsDiv.style.background = background;
  36380. this._statsDiv.style.padding = "0px 0px 0px 5px";
  36381. this._generateheader(this._statsDiv, "STATISTICS");
  36382. this._statsSubsetDiv = document.createElement("div");
  36383. this._statsSubsetDiv.style.paddingTop = "5px";
  36384. this._statsSubsetDiv.style.paddingBottom = "5px";
  36385. this._statsSubsetDiv.style.overflowY = "auto";
  36386. this._statsDiv.appendChild(this._statsSubsetDiv);
  36387. // Tree
  36388. this._treeDiv = document.createElement("div");
  36389. this._treeDiv.id = "DebugLayerTree";
  36390. this._treeDiv.style.border = border;
  36391. this._treeDiv.style.position = "absolute";
  36392. this._treeDiv.style.background = background;
  36393. this._treeDiv.style.padding = "0px 0px 0px 5px";
  36394. this._treeDiv.style.display = "none";
  36395. this._generateheader(this._treeDiv, "MESHES TREE");
  36396. this._treeSubsetDiv = document.createElement("div");
  36397. this._treeSubsetDiv.style.paddingTop = "5px";
  36398. this._treeSubsetDiv.style.paddingRight = "5px";
  36399. this._treeSubsetDiv.style.overflowY = "auto";
  36400. this._treeSubsetDiv.style.maxHeight = "300px";
  36401. this._treeDiv.appendChild(this._treeSubsetDiv);
  36402. this._needToRefreshMeshesTree = true;
  36403. // Logs
  36404. this._logDiv = document.createElement("div");
  36405. this._logDiv.style.border = border;
  36406. this._logDiv.id = "DebugLayerLogs";
  36407. this._logDiv.style.position = "absolute";
  36408. this._logDiv.style.background = background;
  36409. this._logDiv.style.padding = "0px 0px 0px 5px";
  36410. this._logDiv.style.display = "none";
  36411. this._generateheader(this._logDiv, "LOGS");
  36412. this._logSubsetDiv = document.createElement("div");
  36413. this._logSubsetDiv.style.height = "127px";
  36414. this._logSubsetDiv.style.paddingTop = "5px";
  36415. this._logSubsetDiv.style.overflowY = "auto";
  36416. this._logSubsetDiv.style.fontSize = "12px";
  36417. this._logSubsetDiv.style.fontFamily = "consolas";
  36418. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  36419. this._logDiv.appendChild(this._logSubsetDiv);
  36420. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  36421. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  36422. };
  36423. // Options
  36424. this._optionsDiv = document.createElement("div");
  36425. this._optionsDiv.id = "DebugLayerOptions";
  36426. this._optionsDiv.style.border = border;
  36427. this._optionsDiv.style.position = "absolute";
  36428. this._optionsDiv.style.background = background;
  36429. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  36430. this._optionsDiv.style.overflowY = "auto";
  36431. this._generateheader(this._optionsDiv, "OPTIONS");
  36432. this._optionsSubsetDiv = document.createElement("div");
  36433. this._optionsSubsetDiv.style.paddingTop = "5px";
  36434. this._optionsSubsetDiv.style.paddingBottom = "5px";
  36435. this._optionsSubsetDiv.style.overflowY = "auto";
  36436. this._optionsSubsetDiv.style.maxHeight = "200px";
  36437. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  36438. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  36439. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  36440. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  36441. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  36442. _this._displayTree = element.checked;
  36443. _this._needToRefreshMeshesTree = true;
  36444. });
  36445. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36446. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  36447. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  36448. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  36449. _this._labelsEnabled = element.checked;
  36450. if (!_this._labelsEnabled) {
  36451. _this._clearLabels();
  36452. }
  36453. });
  36454. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  36455. if (element.checked) {
  36456. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  36457. }
  36458. else {
  36459. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  36460. }
  36461. });
  36462. ;
  36463. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36464. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  36465. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  36466. if (element.checked) {
  36467. _this._scene.forceWireframe = false;
  36468. _this._scene.forcePointsCloud = false;
  36469. }
  36470. });
  36471. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  36472. if (element.checked) {
  36473. _this._scene.forceWireframe = true;
  36474. _this._scene.forcePointsCloud = false;
  36475. }
  36476. });
  36477. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  36478. if (element.checked) {
  36479. _this._scene.forceWireframe = false;
  36480. _this._scene.forcePointsCloud = true;
  36481. }
  36482. });
  36483. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36484. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  36485. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  36486. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  36487. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  36488. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  36489. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  36490. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  36491. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  36492. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  36493. this._generateCheckBox(this._optionsSubsetDiv, "ColorGrading", BABYLON.StandardMaterial.ColorGradingTextureEnabled, function (element) { BABYLON.StandardMaterial.ColorGradingTextureEnabled = element.checked; });
  36494. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  36495. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  36496. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36497. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  36498. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  36499. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  36500. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  36501. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  36502. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  36503. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  36504. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  36505. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  36506. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  36507. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  36508. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  36509. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  36510. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  36511. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  36512. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  36513. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36514. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  36515. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  36516. if (element.checked) {
  36517. _this._scene.headphone = true;
  36518. }
  36519. });
  36520. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  36521. if (element.checked) {
  36522. _this._scene.headphone = false;
  36523. }
  36524. });
  36525. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  36526. _this._scene.audioEnabled = !element.checked;
  36527. });
  36528. }
  36529. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36530. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  36531. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  36532. if (!element.checked) {
  36533. _this._clearSkeletonViewers();
  36534. return;
  36535. }
  36536. for (var index = 0; index < _this._scene.meshes.length; index++) {
  36537. var mesh = _this._scene.meshes[index];
  36538. if (mesh.skeleton) {
  36539. var found = false;
  36540. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  36541. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  36542. found = true;
  36543. break;
  36544. }
  36545. }
  36546. if (found) {
  36547. continue;
  36548. }
  36549. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  36550. viewer.isEnabled = true;
  36551. _this._skeletonViewers.push(viewer);
  36552. }
  36553. }
  36554. });
  36555. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36556. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  36557. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  36558. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  36559. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  36560. if (_this._camera) {
  36561. console.log(_this._camera);
  36562. }
  36563. else {
  36564. console.warn("No camera defined, or debug layer created before camera creation!");
  36565. }
  36566. });
  36567. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36568. this._globalDiv.appendChild(this._statsDiv);
  36569. this._globalDiv.appendChild(this._logDiv);
  36570. this._globalDiv.appendChild(this._optionsDiv);
  36571. this._globalDiv.appendChild(this._treeDiv);
  36572. }
  36573. };
  36574. DebugLayer.prototype._displayStats = function () {
  36575. var scene = this._scene;
  36576. var engine = scene.getEngine();
  36577. var glInfo = engine.getGlInfo();
  36578. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  36579. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  36580. + "<b>Count</b><br>"
  36581. + "Total meshes: " + scene.meshes.length + "<br>"
  36582. + "Total lights: " + scene.lights.length + "<br>"
  36583. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  36584. + "Total materials: " + scene.materials.length + "<br>"
  36585. + "Total textures: " + scene.textures.length + "<br>"
  36586. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  36587. + "Active indices: " + scene.getActiveIndices() + "<br>"
  36588. + "Active bones: " + scene.getActiveBones() + "<br>"
  36589. + "Active particles: " + scene.getActiveParticles() + "<br>"
  36590. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  36591. + "<b>Duration</b><br>"
  36592. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  36593. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  36594. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  36595. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  36596. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  36597. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  36598. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  36599. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  36600. + "</div>"
  36601. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  36602. + "<b>Extensions</b><br>"
  36603. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  36604. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  36605. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  36606. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  36607. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  36608. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  36609. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  36610. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  36611. + "</div><br>"
  36612. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  36613. + "<b>Caps.</b><br>"
  36614. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  36615. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  36616. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  36617. + "<b>Info</b><br>"
  36618. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  36619. + glInfo.version + "<br>"
  36620. + "</div><br>"
  36621. + glInfo.renderer + "<br>";
  36622. if (this.customStatsFunction) {
  36623. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  36624. }
  36625. };
  36626. return DebugLayer;
  36627. })();
  36628. BABYLON.DebugLayer = DebugLayer;
  36629. })(BABYLON || (BABYLON = {}));
  36630. var BABYLON;
  36631. (function (BABYLON) {
  36632. var SIMDVector3 = (function () {
  36633. function SIMDVector3() {
  36634. }
  36635. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  36636. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  36637. var m0 = SIMD.float32x4.load(transformation.m, 0);
  36638. var m1 = SIMD.float32x4.load(transformation.m, 4);
  36639. var m2 = SIMD.float32x4.load(transformation.m, 8);
  36640. var m3 = SIMD.float32x4.load(transformation.m, 12);
  36641. 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));
  36642. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  36643. SIMD.float32x4.storeXYZ(result._data, 0, r);
  36644. };
  36645. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  36646. var v0 = SIMD.float32x4.splat(x);
  36647. var v1 = SIMD.float32x4.splat(y);
  36648. var v2 = SIMD.float32x4.splat(z);
  36649. var m0 = SIMD.float32x4.load(transformation.m, 0);
  36650. var m1 = SIMD.float32x4.load(transformation.m, 4);
  36651. var m2 = SIMD.float32x4.load(transformation.m, 8);
  36652. var m3 = SIMD.float32x4.load(transformation.m, 12);
  36653. 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));
  36654. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  36655. SIMD.float32x4.storeXYZ(result._data, 0, r);
  36656. };
  36657. return SIMDVector3;
  36658. })();
  36659. BABYLON.SIMDVector3 = SIMDVector3;
  36660. var SIMDMatrix = (function () {
  36661. function SIMDMatrix() {
  36662. }
  36663. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  36664. if (offset === void 0) { offset = 0; }
  36665. var tm = this.m;
  36666. var om = other.m;
  36667. var om0 = SIMD.float32x4.load(om, 0);
  36668. var om1 = SIMD.float32x4.load(om, 4);
  36669. var om2 = SIMD.float32x4.load(om, 8);
  36670. var om3 = SIMD.float32x4.load(om, 12);
  36671. var tm0 = SIMD.float32x4.load(tm, 0);
  36672. 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)))));
  36673. var tm1 = SIMD.float32x4.load(tm, 4);
  36674. 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)))));
  36675. var tm2 = SIMD.float32x4.load(tm, 8);
  36676. 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)))));
  36677. var tm3 = SIMD.float32x4.load(tm, 12);
  36678. 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)))));
  36679. };
  36680. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  36681. var src = this.m;
  36682. var dest = other.m;
  36683. var row0, row1, row2, row3;
  36684. var tmp1;
  36685. var minor0, minor1, minor2, minor3;
  36686. var det;
  36687. // Load the 4 rows
  36688. var src0 = SIMD.float32x4.load(src, 0);
  36689. var src1 = SIMD.float32x4.load(src, 4);
  36690. var src2 = SIMD.float32x4.load(src, 8);
  36691. var src3 = SIMD.float32x4.load(src, 12);
  36692. // Transpose the source matrix. Sort of. Not a true transpose operation
  36693. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  36694. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  36695. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  36696. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  36697. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  36698. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  36699. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  36700. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  36701. // This is a true transposition, but it will lead to an incorrect result
  36702. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  36703. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  36704. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  36705. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  36706. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  36707. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  36708. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  36709. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  36710. // ----
  36711. tmp1 = SIMD.float32x4.mul(row2, row3);
  36712. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36713. minor0 = SIMD.float32x4.mul(row1, tmp1);
  36714. minor1 = SIMD.float32x4.mul(row0, tmp1);
  36715. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36716. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  36717. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  36718. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  36719. // ----
  36720. tmp1 = SIMD.float32x4.mul(row1, row2);
  36721. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36722. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  36723. minor3 = SIMD.float32x4.mul(row0, tmp1);
  36724. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36725. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  36726. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  36727. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  36728. // ----
  36729. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  36730. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36731. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  36732. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  36733. minor2 = SIMD.float32x4.mul(row0, tmp1);
  36734. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36735. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  36736. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  36737. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  36738. // ----
  36739. tmp1 = SIMD.float32x4.mul(row0, row1);
  36740. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36741. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  36742. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  36743. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36744. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  36745. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  36746. // ----
  36747. tmp1 = SIMD.float32x4.mul(row0, row3);
  36748. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36749. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  36750. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  36751. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36752. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  36753. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  36754. // ----
  36755. tmp1 = SIMD.float32x4.mul(row0, row2);
  36756. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36757. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  36758. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  36759. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36760. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  36761. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  36762. // Compute determinant
  36763. det = SIMD.float32x4.mul(row0, minor0);
  36764. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  36765. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  36766. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  36767. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  36768. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  36769. // These shuffles aren't necessary if the faulty transposition is done
  36770. // up at the top of this function.
  36771. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  36772. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  36773. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  36774. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  36775. // Compute final values by multiplying with 1/det
  36776. minor0 = SIMD.float32x4.mul(det, minor0);
  36777. minor1 = SIMD.float32x4.mul(det, minor1);
  36778. minor2 = SIMD.float32x4.mul(det, minor2);
  36779. minor3 = SIMD.float32x4.mul(det, minor3);
  36780. SIMD.float32x4.store(dest, 0, minor0);
  36781. SIMD.float32x4.store(dest, 4, minor1);
  36782. SIMD.float32x4.store(dest, 8, minor2);
  36783. SIMD.float32x4.store(dest, 12, minor3);
  36784. return this;
  36785. };
  36786. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  36787. var out = result.m;
  36788. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  36789. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  36790. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  36791. // cc.kmVec3Subtract(f, pCenter, pEye);
  36792. var f = SIMD.float32x4.sub(center, eye);
  36793. // cc.kmVec3Normalize(f, f);
  36794. var tmp = SIMD.float32x4.mul(f, f);
  36795. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  36796. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  36797. // cc.kmVec3Assign(up, pUp);
  36798. // cc.kmVec3Normalize(up, up);
  36799. tmp = SIMD.float32x4.mul(up, up);
  36800. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  36801. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  36802. // cc.kmVec3Cross(s, f, up);
  36803. 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)));
  36804. // cc.kmVec3Normalize(s, s);
  36805. tmp = SIMD.float32x4.mul(s, s);
  36806. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  36807. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  36808. // cc.kmVec3Cross(u, s, f);
  36809. 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)));
  36810. // cc.kmVec3Normalize(s, s);
  36811. tmp = SIMD.float32x4.mul(s, s);
  36812. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  36813. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  36814. var zero = SIMD.float32x4.splat(0.0);
  36815. s = SIMD.float32x4.neg(s);
  36816. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  36817. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  36818. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  36819. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  36820. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  36821. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  36822. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  36823. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  36824. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  36825. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  36826. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  36827. var b3 = SIMD.float32x4.neg(eye);
  36828. b3 = SIMD.float32x4.withW(b3, 1.0);
  36829. 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)))));
  36830. 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)))));
  36831. 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)))));
  36832. 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)))));
  36833. };
  36834. return SIMDMatrix;
  36835. })();
  36836. BABYLON.SIMDMatrix = SIMDMatrix;
  36837. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  36838. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  36839. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  36840. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  36841. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  36842. var SIMDHelper = (function () {
  36843. function SIMDHelper() {
  36844. }
  36845. Object.defineProperty(SIMDHelper, "IsEnabled", {
  36846. get: function () {
  36847. return SIMDHelper._isEnabled;
  36848. },
  36849. enumerable: true,
  36850. configurable: true
  36851. });
  36852. SIMDHelper.DisableSIMD = function () {
  36853. // Replace functions
  36854. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  36855. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  36856. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  36857. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  36858. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  36859. SIMDHelper._isEnabled = false;
  36860. };
  36861. SIMDHelper.EnableSIMD = function () {
  36862. if (window.SIMD === undefined) {
  36863. return;
  36864. }
  36865. // Replace functions
  36866. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  36867. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  36868. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  36869. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  36870. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  36871. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  36872. get: function () { return this._data[0]; },
  36873. set: function (value) {
  36874. if (!this._data) {
  36875. this._data = new Float32Array(3);
  36876. }
  36877. this._data[0] = value;
  36878. }
  36879. });
  36880. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  36881. get: function () { return this._data[1]; },
  36882. set: function (value) {
  36883. this._data[1] = value;
  36884. }
  36885. });
  36886. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  36887. get: function () { return this._data[2]; },
  36888. set: function (value) {
  36889. this._data[2] = value;
  36890. }
  36891. });
  36892. SIMDHelper._isEnabled = true;
  36893. };
  36894. SIMDHelper._isEnabled = false;
  36895. return SIMDHelper;
  36896. })();
  36897. BABYLON.SIMDHelper = SIMDHelper;
  36898. })(BABYLON || (BABYLON = {}));
  36899. var BABYLON;
  36900. (function (BABYLON) {
  36901. /**
  36902. * This class describe a rectangle that were added to the map.
  36903. * You have access to its coordinates either in pixel or normalized (UV)
  36904. */
  36905. var PackedRect = (function () {
  36906. function PackedRect(root, parent, pos, size) {
  36907. this._pos = pos;
  36908. this._size = size;
  36909. this._root = root;
  36910. this._parent = parent;
  36911. }
  36912. Object.defineProperty(PackedRect.prototype, "pos", {
  36913. /**
  36914. * @returns the position of this node into the map
  36915. */
  36916. get: function () {
  36917. return this._pos;
  36918. },
  36919. enumerable: true,
  36920. configurable: true
  36921. });
  36922. Object.defineProperty(PackedRect.prototype, "contentSize", {
  36923. /**
  36924. * @returns the size of the rectangle this node handles
  36925. */
  36926. get: function () {
  36927. return this._contentSize;
  36928. },
  36929. enumerable: true,
  36930. configurable: true
  36931. });
  36932. Object.defineProperty(PackedRect.prototype, "UVs", {
  36933. /**
  36934. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  36935. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  36936. */
  36937. get: function () {
  36938. return this.getUVsForCustomSize(this._root._size);
  36939. },
  36940. enumerable: true,
  36941. configurable: true
  36942. });
  36943. /**
  36944. * 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.
  36945. * This method will return the UVs for this part by given the custom size of what you really use
  36946. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  36947. */
  36948. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  36949. var mainWidth = this._root._size.width;
  36950. var mainHeight = this._root._size.height;
  36951. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  36952. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  36953. var uvs = new Array();
  36954. uvs.push(topLeft);
  36955. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  36956. uvs.push(rightBottom);
  36957. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  36958. return uvs;
  36959. };
  36960. /**
  36961. * Free this rectangle from the map.
  36962. * Call this method when you no longer need the rectangle to be in the map.
  36963. */
  36964. PackedRect.prototype.freeContent = function () {
  36965. if (!this.contentSize) {
  36966. return;
  36967. }
  36968. this._contentSize = null;
  36969. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  36970. this.attemptDefrag();
  36971. };
  36972. Object.defineProperty(PackedRect.prototype, "isUsed", {
  36973. get: function () {
  36974. return this._contentSize != null || this._leftNode != null;
  36975. },
  36976. enumerable: true,
  36977. configurable: true
  36978. });
  36979. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  36980. var node = this.findNode(contentSize);
  36981. // Not enough space...
  36982. if (!node) {
  36983. return null;
  36984. }
  36985. node.splitNode(contentSize);
  36986. return node;
  36987. };
  36988. PackedRect.prototype.findNode = function (size) {
  36989. var resNode = null;
  36990. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  36991. if (this.isUsed) {
  36992. if (this._leftNode) {
  36993. resNode = this._leftNode.findNode(size);
  36994. }
  36995. if (!resNode && this._rightNode) {
  36996. resNode = this._rightNode.findNode(size);
  36997. }
  36998. if (!resNode && this._bottomNode) {
  36999. resNode = this._bottomNode.findNode(size);
  37000. }
  37001. }
  37002. else if (this._initialSize && (size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  37003. resNode = this;
  37004. }
  37005. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  37006. resNode = this;
  37007. }
  37008. return resNode;
  37009. };
  37010. PackedRect.prototype.splitNode = function (contentSize) {
  37011. // 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)
  37012. if (!this._contentSize && this._initialSize) {
  37013. 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));
  37014. return this._leftNode.splitNode(contentSize);
  37015. }
  37016. else {
  37017. this._contentSize = contentSize.clone();
  37018. this._initialSize = contentSize.clone();
  37019. if (contentSize.width !== this._size.width) {
  37020. 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));
  37021. }
  37022. if (contentSize.height !== this._size.height) {
  37023. 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));
  37024. }
  37025. return this;
  37026. }
  37027. };
  37028. PackedRect.prototype.attemptDefrag = function () {
  37029. if (!this.isUsed && this.isRecursiveFree) {
  37030. this.clearNode();
  37031. if (this._parent) {
  37032. this._parent.attemptDefrag();
  37033. }
  37034. }
  37035. };
  37036. PackedRect.prototype.clearNode = function () {
  37037. this._initialSize = null;
  37038. this._rightNode = null;
  37039. this._bottomNode = null;
  37040. };
  37041. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  37042. get: function () {
  37043. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  37044. },
  37045. enumerable: true,
  37046. configurable: true
  37047. });
  37048. PackedRect.prototype.evalFreeSize = function (size) {
  37049. var levelSize = 0;
  37050. if (!this.isUsed) {
  37051. if (this._initialSize) {
  37052. levelSize = this._initialSize.surface;
  37053. }
  37054. else {
  37055. levelSize = this._size.surface;
  37056. }
  37057. }
  37058. if (this._rightNode) {
  37059. levelSize += this._rightNode.evalFreeSize(0);
  37060. }
  37061. if (this._bottomNode) {
  37062. levelSize += this._bottomNode.evalFreeSize(0);
  37063. }
  37064. return levelSize + size;
  37065. };
  37066. return PackedRect;
  37067. })();
  37068. BABYLON.PackedRect = PackedRect;
  37069. /**
  37070. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  37071. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  37072. * 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.
  37073. */
  37074. var RectPackingMap = (function (_super) {
  37075. __extends(RectPackingMap, _super);
  37076. /**
  37077. * Create an instance of the object with a dimension using the given size
  37078. * @param size The dimension of the rectangle that will contain all the sub ones.
  37079. */
  37080. function RectPackingMap(size) {
  37081. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  37082. this._root = this;
  37083. }
  37084. /**
  37085. * Add a rectangle, finding the best location to store it into the map
  37086. * @param size the dimension of the rectangle to store
  37087. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  37088. */
  37089. RectPackingMap.prototype.addRect = function (size) {
  37090. var node = this.findAndSplitNode(size);
  37091. return node;
  37092. };
  37093. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  37094. /**
  37095. * Return the current space free normalized between [0;1]
  37096. * @returns {}
  37097. */
  37098. get: function () {
  37099. var freeSize = 0;
  37100. freeSize = this.evalFreeSize(freeSize);
  37101. return freeSize / (this._size.width * this._size.height);
  37102. },
  37103. enumerable: true,
  37104. configurable: true
  37105. });
  37106. return RectPackingMap;
  37107. })(PackedRect);
  37108. BABYLON.RectPackingMap = RectPackingMap;
  37109. })(BABYLON || (BABYLON = {}));
  37110. var BABYLON;
  37111. (function (BABYLON) {
  37112. var DynamicFloatArrayElementInfo = (function () {
  37113. function DynamicFloatArrayElementInfo() {
  37114. }
  37115. return DynamicFloatArrayElementInfo;
  37116. })();
  37117. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  37118. /**
  37119. * 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.
  37120. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  37121. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  37122. * 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.
  37123. * 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.
  37124. * 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".
  37125. */
  37126. var DynamicFloatArray = (function () {
  37127. /**
  37128. * Construct an instance of the dynamic float array
  37129. * @param stride size of one element in float (i.e. not bytes!)
  37130. * @param initialElementCount the number of available entries at construction
  37131. */
  37132. function DynamicFloatArray(stride, initialElementCount) {
  37133. this.compareValueOffset = null;
  37134. this.sortingAscending = true;
  37135. this._stride = stride;
  37136. this.buffer = new Float32Array(stride * initialElementCount);
  37137. this._lastUsed = 0;
  37138. this._firstFree = 0;
  37139. this._allEntries = new Array(initialElementCount);
  37140. this._freeEntries = new Array(initialElementCount);
  37141. for (var i = 0; i < initialElementCount; i++) {
  37142. var element = new DynamicFloatArrayElementInfo();
  37143. element.offset = i * stride;
  37144. this._allEntries[i] = element;
  37145. this._freeEntries[initialElementCount - i - 1] = element;
  37146. }
  37147. }
  37148. /**
  37149. * Allocate an element in the array.
  37150. * @return the element info instance that contains the offset into the main buffer of the element's location.
  37151. * Beware, this offset may change when you call pack()
  37152. */
  37153. DynamicFloatArray.prototype.allocElement = function () {
  37154. if (this._freeEntries.length === 0) {
  37155. this._growBuffer();
  37156. }
  37157. var el = this._freeEntries.pop();
  37158. this._lastUsed = Math.max(el.offset, this._lastUsed);
  37159. if (el.offset === this._firstFree) {
  37160. if (this._freeEntries.length > 0) {
  37161. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  37162. }
  37163. else {
  37164. this._firstFree += this._stride;
  37165. }
  37166. }
  37167. return el;
  37168. };
  37169. /**
  37170. * Free the element corresponding to the given element info
  37171. * @param elInfo the element that describe the allocated element
  37172. */
  37173. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  37174. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  37175. this._freeEntries.push(elInfo);
  37176. };
  37177. /**
  37178. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  37179. * 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().
  37180. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  37181. */
  37182. DynamicFloatArray.prototype.pack = function () {
  37183. // no free slot? no need to pack
  37184. if (this._freeEntries.length === 0) {
  37185. return this.buffer;
  37186. }
  37187. // If the buffer is already packed the last used will always be lower than the first free
  37188. // 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.
  37189. if (this._lastUsed < this._firstFree) {
  37190. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  37191. return elementsBuffer_1;
  37192. }
  37193. var s = this._stride;
  37194. // 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
  37195. var lastFree = new DynamicFloatArrayElementInfo();
  37196. lastFree.offset = this.totalElementCount * s;
  37197. this._freeEntries.push(lastFree);
  37198. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  37199. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  37200. var firstFreeSlotOffset = sortedFree[0].offset;
  37201. var freeZoneSize = 1;
  37202. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  37203. var prevOffset = sortedFree[0].offset;
  37204. for (var i = 1; i < sortedFree.length; i++) {
  37205. // 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
  37206. if (firstFreeSlotOffset >= occupiedZoneSize) {
  37207. break;
  37208. }
  37209. var curFree = sortedFree[i];
  37210. var curOffset = curFree.offset;
  37211. // Compute the distance between this offset and the previous
  37212. var distance = curOffset - prevOffset;
  37213. // If the distance is the stride size, they are adjacent, it good, move to the next
  37214. if (distance === s) {
  37215. // Free zone is one element bigger
  37216. ++freeZoneSize;
  37217. // as we're about to iterate to the next, the cur becomes the previous...
  37218. prevOffset = curOffset;
  37219. continue;
  37220. }
  37221. // Distance is bigger, which means there's x element between the previous free and this one
  37222. var usedRange = (distance / s) - 1;
  37223. // Two cases the free zone is smaller than the data to move or bigger
  37224. // Copy what can fit in the free zone
  37225. var curMoveOffset = curOffset - s;
  37226. var copyCount = Math.min(freeZoneSize, usedRange);
  37227. for (var j = 0; j < copyCount; j++) {
  37228. var freeI = firstFreeSlotOffset / s;
  37229. var curI = curMoveOffset / s;
  37230. var moveEl = sortedAll[curI];
  37231. this._moveElement(moveEl, firstFreeSlotOffset);
  37232. var replacedEl = sortedAll[freeI];
  37233. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  37234. replacedEl.offset = curMoveOffset;
  37235. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  37236. sortedAll[freeI] = moveEl;
  37237. sortedAll[curI] = replacedEl;
  37238. curMoveOffset -= s;
  37239. firstFreeSlotOffset += s;
  37240. }
  37241. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  37242. if (freeZoneSize <= usedRange) {
  37243. firstFreeSlotOffset = curMoveOffset + s;
  37244. freeZoneSize = 1 + copyCount;
  37245. }
  37246. else {
  37247. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  37248. }
  37249. // as we're about to iterate to the next, the cur becomes the previous...
  37250. prevOffset = curOffset;
  37251. }
  37252. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  37253. this._lastUsed = firstFreeSlotOffset - s;
  37254. this._firstFree = firstFreeSlotOffset;
  37255. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  37256. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  37257. this._allEntries = sortedAll;
  37258. return elementsBuffer;
  37259. };
  37260. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  37261. for (var i = 0; i < this._stride; i++) {
  37262. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  37263. }
  37264. element.offset = destOffset;
  37265. };
  37266. DynamicFloatArray.prototype._growBuffer = function () {
  37267. // Allocate the new buffer with 50% more entries, copy the content of the current one
  37268. var newElCount = Math.floor(this.totalElementCount * 1.5);
  37269. var newBuffer = new Float32Array(newElCount * this._stride);
  37270. newBuffer.set(this.buffer);
  37271. var curCount = this.totalElementCount;
  37272. var addedCount = newElCount - this.totalElementCount;
  37273. for (var i = 0; i < addedCount; i++) {
  37274. var element = new DynamicFloatArrayElementInfo();
  37275. element.offset = (curCount + i) * this.stride;
  37276. this._allEntries.push(element);
  37277. this._freeEntries[addedCount - i - 1] = element;
  37278. }
  37279. this._firstFree = curCount * this.stride;
  37280. this.buffer = newBuffer;
  37281. };
  37282. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  37283. /**
  37284. * Get the total count of entries that can fit in the current buffer
  37285. * @returns the elements count
  37286. */
  37287. get: function () {
  37288. return this._allEntries.length;
  37289. },
  37290. enumerable: true,
  37291. configurable: true
  37292. });
  37293. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  37294. /**
  37295. * Get the count of free entries that can still be allocated without resizing the buffer
  37296. * @returns the free elements count
  37297. */
  37298. get: function () {
  37299. return this._freeEntries.length;
  37300. },
  37301. enumerable: true,
  37302. configurable: true
  37303. });
  37304. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  37305. /**
  37306. * Get the count of allocated elements
  37307. * @returns the allocated elements count
  37308. */
  37309. get: function () {
  37310. return this._allEntries.length - this._freeEntries.length;
  37311. },
  37312. enumerable: true,
  37313. configurable: true
  37314. });
  37315. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  37316. /**
  37317. * Return the size of one element in float
  37318. * @returns the size in float
  37319. */
  37320. get: function () {
  37321. return this._stride;
  37322. },
  37323. enumerable: true,
  37324. configurable: true
  37325. });
  37326. DynamicFloatArray.prototype.sort = function () {
  37327. var _this = this;
  37328. if (!this.compareValueOffset) {
  37329. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  37330. }
  37331. var count = this.usedElementCount;
  37332. // Do we have to (re)create the sort table?
  37333. if (!this._sortTable || this._sortTable.length < count) {
  37334. // 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...
  37335. var newCount = Math.min(this.totalElementCount, count * 2);
  37336. this._sortTable = new Array(newCount);
  37337. }
  37338. if (!this._sortedTable || this._sortedTable.length !== count) {
  37339. this._sortedTable = new Array(count);
  37340. }
  37341. // Because, you know...
  37342. this.pack();
  37343. //let stride = this.stride;
  37344. //for (let i = 0; i < count; i++) {
  37345. // let si = this._sortTable[i];
  37346. // if (!si) {
  37347. // si = new SortInfo();
  37348. // this._sortTable[i] = si;
  37349. // }
  37350. // si.entry = this._allEntries[i];
  37351. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  37352. // si.swapedOffset = null;
  37353. // this._sortedTable[i] = si;
  37354. //}
  37355. var curOffset = 0;
  37356. var stride = this.stride;
  37357. for (var i = 0; i < count; i++, curOffset += stride) {
  37358. var si = this._sortTable[i];
  37359. if (!si) {
  37360. si = new SortInfo();
  37361. this._sortTable[i] = si;
  37362. }
  37363. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  37364. si.offset = curOffset;
  37365. si.swapedOffset = null;
  37366. this._sortedTable[i] = si;
  37367. }
  37368. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  37369. if (this.sortingAscending) {
  37370. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  37371. }
  37372. else {
  37373. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  37374. }
  37375. var swapElements = function (src, dst) {
  37376. for (var i = 0; i < stride; i++) {
  37377. var tps = _this.buffer[dst + i];
  37378. _this.buffer[dst + i] = _this.buffer[src + i];
  37379. _this.buffer[src + i] = tps;
  37380. }
  37381. };
  37382. // 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:
  37383. // 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),
  37384. // and I still want something with a good algorithm complexity.
  37385. // 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,
  37386. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  37387. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  37388. // 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
  37389. // until we find a SortInfo object without a swapedOffset which means we got the right location
  37390. // 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
  37391. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  37392. for (var i = 0; i < count; i++) {
  37393. // Get the element to move
  37394. var sourceSI = this._sortedTable[i];
  37395. var destSI = this._sortTable[i];
  37396. var sourceOff = sourceSI.offset;
  37397. // If the source changed location, find the new one
  37398. if (sourceSI.swapedOffset) {
  37399. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  37400. var curSI = sourceSI;
  37401. while (curSI.swapedOffset) {
  37402. curSI = this._sortTable[curSI.swapedOffset / stride];
  37403. }
  37404. // Finally get the right location
  37405. sourceOff = curSI.offset;
  37406. }
  37407. // Tag the element being replaced with its new location
  37408. destSI.swapedOffset = sourceOff;
  37409. // Swap elements (only if needed)
  37410. if (sourceOff !== destSI.offset) {
  37411. swapElements(sourceOff, destSI.offset);
  37412. }
  37413. // Update the offset in the corresponding DFAE
  37414. //sourceSI.entry.offset = destSI.entry.offset;
  37415. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  37416. }
  37417. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  37418. return true;
  37419. };
  37420. return DynamicFloatArray;
  37421. })();
  37422. BABYLON.DynamicFloatArray = DynamicFloatArray;
  37423. var SortInfo = (function () {
  37424. function SortInfo() {
  37425. this.compareData = this.offset = this.swapedOffset = null;
  37426. }
  37427. return SortInfo;
  37428. })();
  37429. })(BABYLON || (BABYLON = {}));
  37430. var BABYLON;
  37431. (function (BABYLON) {
  37432. /**
  37433. * This class given information about a given character.
  37434. */
  37435. var CharInfo = (function () {
  37436. function CharInfo() {
  37437. }
  37438. return CharInfo;
  37439. })();
  37440. BABYLON.CharInfo = CharInfo;
  37441. var FontTexture = (function (_super) {
  37442. __extends(FontTexture, _super);
  37443. /**
  37444. * Create a new instance of the FontTexture class
  37445. * @param name the name of the texture
  37446. * @param font the font to use, use the W3C CSS notation
  37447. * @param scene the scene that owns the texture
  37448. * @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
  37449. * @param samplingMode the texture sampling mode
  37450. * @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.
  37451. */
  37452. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample) {
  37453. if (maxCharCount === void 0) { maxCharCount = 200; }
  37454. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37455. if (superSample === void 0) { superSample = false; }
  37456. _super.call(this, null, scene, true, false, samplingMode);
  37457. this._charInfos = {};
  37458. this._curCharCount = 0;
  37459. this._lastUpdateCharCount = -1;
  37460. this._usedCounter = 1;
  37461. this.name = name;
  37462. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37463. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37464. this._superSample = false;
  37465. if (superSample) {
  37466. var sfont = this.getSuperSampleFont(font);
  37467. if (sfont) {
  37468. this._superSample = true;
  37469. font = sfont;
  37470. }
  37471. }
  37472. // First canvas creation to determine the size of the texture to create
  37473. this._canvas = document.createElement("canvas");
  37474. this._context = this._canvas.getContext("2d");
  37475. this._context.font = font;
  37476. this._context.fillStyle = "white";
  37477. this._cachedFontId = null;
  37478. var res = this.getFontHeight(font);
  37479. this._lineHeightSuper = res.height;
  37480. this._lineHeight = this._superSample ? (this._lineHeightSuper / 2) : this._lineHeightSuper;
  37481. this._offset = res.offset - 1;
  37482. var maxCharWidth = this._context.measureText("W").width;
  37483. this._spaceWidthSuper = this._context.measureText(" ").width;
  37484. this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
  37485. // This is an approximate size, but should always be able to fit at least the maxCharCount
  37486. var totalEstSurface = this._lineHeightSuper * maxCharWidth * maxCharCount;
  37487. var edge = Math.sqrt(totalEstSurface);
  37488. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  37489. // Create the texture that will store the font characters
  37490. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  37491. var textureSize = this.getSize();
  37492. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  37493. this._canvas = document.createElement("canvas");
  37494. this._canvas.width = textureSize.width;
  37495. this._canvas.height = textureSize.height;
  37496. this._context = this._canvas.getContext("2d");
  37497. this._context.textBaseline = "top";
  37498. this._context.font = font;
  37499. this._context.fillStyle = "white";
  37500. this._context.imageSmoothingEnabled = false;
  37501. this._currentFreePosition = BABYLON.Vector2.Zero();
  37502. // Add the basic ASCII based characters
  37503. for (var i = 0x20; i < 0x7F; i++) {
  37504. var c = String.fromCharCode(i);
  37505. this.getChar(c);
  37506. }
  37507. this.update();
  37508. }
  37509. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  37510. get: function () {
  37511. return this._superSample;
  37512. },
  37513. enumerable: true,
  37514. configurable: true
  37515. });
  37516. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  37517. get: function () {
  37518. return this._spaceWidth;
  37519. },
  37520. enumerable: true,
  37521. configurable: true
  37522. });
  37523. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  37524. get: function () {
  37525. return this._lineHeight;
  37526. },
  37527. enumerable: true,
  37528. configurable: true
  37529. });
  37530. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample) {
  37531. if (supersample === void 0) { supersample = false; }
  37532. var s = scene;
  37533. if (!s.__fontTextureCache__) {
  37534. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  37535. }
  37536. var dic = s.__fontTextureCache__;
  37537. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  37538. var ft = dic.get(lfn);
  37539. if (ft) {
  37540. ++ft._usedCounter;
  37541. return ft;
  37542. }
  37543. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample);
  37544. ft._cachedFontId = lfn;
  37545. dic.add(lfn, ft);
  37546. return ft;
  37547. };
  37548. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample) {
  37549. if (supersample === void 0) { supersample = false; }
  37550. var s = scene;
  37551. var dic = s.__fontTextureCache__;
  37552. if (!dic) {
  37553. return;
  37554. }
  37555. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  37556. var font = dic.get(lfn);
  37557. if (--font._usedCounter === 0) {
  37558. dic.remove(lfn);
  37559. font.dispose();
  37560. }
  37561. };
  37562. /**
  37563. * Make sure the given char is present in the font map.
  37564. * @param char the character to get or add
  37565. * @return the CharInfo instance corresponding to the given character
  37566. */
  37567. FontTexture.prototype.getChar = function (char) {
  37568. if (char.length !== 1) {
  37569. return null;
  37570. }
  37571. var info = this._charInfos[char];
  37572. if (info) {
  37573. return info;
  37574. }
  37575. info = new CharInfo();
  37576. var measure = this._context.measureText(char);
  37577. var textureSize = this.getSize();
  37578. // we reached the end of the current line?
  37579. var width = Math.round(measure.width);
  37580. var xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  37581. var yMargin = xMargin;
  37582. if (this._currentFreePosition.x + width + xMargin > textureSize.width) {
  37583. this._currentFreePosition.x = 0;
  37584. this._currentFreePosition.y += this._lineHeightSuper + yMargin;
  37585. // No more room?
  37586. if (this._currentFreePosition.y > textureSize.height) {
  37587. return this.getChar("!");
  37588. }
  37589. }
  37590. // Draw the character in the texture
  37591. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  37592. // Fill the CharInfo object
  37593. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  37594. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  37595. info.charWidth = this._superSample ? (width / 2) : width;
  37596. // Add the info structure
  37597. this._charInfos[char] = info;
  37598. this._curCharCount++;
  37599. // Set the next position
  37600. this._currentFreePosition.x += width + xMargin;
  37601. return info;
  37602. };
  37603. FontTexture.prototype.measureText = function (text, tabulationSize) {
  37604. if (tabulationSize === void 0) { tabulationSize = 4; }
  37605. var maxWidth = 0;
  37606. var curWidth = 0;
  37607. var lineCount = 1;
  37608. var charxpos = 0;
  37609. // Parse each char of the string
  37610. for (var _i = 0; _i < text.length; _i++) {
  37611. var char = text[_i];
  37612. // Next line feed?
  37613. if (char === "\n") {
  37614. maxWidth = Math.max(maxWidth, curWidth);
  37615. charxpos = 0;
  37616. curWidth = 0;
  37617. ++lineCount;
  37618. continue;
  37619. }
  37620. // Tabulation ?
  37621. if (char === "\t") {
  37622. var nextPos = charxpos + tabulationSize;
  37623. nextPos = nextPos - (nextPos % tabulationSize);
  37624. curWidth += (nextPos - charxpos) * this.spaceWidth;
  37625. charxpos = nextPos;
  37626. continue;
  37627. }
  37628. if (char < " ") {
  37629. continue;
  37630. }
  37631. curWidth += this.getChar(char).charWidth;
  37632. ++charxpos;
  37633. }
  37634. maxWidth = Math.max(maxWidth, curWidth);
  37635. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  37636. };
  37637. FontTexture.prototype.getSuperSampleFont = function (font) {
  37638. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  37639. 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*$/;
  37640. var res = font.toLocaleLowerCase().match(regex);
  37641. if (res == null) {
  37642. return null;
  37643. }
  37644. var size = parseInt(res[4]);
  37645. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  37646. var newFont = "";
  37647. for (var j = 1; j < res.length; j++) {
  37648. if (res[j] != null) {
  37649. newFont += res[j] + " ";
  37650. }
  37651. }
  37652. return newFont;
  37653. };
  37654. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  37655. FontTexture.prototype.getFontHeight = function (font) {
  37656. var fontDraw = document.createElement("canvas");
  37657. var ctx = fontDraw.getContext('2d');
  37658. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  37659. ctx.textBaseline = 'top';
  37660. ctx.fillStyle = 'white';
  37661. ctx.font = font;
  37662. ctx.fillText('jH|', 0, 0);
  37663. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  37664. var start = -1;
  37665. var end = -1;
  37666. for (var row = 0; row < fontDraw.height; row++) {
  37667. for (var column = 0; column < fontDraw.width; column++) {
  37668. var index = (row * fontDraw.width + column) * 4;
  37669. if (pixels[index] === 0) {
  37670. if (column === fontDraw.width - 1 && start !== -1) {
  37671. end = row;
  37672. row = fontDraw.height;
  37673. break;
  37674. }
  37675. continue;
  37676. }
  37677. else {
  37678. if (start === -1) {
  37679. start = row;
  37680. }
  37681. break;
  37682. }
  37683. }
  37684. }
  37685. return { height: (end - start) + 1, offset: start - 1 };
  37686. };
  37687. Object.defineProperty(FontTexture.prototype, "canRescale", {
  37688. get: function () {
  37689. return false;
  37690. },
  37691. enumerable: true,
  37692. configurable: true
  37693. });
  37694. FontTexture.prototype.getContext = function () {
  37695. return this._context;
  37696. };
  37697. /**
  37698. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  37699. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  37700. */
  37701. FontTexture.prototype.update = function () {
  37702. // Update only if there's new char added since the previous update
  37703. if (this._lastUpdateCharCount < this._curCharCount) {
  37704. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  37705. this._lastUpdateCharCount = this._curCharCount;
  37706. }
  37707. };
  37708. // cloning should be prohibited, there's no point to duplicate this texture at all
  37709. FontTexture.prototype.clone = function () {
  37710. return null;
  37711. };
  37712. /**
  37713. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  37714. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  37715. */
  37716. FontTexture.prototype.incCachedFontTextureCounter = function () {
  37717. ++this._usedCounter;
  37718. };
  37719. /**
  37720. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  37721. */
  37722. FontTexture.prototype.decCachedFontTextureCounter = function () {
  37723. var s = this.getScene();
  37724. var dic = s.__fontTextureCache__;
  37725. if (!dic) {
  37726. return;
  37727. }
  37728. if (--this._usedCounter === 0) {
  37729. dic.remove(this._cachedFontId);
  37730. this.dispose();
  37731. }
  37732. };
  37733. return FontTexture;
  37734. })(BABYLON.Texture);
  37735. BABYLON.FontTexture = FontTexture;
  37736. })(BABYLON || (BABYLON = {}));
  37737. var BABYLON;
  37738. (function (BABYLON) {
  37739. var MapTexture = (function (_super) {
  37740. __extends(MapTexture, _super);
  37741. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  37742. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37743. if (useMipMap === void 0) { useMipMap = false; }
  37744. _super.call(this, null, scene, !useMipMap, false, samplingMode);
  37745. this.name = name;
  37746. this._size = size;
  37747. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37748. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37749. // Create the rectPackMap that will allocate portion of the texture
  37750. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  37751. // Create the texture that will store the content
  37752. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  37753. }
  37754. /**
  37755. * Allocate a rectangle of a given size in the texture map
  37756. * @param size the size of the rectangle to allocation
  37757. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  37758. */
  37759. MapTexture.prototype.allocateRect = function (size) {
  37760. return this._rectPackingMap.addRect(size);
  37761. };
  37762. /**
  37763. * Free a given rectangle from the texture map
  37764. * @param rectInfo the instance corresponding to the rect to free.
  37765. */
  37766. MapTexture.prototype.freeRect = function (rectInfo) {
  37767. if (rectInfo) {
  37768. rectInfo.freeContent();
  37769. }
  37770. };
  37771. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  37772. /**
  37773. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  37774. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  37775. * @returns {}
  37776. */
  37777. get: function () {
  37778. return this._rectPackingMap.freeSpace;
  37779. },
  37780. enumerable: true,
  37781. configurable: true
  37782. });
  37783. /**
  37784. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  37785. * 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.
  37786. * Don't forget to call unbindTexture when you're done rendering
  37787. * @param rect the zone to render to
  37788. * @param clear true to clear the portion's color/depth data
  37789. */
  37790. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  37791. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  37792. };
  37793. /**
  37794. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  37795. * 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.
  37796. * Don't forget to call unbindTexture when you're done rendering
  37797. * @param pos the position into the texture
  37798. * @param size the portion to fit the clip space to
  37799. * @param clear true to clear the portion's color/depth data
  37800. */
  37801. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  37802. var engine = this.getScene().getEngine();
  37803. engine.bindFramebuffer(this._texture);
  37804. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  37805. if (clear) {
  37806. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  37807. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  37808. }
  37809. };
  37810. /**
  37811. * Unbind the texture map from the rendering engine.
  37812. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  37813. * @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.
  37814. */
  37815. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  37816. // Dump ?
  37817. if (dumpForDebug) {
  37818. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  37819. }
  37820. var engine = this.getScene().getEngine();
  37821. if (this._replacedViewport) {
  37822. engine.setViewport(this._replacedViewport);
  37823. this._replacedViewport = null;
  37824. }
  37825. engine.unBindFramebuffer(this._texture);
  37826. };
  37827. Object.defineProperty(MapTexture.prototype, "canRescale", {
  37828. get: function () {
  37829. return false;
  37830. },
  37831. enumerable: true,
  37832. configurable: true
  37833. });
  37834. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  37835. // Anyway, there's not much point to use this method for this kind of texture I guess
  37836. MapTexture.prototype.clone = function () {
  37837. return null;
  37838. };
  37839. return MapTexture;
  37840. })(BABYLON.Texture);
  37841. BABYLON.MapTexture = MapTexture;
  37842. })(BABYLON || (BABYLON = {}));
  37843. var BABYLON;
  37844. (function (BABYLON) {
  37845. /**
  37846. * Stores 2D Bounding Information.
  37847. * This class handles a circle area and a bounding rectangle one.
  37848. */
  37849. var BoundingInfo2D = (function () {
  37850. function BoundingInfo2D() {
  37851. this.radius = 0;
  37852. this.center = BABYLON.Vector2.Zero();
  37853. this.extent = BABYLON.Vector2.Zero();
  37854. }
  37855. /**
  37856. * Create a BoundingInfo2D object from a given size
  37857. * @param size the size that will be used to set the extend, radius will be computed from it.
  37858. */
  37859. BoundingInfo2D.CreateFromSize = function (size) {
  37860. var r = new BoundingInfo2D();
  37861. BoundingInfo2D.CreateFromSizeToRef(size, r);
  37862. return r;
  37863. };
  37864. /**
  37865. * Create a BoundingInfo2D object from a given radius
  37866. * @param radius the radius to use, the extent will be computed from it.
  37867. */
  37868. BoundingInfo2D.CreateFromRadius = function (radius) {
  37869. var r = new BoundingInfo2D();
  37870. BoundingInfo2D.CreateFromRadiusToRef(radius, r);
  37871. return r;
  37872. };
  37873. /**
  37874. * Create a BoundingInfo2D object from a list of points.
  37875. * The resulted object will be the smallest bounding area that includes all the given points.
  37876. * @param points an array of points to compute the bounding object from.
  37877. */
  37878. BoundingInfo2D.CreateFromPoints = function (points) {
  37879. var r = new BoundingInfo2D();
  37880. BoundingInfo2D.CreateFromPointsToRef(points, r);
  37881. return r;
  37882. };
  37883. /**
  37884. * Update a BoundingInfo2D object using the given Size as input
  37885. * @param size the bounding data will be computed from this size.
  37886. * @param b must be a valid/allocated object, it will contain the result of the operation
  37887. */
  37888. BoundingInfo2D.CreateFromSizeToRef = function (size, b) {
  37889. if (!size) {
  37890. size = BABYLON.Size.Zero();
  37891. }
  37892. b.center.x = +size.width / 2;
  37893. b.center.y = +size.height / 2;
  37894. b.extent.x = b.center.x;
  37895. b.extent.y = b.center.y;
  37896. b.radius = b.extent.length();
  37897. };
  37898. /**
  37899. * Update a BoundingInfo2D object using the given radius as input
  37900. * @param radius the bounding data will be computed from this radius
  37901. * @param b must be a valid/allocated object, it will contain the result of the operation
  37902. */
  37903. BoundingInfo2D.CreateFromRadiusToRef = function (radius, b) {
  37904. b.center.x = b.center.y = 0;
  37905. var r = +radius;
  37906. b.extent.x = r;
  37907. b.extent.y = r;
  37908. b.radius = r;
  37909. };
  37910. /**
  37911. * Update a BoundingInfo2D object using the given points array as input
  37912. * @param points the point array to use to update the bounding data
  37913. * @param b must be a valid/allocated object, it will contain the result of the operation
  37914. */
  37915. BoundingInfo2D.CreateFromPointsToRef = function (points, b) {
  37916. var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
  37917. for (var _i = 0; _i < points.length; _i++) {
  37918. var p = points[_i];
  37919. xmin = Math.min(p.x, xmin);
  37920. xmax = Math.max(p.x, xmax);
  37921. ymin = Math.min(p.y, ymin);
  37922. ymax = Math.max(p.y, ymax);
  37923. }
  37924. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b);
  37925. };
  37926. /**
  37927. * Update a BoundingInfo2D object using the given min/max values as input
  37928. * @param xmin the smallest x coordinate
  37929. * @param xmax the biggest x coordinate
  37930. * @param ymin the smallest y coordinate
  37931. * @param ymax the buggest y coordinate
  37932. * @param b must be a valid/allocated object, it will contain the result of the operation
  37933. */
  37934. BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b) {
  37935. var w = xmax - xmin;
  37936. var h = ymax - ymin;
  37937. b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
  37938. b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
  37939. b.radius = b.extent.length();
  37940. };
  37941. /**
  37942. * Duplicate this instance and return a new one
  37943. * @return the duplicated instance
  37944. */
  37945. BoundingInfo2D.prototype.clone = function () {
  37946. var r = new BoundingInfo2D();
  37947. r.center = this.center.clone();
  37948. r.radius = this.radius;
  37949. r.extent = this.extent.clone();
  37950. return r;
  37951. };
  37952. BoundingInfo2D.prototype.clear = function () {
  37953. this.center.copyFromFloats(0, 0);
  37954. this.radius = 0;
  37955. this.extent.copyFromFloats(0, 0);
  37956. };
  37957. BoundingInfo2D.prototype.copyFrom = function (src) {
  37958. this.center.copyFrom(src.center);
  37959. this.radius = src.radius;
  37960. this.extent.copyFrom(src.extent);
  37961. };
  37962. /**
  37963. * return the max extend of the bounding info
  37964. */
  37965. BoundingInfo2D.prototype.max = function () {
  37966. var r = BABYLON.Vector2.Zero();
  37967. this.maxToRef(r);
  37968. return r;
  37969. };
  37970. /**
  37971. * Update a vector2 with the max extend of the bounding info
  37972. * @param result must be a valid/allocated vector2 that will contain the result of the operation
  37973. */
  37974. BoundingInfo2D.prototype.maxToRef = function (result) {
  37975. result.x = this.center.x + this.extent.x;
  37976. result.y = this.center.y + this.extent.y;
  37977. };
  37978. /**
  37979. * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
  37980. * @param matrix the transformation matrix to apply
  37981. * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
  37982. */
  37983. BoundingInfo2D.prototype.transform = function (matrix) {
  37984. var r = new BoundingInfo2D();
  37985. this.transformToRef(matrix, r);
  37986. return r;
  37987. };
  37988. /**
  37989. * Compute the union of this BoundingInfo2D with a given one, returns a new BoundingInfo2D as a result
  37990. * @param other the second BoundingInfo2D to compute the union with this one
  37991. * @return a new instance containing the result of the union
  37992. */
  37993. BoundingInfo2D.prototype.union = function (other) {
  37994. var r = new BoundingInfo2D();
  37995. this.unionToRef(other, r);
  37996. return r;
  37997. };
  37998. /**
  37999. * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
  38000. * 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.
  38001. * @param matrix The matrix to use to compute the transformation
  38002. * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
  38003. */
  38004. BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
  38005. // Construct a bounding box based on the extent values
  38006. var p = BoundingInfo2D._transform;
  38007. p[0].x = this.center.x + this.extent.x;
  38008. p[0].y = this.center.y + this.extent.y;
  38009. p[1].x = this.center.x + this.extent.x;
  38010. p[1].y = this.center.y - this.extent.y;
  38011. p[2].x = this.center.x - this.extent.x;
  38012. p[2].y = this.center.y - this.extent.y;
  38013. p[3].x = this.center.x - this.extent.x;
  38014. p[3].y = this.center.y + this.extent.y;
  38015. // Transform the four points of the bounding box with the matrix
  38016. for (var i = 0; i < 4; i++) {
  38017. BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
  38018. }
  38019. BoundingInfo2D.CreateFromPointsToRef(p, result);
  38020. };
  38021. /**
  38022. * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
  38023. * 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.
  38024. * @param other the second object used to compute the union
  38025. * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
  38026. */
  38027. BoundingInfo2D.prototype.unionToRef = function (other, result) {
  38028. var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
  38029. var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
  38030. var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
  38031. var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
  38032. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
  38033. };
  38034. /**
  38035. * Check if the given point is inside the BoundingInfo.
  38036. * The test is first made on the radius, then inside the rectangle described by the extent
  38037. * @param pickPosition the position to test
  38038. * @return true if the point is inside, false otherwise
  38039. */
  38040. BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
  38041. // is it inside the radius?
  38042. var pickLocal = pickPosition.subtract(this.center);
  38043. if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
  38044. // is it inside the rectangle?
  38045. return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
  38046. }
  38047. return false;
  38048. };
  38049. BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
  38050. return BoundingInfo2D;
  38051. })();
  38052. BABYLON.BoundingInfo2D = BoundingInfo2D;
  38053. })(BABYLON || (BABYLON = {}));
  38054. var BABYLON;
  38055. (function (BABYLON) {
  38056. /**
  38057. * Base class implementing the ILocable interface.
  38058. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  38059. */
  38060. var LockableBase = (function () {
  38061. function LockableBase() {
  38062. }
  38063. LockableBase.prototype.isLocked = function () {
  38064. return this._isLocked;
  38065. };
  38066. LockableBase.prototype.lock = function () {
  38067. if (this._isLocked) {
  38068. return true;
  38069. }
  38070. this.onLock();
  38071. this._isLocked = true;
  38072. return false;
  38073. };
  38074. /**
  38075. * Protected handler that will be called when the instance is about to be locked.
  38076. */
  38077. LockableBase.prototype.onLock = function () {
  38078. };
  38079. return LockableBase;
  38080. })();
  38081. BABYLON.LockableBase = LockableBase;
  38082. var SolidColorBrush2D = (function (_super) {
  38083. __extends(SolidColorBrush2D, _super);
  38084. function SolidColorBrush2D(color, lock) {
  38085. if (lock === void 0) { lock = false; }
  38086. _super.call(this);
  38087. this._color = color;
  38088. if (lock) {
  38089. {
  38090. this.lock();
  38091. }
  38092. }
  38093. }
  38094. /**
  38095. * Return true if the brush is transparent, false if it's totally opaque
  38096. */
  38097. SolidColorBrush2D.prototype.isTransparent = function () {
  38098. return this._color && this._color.a < 1.0;
  38099. };
  38100. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  38101. /**
  38102. * The color used by this instance to render
  38103. * @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.
  38104. */
  38105. get: function () {
  38106. return this._color;
  38107. },
  38108. set: function (value) {
  38109. if (this.isLocked()) {
  38110. return;
  38111. }
  38112. this._color = value;
  38113. },
  38114. enumerable: true,
  38115. configurable: true
  38116. });
  38117. /**
  38118. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  38119. */
  38120. SolidColorBrush2D.prototype.toString = function () {
  38121. return this._color.toHexString();
  38122. };
  38123. SolidColorBrush2D = __decorate([
  38124. BABYLON.className("SolidColorBrush2D")
  38125. ], SolidColorBrush2D);
  38126. return SolidColorBrush2D;
  38127. })(LockableBase);
  38128. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  38129. var GradientColorBrush2D = (function (_super) {
  38130. __extends(GradientColorBrush2D, _super);
  38131. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  38132. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  38133. if (rotation === void 0) { rotation = 0; }
  38134. if (scale === void 0) { scale = 1; }
  38135. if (lock === void 0) { lock = false; }
  38136. _super.call(this);
  38137. this._color1 = color1;
  38138. this._color2 = color2;
  38139. this._translation = translation;
  38140. this._rotation = rotation;
  38141. this._scale = scale;
  38142. if (lock) {
  38143. this.lock();
  38144. }
  38145. }
  38146. /**
  38147. * Return true if the brush is transparent, false if it's totally opaque
  38148. */
  38149. GradientColorBrush2D.prototype.isTransparent = function () {
  38150. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  38151. };
  38152. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  38153. /**
  38154. * First color, the blend will start from this color
  38155. */
  38156. get: function () {
  38157. return this._color1;
  38158. },
  38159. set: function (value) {
  38160. if (this.isLocked()) {
  38161. return;
  38162. }
  38163. this._color1 = value;
  38164. },
  38165. enumerable: true,
  38166. configurable: true
  38167. });
  38168. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  38169. /**
  38170. * Second color, the blend will end to this color
  38171. */
  38172. get: function () {
  38173. return this._color2;
  38174. },
  38175. set: function (value) {
  38176. if (this.isLocked()) {
  38177. return;
  38178. }
  38179. this._color2 = value;
  38180. },
  38181. enumerable: true,
  38182. configurable: true
  38183. });
  38184. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  38185. /**
  38186. * Translation vector to apply on the blend
  38187. * Default is [0;0]
  38188. */
  38189. get: function () {
  38190. return this._translation;
  38191. },
  38192. set: function (value) {
  38193. if (this.isLocked()) {
  38194. return;
  38195. }
  38196. this._translation = value;
  38197. },
  38198. enumerable: true,
  38199. configurable: true
  38200. });
  38201. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  38202. /**
  38203. * Rotation in radian to apply to the brush
  38204. * Default direction of the brush is vertical, you can change this using this property.
  38205. * Default is 0.
  38206. */
  38207. get: function () {
  38208. return this._rotation;
  38209. },
  38210. set: function (value) {
  38211. if (this.isLocked()) {
  38212. return;
  38213. }
  38214. this._rotation = value;
  38215. },
  38216. enumerable: true,
  38217. configurable: true
  38218. });
  38219. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  38220. /**
  38221. * Scale factor to apply to the gradient.
  38222. * Default is 1: no scale.
  38223. */
  38224. get: function () {
  38225. return this._scale;
  38226. },
  38227. set: function (value) {
  38228. if (this.isLocked()) {
  38229. return;
  38230. }
  38231. this._scale = value;
  38232. },
  38233. enumerable: true,
  38234. configurable: true
  38235. });
  38236. /**
  38237. * Return a string describing the brush
  38238. */
  38239. GradientColorBrush2D.prototype.toString = function () {
  38240. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  38241. };
  38242. /**
  38243. * Build a unique key string for the given parameters
  38244. */
  38245. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  38246. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  38247. };
  38248. GradientColorBrush2D = __decorate([
  38249. BABYLON.className("GradientColorBrush2D")
  38250. ], GradientColorBrush2D);
  38251. return GradientColorBrush2D;
  38252. })(LockableBase);
  38253. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  38254. })(BABYLON || (BABYLON = {}));
  38255. var BABYLON;
  38256. (function (BABYLON) {
  38257. var Prim2DClassInfo = (function () {
  38258. function Prim2DClassInfo() {
  38259. }
  38260. return Prim2DClassInfo;
  38261. })();
  38262. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  38263. var Prim2DPropInfo = (function () {
  38264. function Prim2DPropInfo() {
  38265. }
  38266. Prim2DPropInfo.PROPKIND_MODEL = 1;
  38267. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  38268. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  38269. return Prim2DPropInfo;
  38270. })();
  38271. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  38272. /**
  38273. * Custom type of the propertyChanged observable
  38274. */
  38275. var PropertyChangedInfo = (function () {
  38276. function PropertyChangedInfo() {
  38277. }
  38278. return PropertyChangedInfo;
  38279. })();
  38280. BABYLON.PropertyChangedInfo = PropertyChangedInfo;
  38281. var ClassTreeInfo = (function () {
  38282. function ClassTreeInfo(baseClass, type, classContentFactory) {
  38283. this._baseClass = baseClass;
  38284. this._type = type;
  38285. this._subClasses = new Array();
  38286. this._levelContent = new BABYLON.StringDictionary();
  38287. this._classContentFactory = classContentFactory;
  38288. }
  38289. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  38290. get: function () {
  38291. if (!this._classContent) {
  38292. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  38293. }
  38294. return this._classContent;
  38295. },
  38296. enumerable: true,
  38297. configurable: true
  38298. });
  38299. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  38300. get: function () {
  38301. return this._type;
  38302. },
  38303. enumerable: true,
  38304. configurable: true
  38305. });
  38306. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  38307. get: function () {
  38308. return this._levelContent;
  38309. },
  38310. enumerable: true,
  38311. configurable: true
  38312. });
  38313. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  38314. get: function () {
  38315. if (!this._fullContent) {
  38316. var dic = new BABYLON.StringDictionary();
  38317. var curLevel = this;
  38318. while (curLevel) {
  38319. curLevel.levelContent.forEach(function (k, v) { return dic.add(k, v); });
  38320. curLevel = curLevel._baseClass;
  38321. }
  38322. this._fullContent = dic;
  38323. }
  38324. return this._fullContent;
  38325. },
  38326. enumerable: true,
  38327. configurable: true
  38328. });
  38329. ClassTreeInfo.prototype.getLevelOf = function (type) {
  38330. // Are we already there?
  38331. if (type === this._type) {
  38332. return this;
  38333. }
  38334. var baseProto = Object.getPrototypeOf(type);
  38335. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  38336. if (!curProtoContent) {
  38337. this.getLevelOf(baseProto);
  38338. }
  38339. return this.getOrAddType(baseProto, type);
  38340. };
  38341. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  38342. // Are we at the level corresponding to the baseType?
  38343. // If so, get or add the level we're looking for
  38344. if (baseType === this._type) {
  38345. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  38346. var subType = _a[_i];
  38347. if (subType.type === type) {
  38348. return subType.node;
  38349. }
  38350. }
  38351. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  38352. var info = { type: type, node: node };
  38353. this._subClasses.push(info);
  38354. return info.node;
  38355. }
  38356. // Recurse down to keep looking for the node corresponding to the baseTypeName
  38357. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  38358. var subType = _c[_b];
  38359. var info = subType.node.getOrAddType(baseType, type);
  38360. if (info) {
  38361. return info;
  38362. }
  38363. }
  38364. return null;
  38365. };
  38366. ClassTreeInfo.get = function (type) {
  38367. var dic = type["__classTreeInfo"];
  38368. if (!dic) {
  38369. return null;
  38370. }
  38371. return dic.getLevelOf(type);
  38372. };
  38373. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  38374. var dic = type["__classTreeInfo"];
  38375. if (!dic) {
  38376. dic = new ClassTreeInfo(null, type, classContentFactory);
  38377. type["__classTreeInfo"] = dic;
  38378. }
  38379. return dic;
  38380. };
  38381. return ClassTreeInfo;
  38382. })();
  38383. BABYLON.ClassTreeInfo = ClassTreeInfo;
  38384. var SmartPropertyPrim = (function () {
  38385. function SmartPropertyPrim() {
  38386. this._flags = 0;
  38387. this._modelKey = null;
  38388. this._instanceDirtyFlags = 0;
  38389. this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  38390. this.animations = new Array();
  38391. }
  38392. Object.defineProperty(SmartPropertyPrim.prototype, "isDisposed", {
  38393. /**
  38394. * Check if the object is disposed or not.
  38395. * @returns true if the object is dispose, false otherwise.
  38396. */
  38397. get: function () {
  38398. return this._isFlagSet(SmartPropertyPrim.flagIsDisposed);
  38399. },
  38400. enumerable: true,
  38401. configurable: true
  38402. });
  38403. /**
  38404. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  38405. * @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.
  38406. */
  38407. SmartPropertyPrim.prototype.dispose = function () {
  38408. if (this.isDisposed) {
  38409. return false;
  38410. }
  38411. // Don't set to null, it may upset somebody...
  38412. this.animations.splice(0);
  38413. this._setFlags(SmartPropertyPrim.flagIsDisposed);
  38414. return true;
  38415. };
  38416. /**
  38417. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  38418. * Look at Sprite2D for more information
  38419. */
  38420. SmartPropertyPrim.prototype.getAnimatables = function () {
  38421. return new Array();
  38422. };
  38423. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  38424. /**
  38425. * Property giving the Model Key associated to the property.
  38426. * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
  38427. * @returns the model key string.
  38428. */
  38429. get: function () {
  38430. var _this = this;
  38431. // No need to compute it?
  38432. if (!this._isFlagSet(SmartPropertyPrim.flagModelDirty) && this._modelKey) {
  38433. return this._modelKey;
  38434. }
  38435. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  38436. var propDic = this.propDic;
  38437. propDic.forEach(function (k, v) {
  38438. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  38439. var propVal = _this[v.name];
  38440. // 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
  38441. if (propVal && propVal.constructor === Array) {
  38442. var firstVal = propVal[0];
  38443. if (!firstVal) {
  38444. propVal = 0;
  38445. }
  38446. else {
  38447. propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
  38448. }
  38449. }
  38450. modelKey += v.name + ":" + ((propVal != null) ? ((v.typeLevelCompare) ? BABYLON.Tools.getClassName(propVal) : propVal.toString()) : "[null]") + ";";
  38451. }
  38452. });
  38453. this._clearFlags(SmartPropertyPrim.flagModelDirty);
  38454. this._modelKey = modelKey;
  38455. return modelKey;
  38456. },
  38457. enumerable: true,
  38458. configurable: true
  38459. });
  38460. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  38461. /**
  38462. * States if the Primitive is dirty and should be rendered again next time.
  38463. * @returns true is dirty, false otherwise
  38464. */
  38465. get: function () {
  38466. return (this._instanceDirtyFlags !== 0) || this._areSomeFlagsSet(SmartPropertyPrim.flagModelDirty | SmartPropertyPrim.flagPositioningDirty | SmartPropertyPrim.flagLayoutDirty);
  38467. },
  38468. enumerable: true,
  38469. configurable: true
  38470. });
  38471. Object.defineProperty(SmartPropertyPrim.prototype, "propDic", {
  38472. /**
  38473. * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
  38474. * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
  38475. */
  38476. get: function () {
  38477. if (!this._propInfo) {
  38478. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  38479. if (!cti) {
  38480. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  38481. }
  38482. this._propInfo = cti.fullContent;
  38483. }
  38484. return this._propInfo;
  38485. },
  38486. enumerable: true,
  38487. configurable: true
  38488. });
  38489. SmartPropertyPrim._createPropInfo = function (target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind) {
  38490. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  38491. var node = dic.getLevelOf(target);
  38492. var propInfo = node.levelContent.get(propId.toString());
  38493. if (propInfo) {
  38494. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  38495. }
  38496. // Create, setup and add the PropInfo object to our prop dictionary
  38497. propInfo = new Prim2DPropInfo();
  38498. propInfo.id = propId;
  38499. propInfo.flagId = Math.pow(2, propId);
  38500. propInfo.kind = kind;
  38501. propInfo.name = propName;
  38502. propInfo.dirtyBoundingInfo = dirtyBoundingInfo;
  38503. propInfo.dirtyParentBoundingInfo = dirtyParentBoundingBox;
  38504. propInfo.typeLevelCompare = typeLevelCompare;
  38505. node.levelContent.add(propName, propInfo);
  38506. return propInfo;
  38507. };
  38508. SmartPropertyPrim._checkUnchanged = function (curValue, newValue) {
  38509. // Nothing to nothing: nothing to do!
  38510. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  38511. return true;
  38512. }
  38513. // Check value unchanged
  38514. if ((curValue != null) && (newValue != null)) {
  38515. if (typeof (curValue.equals) == "function") {
  38516. if (curValue.equals(newValue)) {
  38517. return true;
  38518. }
  38519. }
  38520. else {
  38521. if (curValue === newValue) {
  38522. return true;
  38523. }
  38524. }
  38525. }
  38526. return false;
  38527. };
  38528. SmartPropertyPrim.prototype.markAsDirty = function (propertyName) {
  38529. if (this.isDisposed) {
  38530. return;
  38531. }
  38532. var i = propertyName.indexOf(".");
  38533. if (i !== -1) {
  38534. propertyName = propertyName.substr(0, i);
  38535. }
  38536. var propInfo = this.propDic.get(propertyName);
  38537. if (!propInfo) {
  38538. return;
  38539. }
  38540. var newValue = this[propertyName];
  38541. this._handlePropChanged(undefined, newValue, propertyName, propInfo, propInfo.typeLevelCompare);
  38542. };
  38543. SmartPropertyPrim.prototype._boundingBoxDirty = function () {
  38544. this._setFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  38545. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  38546. if (this instanceof BABYLON.Prim2DBase) {
  38547. var curprim = this;
  38548. while (curprim) {
  38549. curprim._setFlags(SmartPropertyPrim.flagBoundingInfoDirty);
  38550. if (curprim.isSizeAuto) {
  38551. curprim.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  38552. curprim._setFlags(SmartPropertyPrim.flagPositioningDirty);
  38553. }
  38554. if (curprim instanceof BABYLON.Group2D) {
  38555. if (curprim.isRenderableGroup) {
  38556. break;
  38557. }
  38558. }
  38559. curprim = curprim.parent;
  38560. }
  38561. }
  38562. };
  38563. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  38564. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  38565. if (propInfo.dirtyBoundingInfo) {
  38566. this._boundingBoxDirty();
  38567. }
  38568. else if (propInfo.dirtyParentBoundingInfo) {
  38569. var p = this._parent;
  38570. if (p != null) {
  38571. p._boundingBoxDirty();
  38572. }
  38573. }
  38574. // Trigger property changed
  38575. var info = SmartPropertyPrim.propChangedInfo;
  38576. info.oldValue = curValue;
  38577. info.newValue = newValue;
  38578. info.propertyName = propName;
  38579. var propMask = propInfo.flagId;
  38580. this.propertyChanged.notifyObservers(info, propMask);
  38581. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  38582. if (this instanceof BABYLON.Group2D) {
  38583. this.handleGroupChanged(propInfo);
  38584. }
  38585. // Check for parent layout dirty
  38586. if (this instanceof BABYLON.Prim2DBase) {
  38587. var p = this._parent;
  38588. if (p != null && p.layoutEngine && (p.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  38589. p._setLayoutDirty();
  38590. }
  38591. }
  38592. // For type level compare, if there's a change of type it's a change of model, otherwise we issue an instance change
  38593. var instanceDirty = false;
  38594. if (typeLevelCompare && curValue != null && newValue != null) {
  38595. var cvProto = curValue.__proto__;
  38596. var nvProto = newValue.__proto__;
  38597. instanceDirty = (cvProto === nvProto);
  38598. }
  38599. // Set the dirty flags
  38600. if (!instanceDirty && (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL)) {
  38601. if (!this.isDirty) {
  38602. this._setFlags(SmartPropertyPrim.flagModelDirty);
  38603. }
  38604. }
  38605. else if (instanceDirty || (propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  38606. this.onPrimitivePropertyDirty(propMask);
  38607. }
  38608. };
  38609. SmartPropertyPrim.prototype.onPrimitivePropertyDirty = function (propFlagId) {
  38610. this.onPrimBecomesDirty();
  38611. this._instanceDirtyFlags |= propFlagId;
  38612. };
  38613. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  38614. };
  38615. /**
  38616. * Check if a given set of properties are dirty or not.
  38617. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  38618. * @return true if at least one property is dirty, false if none of them are.
  38619. */
  38620. SmartPropertyPrim.prototype.checkPropertiesDirty = function (flags) {
  38621. return (this._instanceDirtyFlags & flags) !== 0;
  38622. };
  38623. /**
  38624. * Clear a given set of properties.
  38625. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  38626. * @return the new set of property still marked as dirty
  38627. */
  38628. SmartPropertyPrim.prototype.clearPropertiesDirty = function (flags) {
  38629. this._instanceDirtyFlags &= ~flags;
  38630. return this._instanceDirtyFlags;
  38631. };
  38632. SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
  38633. this._instanceDirtyFlags = 0;
  38634. this._clearFlags(SmartPropertyPrim.flagPrimInDirtyList);
  38635. };
  38636. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  38637. /**
  38638. * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
  38639. */
  38640. get: function () {
  38641. if (this._isFlagSet(SmartPropertyPrim.flagLevelBoundingInfoDirty)) {
  38642. this.updateLevelBoundingInfo();
  38643. this._clearFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  38644. }
  38645. return this._levelBoundingInfo;
  38646. },
  38647. enumerable: true,
  38648. configurable: true
  38649. });
  38650. /**
  38651. * This method must be overridden by a given Primitive implementation to compute its boundingInfo
  38652. */
  38653. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  38654. };
  38655. /**
  38656. * Property method called when the Primitive becomes dirty
  38657. */
  38658. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  38659. };
  38660. SmartPropertyPrim._hookProperty = function (propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, kind) {
  38661. return function (target, propName, descriptor) {
  38662. var propInfo = SmartPropertyPrim._createPropInfo(target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind);
  38663. if (piStore) {
  38664. piStore(propInfo);
  38665. }
  38666. var getter = descriptor.get, setter = descriptor.set;
  38667. // Overload the property setter implementation to add our own logic
  38668. descriptor.set = function (val) {
  38669. // check for disposed first, do nothing
  38670. if (this.isDisposed) {
  38671. return;
  38672. }
  38673. var curVal = getter.call(this);
  38674. if (SmartPropertyPrim._checkUnchanged(curVal, val)) {
  38675. return;
  38676. }
  38677. // Cast the object we're working one
  38678. var prim = this;
  38679. // Change the value
  38680. setter.call(this, val);
  38681. // Notify change, dirty flags update
  38682. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  38683. };
  38684. };
  38685. };
  38686. /**
  38687. * Add an externally attached data from its key.
  38688. * This method call will fail and return false, if such key already exists.
  38689. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  38690. * @param key the unique key that identifies the data
  38691. * @param data the data object to associate to the key for this Engine instance
  38692. * @return true if no such key were already present and the data was added successfully, false otherwise
  38693. */
  38694. SmartPropertyPrim.prototype.addExternalData = function (key, data) {
  38695. if (!this._externalData) {
  38696. this._externalData = new BABYLON.StringDictionary();
  38697. }
  38698. return this._externalData.add(key, data);
  38699. };
  38700. /**
  38701. * Get an externally attached data from its key
  38702. * @param key the unique key that identifies the data
  38703. * @return the associated data, if present (can be null), or undefined if not present
  38704. */
  38705. SmartPropertyPrim.prototype.getExternalData = function (key) {
  38706. if (!this._externalData) {
  38707. return null;
  38708. }
  38709. return this._externalData.get(key);
  38710. };
  38711. /**
  38712. * Get an externally attached data from its key, create it using a factory if it's not already present
  38713. * @param key the unique key that identifies the data
  38714. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  38715. * @return the associated data, can be null if the factory returned null.
  38716. */
  38717. SmartPropertyPrim.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  38718. if (!this._externalData) {
  38719. this._externalData = new BABYLON.StringDictionary();
  38720. }
  38721. return this._externalData.getOrAddWithFactory(key, factory);
  38722. };
  38723. /**
  38724. * Remove an externally attached data from the Engine instance
  38725. * @param key the unique key that identifies the data
  38726. * @return true if the data was successfully removed, false if it doesn't exist
  38727. */
  38728. SmartPropertyPrim.prototype.removeExternalData = function (key) {
  38729. if (!this._externalData) {
  38730. return false;
  38731. }
  38732. return this._externalData.remove(key);
  38733. };
  38734. /**
  38735. * Check if a given flag is set
  38736. * @param flag the flag value
  38737. * @return true if set, false otherwise
  38738. */
  38739. SmartPropertyPrim.prototype._isFlagSet = function (flag) {
  38740. return (this._flags & flag) !== 0;
  38741. };
  38742. /**
  38743. * Check if all given flags are set
  38744. * @param flags the flags ORed
  38745. * @return true if all the flags are set, false otherwise
  38746. */
  38747. SmartPropertyPrim.prototype._areAllFlagsSet = function (flags) {
  38748. return (this._flags & flags) === flags;
  38749. };
  38750. /**
  38751. * Check if at least one flag of the given flags is set
  38752. * @param flags the flags ORed
  38753. * @return true if at least one flag is set, false otherwise
  38754. */
  38755. SmartPropertyPrim.prototype._areSomeFlagsSet = function (flags) {
  38756. return (this._flags & flags) !== 0;
  38757. };
  38758. /**
  38759. * Clear the given flags
  38760. * @param flags the flags to clear
  38761. */
  38762. SmartPropertyPrim.prototype._clearFlags = function (flags) {
  38763. this._flags &= ~flags;
  38764. };
  38765. /**
  38766. * Set the given flags to true state
  38767. * @param flags the flags ORed to set
  38768. * @return the flags state before this call
  38769. */
  38770. SmartPropertyPrim.prototype._setFlags = function (flags) {
  38771. var cur = this._flags;
  38772. this._flags |= flags;
  38773. return cur;
  38774. };
  38775. /**
  38776. * Change the state of the given flags
  38777. * @param flags the flags ORed to change
  38778. * @param state true to set them, false to clear them
  38779. */
  38780. SmartPropertyPrim.prototype._changeFlags = function (flags, state) {
  38781. if (state) {
  38782. this._flags |= flags;
  38783. }
  38784. else {
  38785. this._flags &= ~flags;
  38786. }
  38787. };
  38788. SmartPropertyPrim.propChangedInfo = new PropertyChangedInfo();
  38789. SmartPropertyPrim.flagIsDisposed = 0x0000001; // set if the object is already disposed
  38790. SmartPropertyPrim.flagLevelBoundingInfoDirty = 0x0000002; // set if the primitive's level bounding box (not including children) is dirty
  38791. SmartPropertyPrim.flagModelDirty = 0x0000004; // set if the model must be changed
  38792. SmartPropertyPrim.flagLayoutDirty = 0x0000008; // set if the layout must be computed
  38793. SmartPropertyPrim.flagLevelVisible = 0x0000010; // set if the primitive is set as visible for its level only
  38794. SmartPropertyPrim.flagBoundingInfoDirty = 0x0000020; // set if the primitive's overall bounding box (including children) is dirty
  38795. SmartPropertyPrim.flagIsPickable = 0x0000040; // set if the primitive can be picked during interaction
  38796. SmartPropertyPrim.flagIsVisible = 0x0000080; // set if the primitive is concretely visible (use the levelVisible of parents)
  38797. SmartPropertyPrim.flagVisibilityChanged = 0x0000100; // set if there was a transition between visible/hidden status
  38798. SmartPropertyPrim.flagPositioningDirty = 0x0000200; // set if the primitive positioning must be computed
  38799. SmartPropertyPrim.flagTrackedGroup = 0x0000400; // set if the group2D is tracking a scene node
  38800. SmartPropertyPrim.flagWorldCacheChanged = 0x0000800; // set if the cached bitmap of a world space canvas changed
  38801. SmartPropertyPrim.flagChildrenFlatZOrder = 0x0001000; // set if all the children (direct and indirect) will share the same Z-Order
  38802. SmartPropertyPrim.flagZOrderDirty = 0x0002000; // set if the Z-Order for this prim and its children must be recomputed
  38803. SmartPropertyPrim.flagActualOpacityDirty = 0x0004000; // set if the actualOpactity should be recomputed
  38804. SmartPropertyPrim.flagPrimInDirtyList = 0x0008000; // set if the primitive is in the primDirtyList
  38805. SmartPropertyPrim = __decorate([
  38806. BABYLON.className("SmartPropertyPrim")
  38807. ], SmartPropertyPrim);
  38808. return SmartPropertyPrim;
  38809. })();
  38810. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  38811. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  38812. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  38813. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  38814. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  38815. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_MODEL);
  38816. }
  38817. BABYLON.modelLevelProperty = modelLevelProperty;
  38818. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  38819. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  38820. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  38821. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  38822. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_INSTANCE);
  38823. }
  38824. BABYLON.instanceLevelProperty = instanceLevelProperty;
  38825. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  38826. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  38827. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  38828. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  38829. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_DYNAMIC);
  38830. }
  38831. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  38832. })(BABYLON || (BABYLON = {}));
  38833. var BABYLON;
  38834. (function (BABYLON) {
  38835. var PrepareRender2DContext = (function () {
  38836. function PrepareRender2DContext() {
  38837. this.forceRefreshPrimitive = false;
  38838. }
  38839. return PrepareRender2DContext;
  38840. })();
  38841. BABYLON.PrepareRender2DContext = PrepareRender2DContext;
  38842. var Render2DContext = (function () {
  38843. function Render2DContext(renderMode) {
  38844. this._renderMode = renderMode;
  38845. this.useInstancing = false;
  38846. this.groupInfoPartData = null;
  38847. this.partDataStartIndex = this.partDataEndIndex = null;
  38848. this.instancedBuffers = null;
  38849. }
  38850. Object.defineProperty(Render2DContext.prototype, "renderMode", {
  38851. /**
  38852. * Define which render Mode should be used to render the primitive: one of Render2DContext.RenderModeXxxx property
  38853. */
  38854. get: function () {
  38855. return this._renderMode;
  38856. },
  38857. enumerable: true,
  38858. configurable: true
  38859. });
  38860. Object.defineProperty(Render2DContext, "RenderModeOpaque", {
  38861. /**
  38862. * The set of primitives to render is opaque.
  38863. * This is the first rendering pass. All Opaque primitives are rendered. Depth Compare and Write are both enabled.
  38864. */
  38865. get: function () {
  38866. return Render2DContext._renderModeOpaque;
  38867. },
  38868. enumerable: true,
  38869. configurable: true
  38870. });
  38871. Object.defineProperty(Render2DContext, "RenderModeAlphaTest", {
  38872. /**
  38873. * The set of primitives to render is using Alpha Test (aka masking).
  38874. * 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.
  38875. */
  38876. get: function () {
  38877. return Render2DContext._renderModeAlphaTest;
  38878. },
  38879. enumerable: true,
  38880. configurable: true
  38881. });
  38882. Object.defineProperty(Render2DContext, "RenderModeTransparent", {
  38883. /**
  38884. * The set of primitives to render is transparent.
  38885. * 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.
  38886. */
  38887. get: function () {
  38888. return Render2DContext._renderModeTransparent;
  38889. },
  38890. enumerable: true,
  38891. configurable: true
  38892. });
  38893. Render2DContext._renderModeOpaque = 1;
  38894. Render2DContext._renderModeAlphaTest = 2;
  38895. Render2DContext._renderModeTransparent = 3;
  38896. return Render2DContext;
  38897. })();
  38898. BABYLON.Render2DContext = Render2DContext;
  38899. /**
  38900. * This class store information for the pointerEventObservable Observable.
  38901. * 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.
  38902. */
  38903. var PrimitivePointerInfo = (function () {
  38904. function PrimitivePointerInfo() {
  38905. this.primitivePointerPos = BABYLON.Vector2.Zero();
  38906. this.tilt = BABYLON.Vector2.Zero();
  38907. this.cancelBubble = false;
  38908. }
  38909. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  38910. // 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.
  38911. /**
  38912. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  38913. * Bubbles: yes
  38914. */
  38915. get: function () {
  38916. return PrimitivePointerInfo._pointerOver;
  38917. },
  38918. enumerable: true,
  38919. configurable: true
  38920. });
  38921. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  38922. /**
  38923. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  38924. * Bubbles: no
  38925. */
  38926. get: function () {
  38927. return PrimitivePointerInfo._pointerEnter;
  38928. },
  38929. enumerable: true,
  38930. configurable: true
  38931. });
  38932. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  38933. /**
  38934. * 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.
  38935. * Bubbles: yes
  38936. */
  38937. get: function () {
  38938. return PrimitivePointerInfo._pointerDown;
  38939. },
  38940. enumerable: true,
  38941. configurable: true
  38942. });
  38943. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  38944. /**
  38945. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  38946. * Bubbles: yes
  38947. */
  38948. get: function () {
  38949. return PrimitivePointerInfo._pointerMouseWheel;
  38950. },
  38951. enumerable: true,
  38952. configurable: true
  38953. });
  38954. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  38955. /**
  38956. * 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.
  38957. * Bubbles: yes
  38958. */
  38959. get: function () {
  38960. return PrimitivePointerInfo._pointerMove;
  38961. },
  38962. enumerable: true,
  38963. configurable: true
  38964. });
  38965. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  38966. /**
  38967. * 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.
  38968. * Bubbles: yes
  38969. */
  38970. get: function () {
  38971. return PrimitivePointerInfo._pointerUp;
  38972. },
  38973. enumerable: true,
  38974. configurable: true
  38975. });
  38976. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  38977. /**
  38978. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  38979. * Bubbles: yes
  38980. */
  38981. get: function () {
  38982. return PrimitivePointerInfo._pointerOut;
  38983. },
  38984. enumerable: true,
  38985. configurable: true
  38986. });
  38987. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  38988. /**
  38989. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  38990. * Bubbles: no
  38991. */
  38992. get: function () {
  38993. return PrimitivePointerInfo._pointerLeave;
  38994. },
  38995. enumerable: true,
  38996. configurable: true
  38997. });
  38998. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  38999. /**
  39000. * 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.
  39001. * Bubbles: yes
  39002. */
  39003. get: function () {
  39004. return PrimitivePointerInfo._pointerGotCapture;
  39005. },
  39006. enumerable: true,
  39007. configurable: true
  39008. });
  39009. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  39010. /**
  39011. * This event type is raised after pointer capture is released for a pointer.
  39012. * Bubbles: yes
  39013. */
  39014. get: function () {
  39015. return PrimitivePointerInfo._pointerLostCapture;
  39016. },
  39017. enumerable: true,
  39018. configurable: true
  39019. });
  39020. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  39021. get: function () {
  39022. return PrimitivePointerInfo._mouseWheelPrecision;
  39023. },
  39024. enumerable: true,
  39025. configurable: true
  39026. });
  39027. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  39028. this.relatedTarget = prim;
  39029. this.relatedTargetPointerPos = primPointerPos;
  39030. };
  39031. PrimitivePointerInfo.getEventTypeName = function (mask) {
  39032. switch (mask) {
  39033. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  39034. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  39035. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  39036. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  39037. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  39038. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  39039. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  39040. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  39041. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  39042. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  39043. }
  39044. };
  39045. PrimitivePointerInfo._pointerOver = 0x0001;
  39046. PrimitivePointerInfo._pointerEnter = 0x0002;
  39047. PrimitivePointerInfo._pointerDown = 0x0004;
  39048. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  39049. PrimitivePointerInfo._pointerMove = 0x0010;
  39050. PrimitivePointerInfo._pointerUp = 0x0020;
  39051. PrimitivePointerInfo._pointerOut = 0x0040;
  39052. PrimitivePointerInfo._pointerLeave = 0x0080;
  39053. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  39054. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  39055. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  39056. return PrimitivePointerInfo;
  39057. })();
  39058. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  39059. /**
  39060. * Defines the horizontal and vertical alignment information for a Primitive.
  39061. */
  39062. var PrimitiveAlignment = (function () {
  39063. function PrimitiveAlignment(changeCallback) {
  39064. this._changedCallback = changeCallback;
  39065. this._horizontal = PrimitiveAlignment.AlignLeft;
  39066. this._vertical = PrimitiveAlignment.AlignBottom;
  39067. }
  39068. Object.defineProperty(PrimitiveAlignment, "AlignLeft", {
  39069. /**
  39070. * Alignment is made relative to the left edge of the Primitive. Valid for horizontal alignment only.
  39071. */
  39072. get: function () { return PrimitiveAlignment._AlignLeft; },
  39073. enumerable: true,
  39074. configurable: true
  39075. });
  39076. Object.defineProperty(PrimitiveAlignment, "AlignTop", {
  39077. /**
  39078. * Alignment is made relative to the top edge of the Primitive. Valid for vertical alignment only.
  39079. */
  39080. get: function () { return PrimitiveAlignment._AlignTop; },
  39081. enumerable: true,
  39082. configurable: true
  39083. });
  39084. Object.defineProperty(PrimitiveAlignment, "AlignRight", {
  39085. /**
  39086. * Alignment is made relative to the right edge of the Primitive. Valid for horizontal alignment only.
  39087. */
  39088. get: function () { return PrimitiveAlignment._AlignRight; },
  39089. enumerable: true,
  39090. configurable: true
  39091. });
  39092. Object.defineProperty(PrimitiveAlignment, "AlignBottom", {
  39093. /**
  39094. * Alignment is made relative to the bottom edge of the Primitive. Valid for vertical alignment only.
  39095. */
  39096. get: function () { return PrimitiveAlignment._AlignBottom; },
  39097. enumerable: true,
  39098. configurable: true
  39099. });
  39100. Object.defineProperty(PrimitiveAlignment, "AlignCenter", {
  39101. /**
  39102. * Alignment is made to center the content from equal distance to the opposite edges of the Primitive
  39103. */
  39104. get: function () { return PrimitiveAlignment._AlignCenter; },
  39105. enumerable: true,
  39106. configurable: true
  39107. });
  39108. Object.defineProperty(PrimitiveAlignment, "AlignStretch", {
  39109. /**
  39110. * The content is stretched toward the opposite edges of the Primitive
  39111. */
  39112. get: function () { return PrimitiveAlignment._AlignStretch; },
  39113. enumerable: true,
  39114. configurable: true
  39115. });
  39116. Object.defineProperty(PrimitiveAlignment.prototype, "horizontal", {
  39117. /**
  39118. * Get/set the horizontal alignment. Use one of the AlignXXX static properties of this class
  39119. */
  39120. get: function () {
  39121. return this._horizontal;
  39122. },
  39123. set: function (value) {
  39124. if (this._horizontal === value) {
  39125. return;
  39126. }
  39127. this._horizontal = value;
  39128. this._changedCallback();
  39129. },
  39130. enumerable: true,
  39131. configurable: true
  39132. });
  39133. Object.defineProperty(PrimitiveAlignment.prototype, "vertical", {
  39134. /**
  39135. * Get/set the vertical alignment. Use one of the AlignXXX static properties of this class
  39136. */
  39137. get: function () {
  39138. return this._vertical;
  39139. },
  39140. set: function (value) {
  39141. if (this._vertical === value) {
  39142. return;
  39143. }
  39144. this._vertical = value;
  39145. this._changedCallback();
  39146. },
  39147. enumerable: true,
  39148. configurable: true
  39149. });
  39150. /**
  39151. * Set the horizontal alignment from a string value.
  39152. * @param text can be either: 'left','right','center','stretch'
  39153. */
  39154. PrimitiveAlignment.prototype.setHorizontal = function (text) {
  39155. var v = text.trim().toLocaleLowerCase();
  39156. switch (v) {
  39157. case "left":
  39158. this.horizontal = PrimitiveAlignment.AlignLeft;
  39159. return;
  39160. case "right":
  39161. this.horizontal = PrimitiveAlignment.AlignRight;
  39162. return;
  39163. case "center":
  39164. this.horizontal = PrimitiveAlignment.AlignCenter;
  39165. return;
  39166. case "stretch":
  39167. this.horizontal = PrimitiveAlignment.AlignStretch;
  39168. return;
  39169. }
  39170. };
  39171. /**
  39172. * Set the vertical alignment from a string value.
  39173. * @param text can be either: 'top','bottom','center','stretch'
  39174. */
  39175. PrimitiveAlignment.prototype.setVertical = function (text) {
  39176. var v = text.trim().toLocaleLowerCase();
  39177. switch (v) {
  39178. case "top":
  39179. this.vertical = PrimitiveAlignment.AlignTop;
  39180. return;
  39181. case "bottom":
  39182. this.vertical = PrimitiveAlignment.AlignBottom;
  39183. return;
  39184. case "center":
  39185. this.vertical = PrimitiveAlignment.AlignCenter;
  39186. return;
  39187. case "stretch":
  39188. this.vertical = PrimitiveAlignment.AlignStretch;
  39189. return;
  39190. }
  39191. };
  39192. /**
  39193. * Set the horizontal and or vertical alignments from a string value.
  39194. * @param text can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
  39195. */
  39196. PrimitiveAlignment.prototype.fromString = function (value) {
  39197. var m = value.trim().split(",");
  39198. for (var _i = 0; _i < m.length; _i++) {
  39199. var v = m[_i];
  39200. v = v.toLocaleLowerCase().trim();
  39201. // Horizontal
  39202. var i = v.indexOf("h:");
  39203. if (i === -1) {
  39204. i = v.indexOf("horizontal:");
  39205. }
  39206. if (i !== -1) {
  39207. v = v.substr(v.indexOf(":") + 1);
  39208. this.setHorizontal(v);
  39209. continue;
  39210. }
  39211. // Vertical
  39212. i = v.indexOf("v:");
  39213. if (i === -1) {
  39214. i = v.indexOf("vertical:");
  39215. }
  39216. if (i !== -1) {
  39217. v = v.substr(v.indexOf(":") + 1);
  39218. this.setVertical(v);
  39219. continue;
  39220. }
  39221. }
  39222. };
  39223. PrimitiveAlignment._AlignLeft = 1;
  39224. PrimitiveAlignment._AlignTop = 1; // Same as left
  39225. PrimitiveAlignment._AlignRight = 2;
  39226. PrimitiveAlignment._AlignBottom = 2; // Same as right
  39227. PrimitiveAlignment._AlignCenter = 3;
  39228. PrimitiveAlignment._AlignStretch = 4;
  39229. return PrimitiveAlignment;
  39230. })();
  39231. BABYLON.PrimitiveAlignment = PrimitiveAlignment;
  39232. /**
  39233. * Stores information about a Primitive that was intersected
  39234. */
  39235. var PrimitiveIntersectedInfo = (function () {
  39236. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  39237. this.prim = prim;
  39238. this.intersectionLocation = intersectionLocation;
  39239. }
  39240. return PrimitiveIntersectedInfo;
  39241. })();
  39242. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  39243. /**
  39244. * Define a thickness toward every edges of a Primitive to allow margin and padding.
  39245. * The thickness can be expressed as pixels, percentages, inherit the value of the parent primitive or be auto.
  39246. */
  39247. var PrimitiveThickness = (function () {
  39248. function PrimitiveThickness(parentAccess, changedCallback) {
  39249. this._parentAccess = parentAccess;
  39250. this._changedCallback = changedCallback;
  39251. this._pixels = new Array(4);
  39252. this._percentages = new Array(4);
  39253. this._setType(0, PrimitiveThickness.Auto);
  39254. this._setType(1, PrimitiveThickness.Auto);
  39255. this._setType(2, PrimitiveThickness.Auto);
  39256. this._setType(3, PrimitiveThickness.Auto);
  39257. this._pixels[0] = 0;
  39258. this._pixels[1] = 0;
  39259. this._pixels[2] = 0;
  39260. this._pixels[3] = 0;
  39261. }
  39262. /**
  39263. * Set the thickness from a string value
  39264. * @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.
  39265. * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39266. */
  39267. PrimitiveThickness.prototype.fromString = function (thickness) {
  39268. this._clear();
  39269. var m = thickness.trim().split(",");
  39270. // Special case, one value to apply to all edges
  39271. if (m.length === 1 && thickness.indexOf(":") === -1) {
  39272. this._setStringValue(m[0], 0, false);
  39273. this._setStringValue(m[0], 1, false);
  39274. this._setStringValue(m[0], 2, false);
  39275. this._setStringValue(m[0], 3, false);
  39276. this._changedCallback();
  39277. return;
  39278. }
  39279. var res = false;
  39280. for (var _i = 0; _i < m.length; _i++) {
  39281. var cm = m[_i];
  39282. res = this._extractString(cm, false) || res;
  39283. }
  39284. if (!res) {
  39285. throw new Error("Can't parse the string to create a PrimitiveMargin object, format must be: 'top: <value>, left:<value>, right:<value>, bottom:<value>");
  39286. }
  39287. // Check the margin that weren't set and set them in auto
  39288. if ((this._flags & 0x000F) === 0)
  39289. this._flags |= PrimitiveThickness.Pixel << 0;
  39290. if ((this._flags & 0x00F0) === 0)
  39291. this._flags |= PrimitiveThickness.Pixel << 4;
  39292. if ((this._flags & 0x0F00) === 0)
  39293. this._flags |= PrimitiveThickness.Pixel << 8;
  39294. if ((this._flags & 0xF000) === 0)
  39295. this._flags |= PrimitiveThickness.Pixel << 12;
  39296. this._changedCallback();
  39297. };
  39298. /**
  39299. * Set the thickness from multiple string
  39300. * Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39301. * @param top the top thickness to set
  39302. * @param left the left thickness to set
  39303. * @param right the right thickness to set
  39304. * @param bottom the bottom thickness to set
  39305. */
  39306. PrimitiveThickness.prototype.fromStrings = function (top, left, right, bottom) {
  39307. this._clear();
  39308. this._setStringValue(top, 0, false);
  39309. this._setStringValue(left, 1, false);
  39310. this._setStringValue(right, 2, false);
  39311. this._setStringValue(bottom, 3, false);
  39312. this._changedCallback();
  39313. return this;
  39314. };
  39315. /**
  39316. * Set the thickness from pixel values
  39317. * @param top the top thickness in pixels to set
  39318. * @param left the left thickness in pixels to set
  39319. * @param right the right thickness in pixels to set
  39320. * @param bottom the bottom thickness in pixels to set
  39321. */
  39322. PrimitiveThickness.prototype.fromPixels = function (top, left, right, bottom) {
  39323. this._clear();
  39324. this._pixels[0] = top;
  39325. this._pixels[1] = left;
  39326. this._pixels[2] = right;
  39327. this._pixels[3] = bottom;
  39328. this._changedCallback();
  39329. return this;
  39330. };
  39331. /**
  39332. * Apply the same pixel value to all edges
  39333. * @param margin the value to set, in pixels.
  39334. */
  39335. PrimitiveThickness.prototype.fromUniformPixels = function (margin) {
  39336. this._clear();
  39337. this._pixels[0] = margin;
  39338. this._pixels[1] = margin;
  39339. this._pixels[2] = margin;
  39340. this._pixels[3] = margin;
  39341. this._changedCallback();
  39342. return this;
  39343. };
  39344. /**
  39345. * Set all edges in auto
  39346. */
  39347. PrimitiveThickness.prototype.auto = function () {
  39348. this._clear();
  39349. this._flags = (PrimitiveThickness.Auto << 0) | (PrimitiveThickness.Auto << 4) | (PrimitiveThickness.Auto << 8) | (PrimitiveThickness.Auto << 12);
  39350. this._pixels[0] = 0;
  39351. this._pixels[1] = 0;
  39352. this._pixels[2] = 0;
  39353. this._pixels[3] = 0;
  39354. this._changedCallback();
  39355. return this;
  39356. };
  39357. PrimitiveThickness.prototype._clear = function () {
  39358. this._flags = 0;
  39359. this._pixels[0] = 0;
  39360. this._pixels[1] = 0;
  39361. this._pixels[2] = 0;
  39362. this._pixels[3] = 0;
  39363. this._percentages[0] = null;
  39364. this._percentages[1] = null;
  39365. this._percentages[2] = null;
  39366. this._percentages[3] = null;
  39367. };
  39368. PrimitiveThickness.prototype._extractString = function (value, emitChanged) {
  39369. var v = value.trim().toLocaleLowerCase();
  39370. if (v.indexOf("top:") === 0) {
  39371. v = v.substr(4).trim();
  39372. return this._setStringValue(v, 0, emitChanged);
  39373. }
  39374. if (v.indexOf("left:") === 0) {
  39375. v = v.substr(5).trim();
  39376. return this._setStringValue(v, 1, emitChanged);
  39377. }
  39378. if (v.indexOf("right:") === 0) {
  39379. v = v.substr(6).trim();
  39380. return this._setStringValue(v, 2, emitChanged);
  39381. }
  39382. if (v.indexOf("bottom:") === 0) {
  39383. v = v.substr(7).trim();
  39384. return this._setStringValue(v, 3, emitChanged);
  39385. }
  39386. return false;
  39387. };
  39388. PrimitiveThickness.prototype._setStringValue = function (value, index, emitChanged) {
  39389. // Check for auto
  39390. var v = value.trim().toLocaleLowerCase();
  39391. if (v === "auto") {
  39392. if (this._isType(index, PrimitiveThickness.Auto)) {
  39393. return true;
  39394. }
  39395. this._setType(index, PrimitiveThickness.Auto);
  39396. this._pixels[index] = 0;
  39397. if (emitChanged) {
  39398. this._changedCallback();
  39399. }
  39400. }
  39401. else if (v === "inherit") {
  39402. if (this._isType(index, PrimitiveThickness.Inherit)) {
  39403. return true;
  39404. }
  39405. this._setType(index, PrimitiveThickness.Inherit);
  39406. this._pixels[index] = null;
  39407. if (emitChanged) {
  39408. this._changedCallback();
  39409. }
  39410. }
  39411. else {
  39412. var pI = v.indexOf("%");
  39413. // Check for percentage
  39414. if (pI !== -1) {
  39415. var n_1 = v.substr(0, pI);
  39416. var number_1 = Math.round(Number(n_1)) / 100; // Normalize the percentage to [0;1] with a 0.01 precision
  39417. if (this._isType(index, PrimitiveThickness.Percentage) && (this._percentages[index] === number_1)) {
  39418. return true;
  39419. }
  39420. this._setType(index, PrimitiveThickness.Percentage);
  39421. if (isNaN(number_1)) {
  39422. return false;
  39423. }
  39424. this._percentages[index] = number_1;
  39425. if (emitChanged) {
  39426. this._changedCallback();
  39427. }
  39428. return true;
  39429. }
  39430. // Check for pixel
  39431. var n;
  39432. pI = v.indexOf("px");
  39433. if (pI !== -1) {
  39434. n = v.substr(0, pI).trim();
  39435. }
  39436. else {
  39437. n = v;
  39438. }
  39439. var number = Number(n);
  39440. if (this._isType(index, PrimitiveThickness.Pixel) && (this._pixels[index] === number)) {
  39441. return true;
  39442. }
  39443. if (isNaN(number)) {
  39444. return false;
  39445. }
  39446. this._pixels[index] = number;
  39447. this._setType(index, PrimitiveThickness.Pixel);
  39448. if (emitChanged) {
  39449. this._changedCallback();
  39450. }
  39451. return true;
  39452. }
  39453. };
  39454. PrimitiveThickness.prototype._setPixels = function (value, index, emitChanged) {
  39455. // 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
  39456. value = Math.round(value);
  39457. if (this._isType(index, PrimitiveThickness.Pixel) && this._pixels[index] === value) {
  39458. return;
  39459. }
  39460. this._setType(index, PrimitiveThickness.Pixel);
  39461. this._pixels[index] = value;
  39462. if (emitChanged) {
  39463. this._changedCallback();
  39464. }
  39465. };
  39466. PrimitiveThickness.prototype._setPercentage = function (value, index, emitChanged) {
  39467. // Clip Value to bounds
  39468. value = Math.min(1, value);
  39469. value = Math.max(0, value);
  39470. value = Math.round(value * 100) / 100; // 0.01 precision
  39471. if (this._isType(index, PrimitiveThickness.Percentage) && this._percentages[index] === value) {
  39472. return;
  39473. }
  39474. this._setType(index, PrimitiveThickness.Percentage);
  39475. this._percentages[index] = value;
  39476. if (emitChanged) {
  39477. this._changedCallback();
  39478. }
  39479. };
  39480. PrimitiveThickness.prototype._getStringValue = function (index) {
  39481. var f = (this._flags >> (index * 4)) & 0xF;
  39482. switch (f) {
  39483. case PrimitiveThickness.Auto:
  39484. return "auto";
  39485. case PrimitiveThickness.Pixel:
  39486. return this._pixels[index] + "px";
  39487. case PrimitiveThickness.Percentage:
  39488. return this._percentages[index] * 100 + "%";
  39489. case PrimitiveThickness.Inherit:
  39490. return "inherit";
  39491. }
  39492. return "";
  39493. };
  39494. PrimitiveThickness.prototype._isType = function (index, type) {
  39495. var f = (this._flags >> (index * 4)) & 0xF;
  39496. return f === type;
  39497. };
  39498. PrimitiveThickness.prototype._getType = function (index, processInherit) {
  39499. var t = (this._flags >> (index * 4)) & 0xF;
  39500. if (processInherit && (t === PrimitiveThickness.Inherit)) {
  39501. var p = this._parentAccess();
  39502. if (p) {
  39503. return p._getType(index, true);
  39504. }
  39505. return PrimitiveThickness.Auto;
  39506. }
  39507. return t;
  39508. };
  39509. PrimitiveThickness.prototype._setType = function (index, type) {
  39510. this._flags &= ~(0xF << (index * 4));
  39511. this._flags |= type << (index * 4);
  39512. };
  39513. PrimitiveThickness.prototype.setTop = function (value) {
  39514. if (typeof value === "string") {
  39515. this._setStringValue(value, 0, true);
  39516. }
  39517. else {
  39518. this.topPixels = value;
  39519. }
  39520. };
  39521. PrimitiveThickness.prototype.setLeft = function (value) {
  39522. if (typeof value === "string") {
  39523. this._setStringValue(value, 1, true);
  39524. }
  39525. else {
  39526. this.leftPixels = value;
  39527. }
  39528. };
  39529. PrimitiveThickness.prototype.setRight = function (value) {
  39530. if (typeof value === "string") {
  39531. this._setStringValue(value, 2, true);
  39532. }
  39533. else {
  39534. this.rightPixels = value;
  39535. }
  39536. };
  39537. PrimitiveThickness.prototype.setBottom = function (value) {
  39538. if (typeof value === "string") {
  39539. this._setStringValue(value, 3, true);
  39540. }
  39541. else {
  39542. this.bottomPixels = value;
  39543. }
  39544. };
  39545. Object.defineProperty(PrimitiveThickness.prototype, "top", {
  39546. /**
  39547. * Get/set the top thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39548. */
  39549. get: function () {
  39550. return this._getStringValue(0);
  39551. },
  39552. set: function (value) {
  39553. this._setStringValue(value, 0, true);
  39554. },
  39555. enumerable: true,
  39556. configurable: true
  39557. });
  39558. Object.defineProperty(PrimitiveThickness.prototype, "left", {
  39559. /**
  39560. * Get/set the left thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39561. */
  39562. get: function () {
  39563. return this._getStringValue(1);
  39564. },
  39565. set: function (value) {
  39566. this._setStringValue(value, 1, true);
  39567. },
  39568. enumerable: true,
  39569. configurable: true
  39570. });
  39571. Object.defineProperty(PrimitiveThickness.prototype, "right", {
  39572. /**
  39573. * Get/set the right thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39574. */
  39575. get: function () {
  39576. return this._getStringValue(2);
  39577. },
  39578. set: function (value) {
  39579. this._setStringValue(value, 2, true);
  39580. },
  39581. enumerable: true,
  39582. configurable: true
  39583. });
  39584. Object.defineProperty(PrimitiveThickness.prototype, "bottom", {
  39585. /**
  39586. * Get/set the bottom thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39587. */
  39588. get: function () {
  39589. return this._getStringValue(3);
  39590. },
  39591. set: function (value) {
  39592. this._setStringValue(value, 3, true);
  39593. },
  39594. enumerable: true,
  39595. configurable: true
  39596. });
  39597. Object.defineProperty(PrimitiveThickness.prototype, "topPixels", {
  39598. /**
  39599. * Get/set the top thickness in pixel.
  39600. */
  39601. get: function () {
  39602. return this._pixels[0];
  39603. },
  39604. set: function (value) {
  39605. this._setPixels(value, 0, true);
  39606. },
  39607. enumerable: true,
  39608. configurable: true
  39609. });
  39610. Object.defineProperty(PrimitiveThickness.prototype, "leftPixels", {
  39611. /**
  39612. * Get/set the left thickness in pixel.
  39613. */
  39614. get: function () {
  39615. return this._pixels[1];
  39616. },
  39617. set: function (value) {
  39618. this._setPixels(value, 1, true);
  39619. },
  39620. enumerable: true,
  39621. configurable: true
  39622. });
  39623. Object.defineProperty(PrimitiveThickness.prototype, "rightPixels", {
  39624. /**
  39625. * Get/set the right thickness in pixel.
  39626. */
  39627. get: function () {
  39628. return this._pixels[2];
  39629. },
  39630. set: function (value) {
  39631. this._setPixels(value, 2, true);
  39632. },
  39633. enumerable: true,
  39634. configurable: true
  39635. });
  39636. Object.defineProperty(PrimitiveThickness.prototype, "bottomPixels", {
  39637. /**
  39638. * Get/set the bottom thickness in pixel.
  39639. */
  39640. get: function () {
  39641. return this._pixels[3];
  39642. },
  39643. set: function (value) {
  39644. this._setPixels(value, 3, true);
  39645. },
  39646. enumerable: true,
  39647. configurable: true
  39648. });
  39649. Object.defineProperty(PrimitiveThickness.prototype, "topPercentage", {
  39650. /**
  39651. * Get/set the top thickness in percentage.
  39652. * The get will return a valid value only if the edge type is percentage.
  39653. * The Set will change the edge mode if needed
  39654. */
  39655. get: function () {
  39656. return this._percentages[0];
  39657. },
  39658. set: function (value) {
  39659. this._setPercentage(value, 0, true);
  39660. },
  39661. enumerable: true,
  39662. configurable: true
  39663. });
  39664. Object.defineProperty(PrimitiveThickness.prototype, "leftPercentage", {
  39665. /**
  39666. * Get/set the left thickness in percentage.
  39667. * The get will return a valid value only if the edge mode is percentage.
  39668. * The Set will change the edge mode if needed
  39669. */
  39670. get: function () {
  39671. return this._percentages[1];
  39672. },
  39673. set: function (value) {
  39674. this._setPercentage(value, 1, true);
  39675. },
  39676. enumerable: true,
  39677. configurable: true
  39678. });
  39679. Object.defineProperty(PrimitiveThickness.prototype, "rightPercentage", {
  39680. /**
  39681. * Get/set the right thickness in percentage.
  39682. * The get will return a valid value only if the edge mode is percentage.
  39683. * The Set will change the edge mode if needed
  39684. */
  39685. get: function () {
  39686. return this._percentages[2];
  39687. },
  39688. set: function (value) {
  39689. this._setPercentage(value, 2, true);
  39690. },
  39691. enumerable: true,
  39692. configurable: true
  39693. });
  39694. Object.defineProperty(PrimitiveThickness.prototype, "bottomPercentage", {
  39695. /**
  39696. * Get/set the bottom thickness in percentage.
  39697. * The get will return a valid value only if the edge mode is percentage.
  39698. * The Set will change the edge mode if needed
  39699. */
  39700. get: function () {
  39701. return this._percentages[3];
  39702. },
  39703. set: function (value) {
  39704. this._setPercentage(value, 3, true);
  39705. },
  39706. enumerable: true,
  39707. configurable: true
  39708. });
  39709. Object.defineProperty(PrimitiveThickness.prototype, "topMode", {
  39710. /**
  39711. * Get/set the top mode. The setter shouldn't be used, other setters with value should be preferred
  39712. */
  39713. get: function () {
  39714. return this._getType(0, false);
  39715. },
  39716. set: function (mode) {
  39717. this._setType(0, mode);
  39718. },
  39719. enumerable: true,
  39720. configurable: true
  39721. });
  39722. Object.defineProperty(PrimitiveThickness.prototype, "leftMode", {
  39723. /**
  39724. * Get/set the left mode. The setter shouldn't be used, other setters with value should be preferred
  39725. */
  39726. get: function () {
  39727. return this._getType(1, false);
  39728. },
  39729. set: function (mode) {
  39730. this._setType(1, mode);
  39731. },
  39732. enumerable: true,
  39733. configurable: true
  39734. });
  39735. Object.defineProperty(PrimitiveThickness.prototype, "rightMode", {
  39736. /**
  39737. * Get/set the right mode. The setter shouldn't be used, other setters with value should be preferred
  39738. */
  39739. get: function () {
  39740. return this._getType(2, false);
  39741. },
  39742. set: function (mode) {
  39743. this._setType(2, mode);
  39744. },
  39745. enumerable: true,
  39746. configurable: true
  39747. });
  39748. Object.defineProperty(PrimitiveThickness.prototype, "bottomMode", {
  39749. /**
  39750. * Get/set the bottom mode. The setter shouldn't be used, other setters with value should be preferred
  39751. */
  39752. get: function () {
  39753. return this._getType(3, false);
  39754. },
  39755. set: function (mode) {
  39756. this._setType(3, mode);
  39757. },
  39758. enumerable: true,
  39759. configurable: true
  39760. });
  39761. PrimitiveThickness.prototype._computePixels = function (index, sourceArea, emitChanged) {
  39762. var type = this._getType(index, false);
  39763. if (type === PrimitiveThickness.Inherit) {
  39764. this._parentAccess()._computePixels(index, sourceArea, emitChanged);
  39765. return;
  39766. }
  39767. if (type !== PrimitiveThickness.Percentage) {
  39768. return;
  39769. }
  39770. var pixels = ((index === 0 || index === 3) ? sourceArea.height : sourceArea.width) * this._percentages[index];
  39771. this._pixels[index] = pixels;
  39772. if (emitChanged) {
  39773. this._changedCallback();
  39774. }
  39775. };
  39776. /**
  39777. * Compute the positioning/size of an area considering the thickness of this object and a given alignment
  39778. * @param sourceArea the source area
  39779. * @param contentSize the content size to position/resize
  39780. * @param alignment the alignment setting
  39781. * @param dstOffset the position of the content
  39782. * @param dstArea the new size of the content
  39783. */
  39784. PrimitiveThickness.prototype.computeWithAlignment = function (sourceArea, contentSize, alignment, dstOffset, dstArea) {
  39785. // Fetch some data
  39786. var topType = this._getType(0, true);
  39787. var leftType = this._getType(1, true);
  39788. var rightType = this._getType(2, true);
  39789. var bottomType = this._getType(3, true);
  39790. var hasWidth = contentSize && (contentSize.width != null);
  39791. var hasHeight = contentSize && (contentSize.height != null);
  39792. var width = hasWidth ? contentSize.width : 0;
  39793. var height = hasHeight ? contentSize.height : 0;
  39794. var isTopAuto = topType === PrimitiveThickness.Auto;
  39795. var isLeftAuto = leftType === PrimitiveThickness.Auto;
  39796. var isRightAuto = rightType === PrimitiveThickness.Auto;
  39797. var isBottomAuto = bottomType === PrimitiveThickness.Auto;
  39798. switch (alignment.horizontal) {
  39799. case PrimitiveAlignment.AlignLeft:
  39800. {
  39801. if (isLeftAuto) {
  39802. dstOffset.x = 0;
  39803. }
  39804. else {
  39805. this._computePixels(1, sourceArea, true);
  39806. dstOffset.x = this.leftPixels;
  39807. }
  39808. dstArea.width = width;
  39809. break;
  39810. }
  39811. case PrimitiveAlignment.AlignRight:
  39812. {
  39813. if (isRightAuto) {
  39814. dstOffset.x = Math.round(sourceArea.width - width);
  39815. }
  39816. else {
  39817. this._computePixels(2, sourceArea, true);
  39818. dstOffset.x = Math.round(sourceArea.width - (width + this.rightPixels));
  39819. }
  39820. dstArea.width = width;
  39821. break;
  39822. }
  39823. case PrimitiveAlignment.AlignStretch:
  39824. {
  39825. if (isLeftAuto) {
  39826. dstOffset.x = 0;
  39827. }
  39828. else {
  39829. this._computePixels(1, sourceArea, true);
  39830. dstOffset.x = this.leftPixels;
  39831. }
  39832. var right = 0;
  39833. if (!isRightAuto) {
  39834. this._computePixels(2, sourceArea, true);
  39835. right = this.rightPixels;
  39836. }
  39837. dstArea.width = sourceArea.width - (dstOffset.x + right);
  39838. break;
  39839. }
  39840. case PrimitiveAlignment.AlignCenter:
  39841. {
  39842. if (!isLeftAuto) {
  39843. this._computePixels(1, sourceArea, true);
  39844. }
  39845. if (!isRightAuto) {
  39846. this._computePixels(2, sourceArea, true);
  39847. }
  39848. var offset = (isLeftAuto ? 0 : this.leftPixels) - (isRightAuto ? 0 : this.rightPixels);
  39849. dstOffset.x = Math.round(((sourceArea.width - width) / 2) + offset);
  39850. dstArea.width = width;
  39851. break;
  39852. }
  39853. }
  39854. switch (alignment.vertical) {
  39855. case PrimitiveAlignment.AlignTop:
  39856. {
  39857. if (isTopAuto) {
  39858. dstOffset.y = sourceArea.height - height;
  39859. }
  39860. else {
  39861. this._computePixels(0, sourceArea, true);
  39862. dstOffset.y = Math.round(sourceArea.height - (height + this.topPixels));
  39863. }
  39864. dstArea.height = height;
  39865. break;
  39866. }
  39867. case PrimitiveAlignment.AlignBottom:
  39868. {
  39869. if (isBottomAuto) {
  39870. dstOffset.y = 0;
  39871. }
  39872. else {
  39873. this._computePixels(3, sourceArea, true);
  39874. dstOffset.y = this.bottomPixels;
  39875. }
  39876. dstArea.height = height;
  39877. break;
  39878. }
  39879. case PrimitiveAlignment.AlignStretch:
  39880. {
  39881. if (isBottomAuto) {
  39882. dstOffset.y = 0;
  39883. }
  39884. else {
  39885. this._computePixels(3, sourceArea, true);
  39886. dstOffset.y = this.bottomPixels;
  39887. }
  39888. var top_1 = 0;
  39889. if (!isTopAuto) {
  39890. this._computePixels(0, sourceArea, true);
  39891. top_1 = this.topPixels;
  39892. }
  39893. dstArea.height = sourceArea.height - (dstOffset.y + top_1);
  39894. break;
  39895. }
  39896. case PrimitiveAlignment.AlignCenter:
  39897. {
  39898. if (!isTopAuto) {
  39899. this._computePixels(0, sourceArea, true);
  39900. }
  39901. if (!isBottomAuto) {
  39902. this._computePixels(3, sourceArea, true);
  39903. }
  39904. var offset = (isBottomAuto ? 0 : this.bottomPixels) - (isTopAuto ? 0 : this.topPixels);
  39905. dstOffset.y = Math.round(((sourceArea.height - height) / 2) + offset);
  39906. dstArea.height = height;
  39907. break;
  39908. }
  39909. }
  39910. };
  39911. /**
  39912. * Compute an area and its position considering this thickness properties based on a given source area
  39913. * @param sourceArea the source area
  39914. * @param dstOffset the position of the resulting area
  39915. * @param dstArea the size of the resulting area
  39916. */
  39917. PrimitiveThickness.prototype.compute = function (sourceArea, dstOffset, dstArea) {
  39918. this._computePixels(0, sourceArea, true);
  39919. this._computePixels(1, sourceArea, true);
  39920. this._computePixels(2, sourceArea, true);
  39921. this._computePixels(3, sourceArea, true);
  39922. dstOffset.x = this.leftPixels;
  39923. dstArea.width = sourceArea.width - (dstOffset.x + this.rightPixels);
  39924. dstOffset.y = this.bottomPixels;
  39925. dstArea.height = sourceArea.height - (dstOffset.y + this.topPixels);
  39926. };
  39927. /**
  39928. * Compute an area considering this thickness properties based on a given source area
  39929. * @param sourceArea the source area
  39930. * @param result the resulting area
  39931. */
  39932. PrimitiveThickness.prototype.computeArea = function (sourceArea, result) {
  39933. this._computePixels(0, sourceArea, true);
  39934. this._computePixels(1, sourceArea, true);
  39935. this._computePixels(2, sourceArea, true);
  39936. this._computePixels(3, sourceArea, true);
  39937. result.width = this.leftPixels + sourceArea.width + this.rightPixels;
  39938. result.height = this.bottomPixels + sourceArea.height + this.topPixels;
  39939. };
  39940. PrimitiveThickness.prototype.enlarge = function (sourceArea, dstOffset, enlargedArea) {
  39941. this._computePixels(0, sourceArea, true);
  39942. this._computePixels(1, sourceArea, true);
  39943. this._computePixels(2, sourceArea, true);
  39944. this._computePixels(3, sourceArea, true);
  39945. dstOffset.x = this.leftPixels;
  39946. enlargedArea.width = sourceArea.width + (dstOffset.x + this.rightPixels);
  39947. dstOffset.y = this.bottomPixels;
  39948. enlargedArea.height = sourceArea.height + (dstOffset.y + this.topPixels);
  39949. };
  39950. PrimitiveThickness.Auto = 0x1;
  39951. PrimitiveThickness.Inherit = 0x2;
  39952. PrimitiveThickness.Percentage = 0x4;
  39953. PrimitiveThickness.Pixel = 0x8;
  39954. return PrimitiveThickness;
  39955. })();
  39956. BABYLON.PrimitiveThickness = PrimitiveThickness;
  39957. /**
  39958. * Main class used for the Primitive Intersection API
  39959. */
  39960. var IntersectInfo2D = (function () {
  39961. function IntersectInfo2D() {
  39962. this.findFirstOnly = false;
  39963. this.intersectHidden = false;
  39964. this.pickPosition = BABYLON.Vector2.Zero();
  39965. }
  39966. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  39967. /**
  39968. * true if at least one primitive intersected during the test
  39969. */
  39970. get: function () {
  39971. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  39972. },
  39973. enumerable: true,
  39974. configurable: true
  39975. });
  39976. IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
  39977. for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
  39978. var cur = _a[_i];
  39979. if (cur.prim === prim) {
  39980. return cur.intersectionLocation;
  39981. }
  39982. }
  39983. return null;
  39984. };
  39985. // Internals, don't use
  39986. IntersectInfo2D.prototype._exit = function (firstLevel) {
  39987. if (firstLevel) {
  39988. this._globalPickPosition = null;
  39989. }
  39990. };
  39991. return IntersectInfo2D;
  39992. })();
  39993. BABYLON.IntersectInfo2D = IntersectInfo2D;
  39994. var Prim2DBase = (function (_super) {
  39995. __extends(Prim2DBase, _super);
  39996. function Prim2DBase(settings) {
  39997. // Avoid checking every time if the object exists
  39998. if (settings == null) {
  39999. settings = {};
  40000. }
  40001. // BASE CLASS CALL
  40002. _super.call(this);
  40003. // Fetch the owner, parent. There're many ways to do it and we can end up with nothing for both
  40004. var owner;
  40005. var parent;
  40006. if (Prim2DBase._isCanvasInit) {
  40007. owner = this;
  40008. parent = null;
  40009. this._canvasPreInit(settings);
  40010. }
  40011. else {
  40012. if (settings.parent != null) {
  40013. parent = settings.parent;
  40014. owner = settings.parent.owner;
  40015. if (!owner) {
  40016. throw new Error("Parent " + parent.id + " of " + settings.id + " doesn't have a valid owner!");
  40017. }
  40018. 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)) {
  40019. 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");
  40020. }
  40021. }
  40022. }
  40023. // Fields initialization
  40024. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  40025. this._size = null; //Size.Zero();
  40026. this._scale = new BABYLON.Vector2(1, 1);
  40027. this._actualSize = null;
  40028. this._boundingSize = BABYLON.Size.Zero();
  40029. this._layoutArea = BABYLON.Size.Zero();
  40030. this._layoutAreaPos = BABYLON.Vector2.Zero();
  40031. this._marginOffset = BABYLON.Vector2.Zero();
  40032. this._paddingOffset = BABYLON.Vector2.Zero();
  40033. this._parentPaddingOffset = BABYLON.Vector2.Zero();
  40034. this._parentContentArea = BABYLON.Size.Zero();
  40035. this._lastAutoSizeArea = BABYLON.Size.Zero();
  40036. this._contentArea = new BABYLON.Size(null, null);
  40037. this._pointerEventObservable = new BABYLON.Observable();
  40038. this._boundingInfo = new BABYLON.BoundingInfo2D();
  40039. this._owner = owner;
  40040. this._parent = null;
  40041. this._margin = null;
  40042. this._padding = null;
  40043. this._marginAlignment = null;
  40044. this._id = settings.id;
  40045. this.propertyChanged = new BABYLON.Observable();
  40046. this._children = new Array();
  40047. this._localTransform = new BABYLON.Matrix();
  40048. this._globalTransform = null;
  40049. this._invGlobalTransform = null;
  40050. this._globalTransformProcessStep = 0;
  40051. this._globalTransformStep = 0;
  40052. this._renderGroup = null;
  40053. this._primLinearPosition = 0;
  40054. this._manualZOrder = null;
  40055. this._zOrder = 0;
  40056. this._zMax = 0;
  40057. this._firstZDirtyIndex = Prim2DBase._bigInt;
  40058. this._setFlags(BABYLON.SmartPropertyPrim.flagIsPickable | BABYLON.SmartPropertyPrim.flagBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  40059. if (settings.opacity != null) {
  40060. this._opacity = settings.opacity;
  40061. }
  40062. else {
  40063. this._opacity = 1;
  40064. }
  40065. this._updateRenderMode();
  40066. if (settings.childrenFlatZOrder) {
  40067. this._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  40068. }
  40069. // If the parent is given, initialize the hierarchy/owner related data
  40070. if (parent != null) {
  40071. parent.addChild(this);
  40072. this._patchHierarchy(parent.owner);
  40073. }
  40074. // If it's a group, detect its own states
  40075. if (this.owner && this instanceof BABYLON.Group2D) {
  40076. var group = this;
  40077. group.detectGroupStates();
  40078. }
  40079. // Time to insert children if some are specified
  40080. if (settings.children != null) {
  40081. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  40082. var child = _a[_i];
  40083. this.addChild(child);
  40084. // Good time to patch the hierarchy, it won't go very far if there's no need to
  40085. child._patchHierarchy(this.owner);
  40086. }
  40087. }
  40088. // Set the model related properties
  40089. if (settings.position != null) {
  40090. this.position = settings.position;
  40091. }
  40092. else if (settings.x != null || settings.y != null) {
  40093. this.position = new BABYLON.Vector2(settings.x || 0, settings.y || 0);
  40094. }
  40095. else {
  40096. this._position = null;
  40097. }
  40098. this.rotation = (settings.rotation == null) ? 0 : settings.rotation;
  40099. if (settings.scale != null) {
  40100. this.scale = settings.scale;
  40101. }
  40102. else {
  40103. if (settings.scaleX != null) {
  40104. this.scaleX = settings.scaleX;
  40105. }
  40106. if (settings.scaleY != null) {
  40107. this.scaleY = settings.scaleY;
  40108. }
  40109. }
  40110. this.levelVisible = (settings.isVisible == null) ? true : settings.isVisible;
  40111. this.origin = settings.origin || new BABYLON.Vector2(0.5, 0.5);
  40112. // Layout Engine
  40113. if (settings.layoutEngine != null) {
  40114. if (typeof settings.layoutEngine === "string") {
  40115. var name_1 = settings.layoutEngine.toLocaleLowerCase().trim();
  40116. if (name_1 === "canvas" || name_1 === "canvaslayoutengine") {
  40117. this.layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  40118. }
  40119. else if (name_1.indexOf("stackpanel") === 0 || name_1.indexOf("horizontalstackpanel") === 0) {
  40120. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Horizontal;
  40121. }
  40122. else if (name_1.indexOf("verticalstackpanel") === 0) {
  40123. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Vertical;
  40124. }
  40125. }
  40126. else if (settings.layoutEngine instanceof BABYLON.LayoutEngineBase) {
  40127. this.layoutEngine = settings.layoutEngine;
  40128. }
  40129. }
  40130. // Set the layout/margin stuffs
  40131. if (settings.marginTop) {
  40132. this.margin.setTop(settings.marginTop);
  40133. }
  40134. if (settings.marginLeft) {
  40135. this.margin.setLeft(settings.marginLeft);
  40136. }
  40137. if (settings.marginRight) {
  40138. this.margin.setRight(settings.marginRight);
  40139. }
  40140. if (settings.marginBottom) {
  40141. this.margin.setBottom(settings.marginBottom);
  40142. }
  40143. if (settings.margin) {
  40144. if (typeof settings.margin === "string") {
  40145. this.margin.fromString(settings.margin);
  40146. }
  40147. else {
  40148. this.margin.fromUniformPixels(settings.margin);
  40149. }
  40150. }
  40151. if (settings.marginHAlignment) {
  40152. this.marginAlignment.horizontal = settings.marginHAlignment;
  40153. }
  40154. if (settings.marginVAlignment) {
  40155. this.marginAlignment.vertical = settings.marginVAlignment;
  40156. }
  40157. if (settings.marginAlignment) {
  40158. this.marginAlignment.fromString(settings.marginAlignment);
  40159. }
  40160. if (settings.paddingTop) {
  40161. this.padding.setTop(settings.paddingTop);
  40162. }
  40163. if (settings.paddingLeft) {
  40164. this.padding.setLeft(settings.paddingLeft);
  40165. }
  40166. if (settings.paddingRight) {
  40167. this.padding.setRight(settings.paddingRight);
  40168. }
  40169. if (settings.paddingBottom) {
  40170. this.padding.setBottom(settings.paddingBottom);
  40171. }
  40172. if (settings.padding) {
  40173. this.padding.fromString(settings.padding);
  40174. }
  40175. // Dirty layout and positioning
  40176. this._parentLayoutDirty();
  40177. this._positioningDirty();
  40178. }
  40179. Object.defineProperty(Prim2DBase.prototype, "actionManager", {
  40180. get: function () {
  40181. if (!this._actionManager) {
  40182. this._actionManager = new BABYLON.ActionManager(this.owner.scene);
  40183. }
  40184. return this._actionManager;
  40185. },
  40186. enumerable: true,
  40187. configurable: true
  40188. });
  40189. /**
  40190. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  40191. * @param predicate the predicate to test on each parent
  40192. * @return the first primitive where the predicate was successful
  40193. */
  40194. Prim2DBase.prototype.traverseUp = function (predicate) {
  40195. var p = this;
  40196. while (p != null) {
  40197. if (predicate(p)) {
  40198. return p;
  40199. }
  40200. p = p._parent;
  40201. }
  40202. return null;
  40203. };
  40204. Object.defineProperty(Prim2DBase.prototype, "owner", {
  40205. /**
  40206. * Retrieve the owner Canvas2D
  40207. */
  40208. get: function () {
  40209. return this._owner;
  40210. },
  40211. enumerable: true,
  40212. configurable: true
  40213. });
  40214. Object.defineProperty(Prim2DBase.prototype, "parent", {
  40215. /**
  40216. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  40217. */
  40218. get: function () {
  40219. return this._parent;
  40220. },
  40221. enumerable: true,
  40222. configurable: true
  40223. });
  40224. Object.defineProperty(Prim2DBase.prototype, "children", {
  40225. /**
  40226. * The array of direct children primitives
  40227. */
  40228. get: function () {
  40229. return this._children;
  40230. },
  40231. enumerable: true,
  40232. configurable: true
  40233. });
  40234. Object.defineProperty(Prim2DBase.prototype, "id", {
  40235. /**
  40236. * The identifier of this primitive, may not be unique, it's for information purpose only
  40237. */
  40238. get: function () {
  40239. return this._id;
  40240. },
  40241. enumerable: true,
  40242. configurable: true
  40243. });
  40244. Object.defineProperty(Prim2DBase.prototype, "actualPosition", {
  40245. get: function () {
  40246. if (this._actualPosition != null) {
  40247. return this._actualPosition;
  40248. }
  40249. if (this._position != null) {
  40250. return this._position;
  40251. }
  40252. // At least return 0,0, we can't return null on actualPosition
  40253. return Prim2DBase._nullPosition;
  40254. },
  40255. /**
  40256. * DO NOT INVOKE for internal purpose only
  40257. */
  40258. set: function (val) {
  40259. this._actualPosition = val;
  40260. },
  40261. enumerable: true,
  40262. configurable: true
  40263. });
  40264. Object.defineProperty(Prim2DBase.prototype, "actualX", {
  40265. /**
  40266. * Shortcut to actualPosition.x
  40267. */
  40268. get: function () {
  40269. return this.actualPosition.x;
  40270. },
  40271. enumerable: true,
  40272. configurable: true
  40273. });
  40274. Object.defineProperty(Prim2DBase.prototype, "actualY", {
  40275. /**
  40276. * Shortcut to actualPosition.y
  40277. */
  40278. get: function () {
  40279. return this.actualPosition.y;
  40280. },
  40281. enumerable: true,
  40282. configurable: true
  40283. });
  40284. Object.defineProperty(Prim2DBase.prototype, "position", {
  40285. /**
  40286. * Position of the primitive, relative to its parent.
  40287. * BEWARE: if you change only position.x or y it won't trigger a property change and you won't have the expected behavior.
  40288. * Use this property to set a new Vector2 object, otherwise to change only the x/y use Prim2DBase.x or y properties.
  40289. * Setting this property may have no effect is specific alignment are in effect.
  40290. */
  40291. get: function () {
  40292. return this._position || Prim2DBase._nullPosition;
  40293. },
  40294. set: function (value) {
  40295. if (!this._checkPositionChange()) {
  40296. return;
  40297. }
  40298. this._position = value;
  40299. this.markAsDirty("actualPosition");
  40300. },
  40301. enumerable: true,
  40302. configurable: true
  40303. });
  40304. Object.defineProperty(Prim2DBase.prototype, "x", {
  40305. /**
  40306. * Direct access to the position.x value of the primitive
  40307. * Use this property when you only want to change one component of the position property
  40308. */
  40309. get: function () {
  40310. if (!this._position) {
  40311. return null;
  40312. }
  40313. return this._position.x;
  40314. },
  40315. set: function (value) {
  40316. if (!this._checkPositionChange()) {
  40317. return;
  40318. }
  40319. if (!this._position) {
  40320. this._position = BABYLON.Vector2.Zero();
  40321. }
  40322. if (this._position.x === value) {
  40323. return;
  40324. }
  40325. this._position.x = value;
  40326. this.markAsDirty("position");
  40327. this.markAsDirty("actualPosition");
  40328. },
  40329. enumerable: true,
  40330. configurable: true
  40331. });
  40332. Object.defineProperty(Prim2DBase.prototype, "y", {
  40333. /**
  40334. * Direct access to the position.y value of the primitive
  40335. * Use this property when you only want to change one component of the position property
  40336. */
  40337. get: function () {
  40338. if (!this._position) {
  40339. return null;
  40340. }
  40341. return this._position.y;
  40342. },
  40343. set: function (value) {
  40344. if (!this._checkPositionChange()) {
  40345. return;
  40346. }
  40347. if (!this._position) {
  40348. this._position = BABYLON.Vector2.Zero();
  40349. }
  40350. if (this._position.y === value) {
  40351. return;
  40352. }
  40353. this._position.y = value;
  40354. this.markAsDirty("position");
  40355. this.markAsDirty("actualPosition");
  40356. },
  40357. enumerable: true,
  40358. configurable: true
  40359. });
  40360. Object.defineProperty(Prim2DBase.prototype, "size", {
  40361. /**
  40362. * Size of the primitive or its bounding area
  40363. * BEWARE: if you change only size.width or height it won't trigger a property change and you won't have the expected behavior.
  40364. * Use this property to set a new Size object, otherwise to change only the width/height use Prim2DBase.width or height properties.
  40365. */
  40366. get: function () {
  40367. if (!this._size || this._size.width == null || this._size.height == null) {
  40368. if (Prim2DBase.boundinbBoxReentrency) {
  40369. return Prim2DBase.nullSize;
  40370. }
  40371. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  40372. return this._boundingSize;
  40373. }
  40374. Prim2DBase.boundinbBoxReentrency = true;
  40375. var b = this.boundingInfo;
  40376. Prim2DBase.boundinbBoxReentrency = false;
  40377. return this._boundingSize;
  40378. }
  40379. return this._size;
  40380. },
  40381. set: function (value) {
  40382. this._size = value;
  40383. },
  40384. enumerable: true,
  40385. configurable: true
  40386. });
  40387. Object.defineProperty(Prim2DBase.prototype, "width", {
  40388. /**
  40389. * Direct access to the size.width value of the primitive
  40390. * Use this property when you only want to change one component of the size property
  40391. */
  40392. get: function () {
  40393. if (!this.size) {
  40394. return null;
  40395. }
  40396. return this.size.width;
  40397. },
  40398. set: function (value) {
  40399. if (!this.size) {
  40400. this.size = new BABYLON.Size(value, 0);
  40401. return;
  40402. }
  40403. if (this.size.width === value) {
  40404. return;
  40405. }
  40406. this.size.width = value;
  40407. this.markAsDirty("size");
  40408. this._positioningDirty();
  40409. },
  40410. enumerable: true,
  40411. configurable: true
  40412. });
  40413. Object.defineProperty(Prim2DBase.prototype, "height", {
  40414. /**
  40415. * Direct access to the size.height value of the primitive
  40416. * Use this property when you only want to change one component of the size property
  40417. */
  40418. get: function () {
  40419. if (!this.size) {
  40420. return null;
  40421. }
  40422. return this.size.height;
  40423. },
  40424. set: function (value) {
  40425. if (!this.size) {
  40426. this.size = new BABYLON.Size(0, value);
  40427. return;
  40428. }
  40429. if (this.size.height === value) {
  40430. return;
  40431. }
  40432. this.size.height = value;
  40433. this.markAsDirty("size");
  40434. this._positioningDirty();
  40435. },
  40436. enumerable: true,
  40437. configurable: true
  40438. });
  40439. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  40440. get: function () {
  40441. return this._rotation;
  40442. },
  40443. set: function (value) {
  40444. this._rotation = value;
  40445. },
  40446. enumerable: true,
  40447. configurable: true
  40448. });
  40449. Object.defineProperty(Prim2DBase.prototype, "scale", {
  40450. get: function () {
  40451. return this._scale.x;
  40452. },
  40453. set: function (value) {
  40454. this._scale.x = this._scale.y = value;
  40455. },
  40456. enumerable: true,
  40457. configurable: true
  40458. });
  40459. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  40460. /**
  40461. * Return the size of the primitive as it's being rendered into the target.
  40462. * 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.
  40463. * BEWARE: don't use the setter, it's for internal purpose only
  40464. * Note to implementers: you have to override this property and declare if necessary a @xxxxInstanceLevel decorator
  40465. */
  40466. get: function () {
  40467. if (this._actualSize) {
  40468. return this._actualSize;
  40469. }
  40470. return this._size;
  40471. },
  40472. set: function (value) {
  40473. if (this._actualSize.equals(value)) {
  40474. return;
  40475. }
  40476. this._actualSize = value;
  40477. },
  40478. enumerable: true,
  40479. configurable: true
  40480. });
  40481. Object.defineProperty(Prim2DBase.prototype, "actualZOffset", {
  40482. get: function () {
  40483. if (this._manualZOrder != null) {
  40484. return this._manualZOrder;
  40485. }
  40486. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  40487. this._updateZOrder();
  40488. }
  40489. return (1 - this._zOrder);
  40490. },
  40491. enumerable: true,
  40492. configurable: true
  40493. });
  40494. Object.defineProperty(Prim2DBase.prototype, "minSize", {
  40495. /**
  40496. * Get or set the minimal size the Layout Engine should respect when computing the primitive's actualSize.
  40497. * The Primitive's size won't be less than specified.
  40498. * The default value depends of the Primitive type
  40499. */
  40500. get: function () {
  40501. return this._minSize;
  40502. },
  40503. set: function (value) {
  40504. if (this._minSize && value && this._minSize.equals(value)) {
  40505. return;
  40506. }
  40507. this._minSize = value;
  40508. this._parentLayoutDirty();
  40509. },
  40510. enumerable: true,
  40511. configurable: true
  40512. });
  40513. Object.defineProperty(Prim2DBase.prototype, "maxSize", {
  40514. /**
  40515. * Get or set the maximal size the Layout Engine should respect when computing the primitive's actualSize.
  40516. * The Primitive's size won't be more than specified.
  40517. * The default value depends of the Primitive type
  40518. */
  40519. get: function () {
  40520. return this._maxSize;
  40521. },
  40522. set: function (value) {
  40523. if (this._maxSize && value && this._maxSize.equals(value)) {
  40524. return;
  40525. }
  40526. this._maxSize = value;
  40527. this._parentLayoutDirty();
  40528. },
  40529. enumerable: true,
  40530. configurable: true
  40531. });
  40532. Object.defineProperty(Prim2DBase.prototype, "origin", {
  40533. /**
  40534. * The origin defines the normalized coordinate of the center of the primitive, from the bottom/left corner.
  40535. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  40536. * For instance:
  40537. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  40538. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  40539. * 0,1 means the center is top/left
  40540. * @returns The normalized center.
  40541. */
  40542. get: function () {
  40543. return this._origin;
  40544. },
  40545. set: function (value) {
  40546. this._origin = value;
  40547. },
  40548. enumerable: true,
  40549. configurable: true
  40550. });
  40551. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  40552. get: function () {
  40553. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelVisible);
  40554. },
  40555. set: function (value) {
  40556. this._changeFlags(BABYLON.SmartPropertyPrim.flagLevelVisible, value);
  40557. },
  40558. enumerable: true,
  40559. configurable: true
  40560. });
  40561. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  40562. get: function () {
  40563. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsVisible);
  40564. },
  40565. set: function (value) {
  40566. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsVisible, value);
  40567. },
  40568. enumerable: true,
  40569. configurable: true
  40570. });
  40571. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  40572. get: function () {
  40573. return this._manualZOrder;
  40574. },
  40575. set: function (value) {
  40576. if (this._manualZOrder === value) {
  40577. return;
  40578. }
  40579. this._manualZOrder = value;
  40580. this.onZOrderChanged();
  40581. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  40582. this._actualZOrderChangedObservable.notifyObservers(value);
  40583. }
  40584. },
  40585. enumerable: true,
  40586. configurable: true
  40587. });
  40588. Object.defineProperty(Prim2DBase.prototype, "isManualZOrder", {
  40589. get: function () {
  40590. return this._manualZOrder != null;
  40591. },
  40592. enumerable: true,
  40593. configurable: true
  40594. });
  40595. Object.defineProperty(Prim2DBase.prototype, "margin", {
  40596. get: function () {
  40597. var _this = this;
  40598. if (!this._margin) {
  40599. this._margin = new PrimitiveThickness(function () {
  40600. if (!_this.parent) {
  40601. return null;
  40602. }
  40603. return _this.parent.margin;
  40604. }, function () { return _this._positioningDirty(); });
  40605. }
  40606. return this._margin;
  40607. },
  40608. enumerable: true,
  40609. configurable: true
  40610. });
  40611. Object.defineProperty(Prim2DBase.prototype, "_hasMargin", {
  40612. get: function () {
  40613. return (this._margin !== null) || (this._marginAlignment !== null);
  40614. },
  40615. enumerable: true,
  40616. configurable: true
  40617. });
  40618. Object.defineProperty(Prim2DBase.prototype, "padding", {
  40619. get: function () {
  40620. var _this = this;
  40621. if (!this._padding) {
  40622. this._padding = new PrimitiveThickness(function () {
  40623. if (!_this.parent) {
  40624. return null;
  40625. }
  40626. return _this.parent.padding;
  40627. }, function () { return _this._positioningDirty(); });
  40628. }
  40629. return this._padding;
  40630. },
  40631. enumerable: true,
  40632. configurable: true
  40633. });
  40634. Object.defineProperty(Prim2DBase.prototype, "_hasPadding", {
  40635. get: function () {
  40636. return this._padding !== null;
  40637. },
  40638. enumerable: true,
  40639. configurable: true
  40640. });
  40641. Object.defineProperty(Prim2DBase.prototype, "marginAlignment", {
  40642. get: function () {
  40643. var _this = this;
  40644. if (!this._marginAlignment) {
  40645. this._marginAlignment = new PrimitiveAlignment(function () { return _this._positioningDirty(); });
  40646. }
  40647. return this._marginAlignment;
  40648. },
  40649. enumerable: true,
  40650. configurable: true
  40651. });
  40652. Object.defineProperty(Prim2DBase.prototype, "opacity", {
  40653. get: function () {
  40654. return this._opacity;
  40655. },
  40656. set: function (value) {
  40657. if (value < 0) {
  40658. value = 0;
  40659. }
  40660. else if (value > 1) {
  40661. value = 1;
  40662. }
  40663. if (this._opacity === value) {
  40664. return;
  40665. }
  40666. this._opacity = value;
  40667. this._updateRenderMode();
  40668. this._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  40669. this._spreadActualOpacityChanged();
  40670. },
  40671. enumerable: true,
  40672. configurable: true
  40673. });
  40674. Object.defineProperty(Prim2DBase.prototype, "scaleX", {
  40675. get: function () {
  40676. return this._scale.x;
  40677. },
  40678. set: function (value) {
  40679. this._scale.x = value;
  40680. },
  40681. enumerable: true,
  40682. configurable: true
  40683. });
  40684. Object.defineProperty(Prim2DBase.prototype, "scaleY", {
  40685. get: function () {
  40686. return this._scale.y;
  40687. },
  40688. set: function (value) {
  40689. this._scale.y = value;
  40690. },
  40691. enumerable: true,
  40692. configurable: true
  40693. });
  40694. Object.defineProperty(Prim2DBase.prototype, "actualOpacity", {
  40695. get: function () {
  40696. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualOpacityDirty)) {
  40697. var cur = this.parent;
  40698. var op = this.opacity;
  40699. while (cur) {
  40700. op *= cur.opacity;
  40701. cur = cur.parent;
  40702. }
  40703. this._actualOpacity = op;
  40704. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  40705. }
  40706. return this._actualOpacity;
  40707. },
  40708. enumerable: true,
  40709. configurable: true
  40710. });
  40711. Object.defineProperty(Prim2DBase.prototype, "layoutEngine", {
  40712. /**
  40713. * Get/set the layout engine to use for this primitive.
  40714. * The default layout engine is the CanvasLayoutEngine.
  40715. */
  40716. get: function () {
  40717. if (!this._layoutEngine) {
  40718. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  40719. }
  40720. return this._layoutEngine;
  40721. },
  40722. set: function (value) {
  40723. if (this._layoutEngine === value) {
  40724. return;
  40725. }
  40726. this._changeLayoutEngine(value);
  40727. },
  40728. enumerable: true,
  40729. configurable: true
  40730. });
  40731. Object.defineProperty(Prim2DBase.prototype, "layoutArea", {
  40732. /**
  40733. * Get/set the layout are of this primitive.
  40734. * The Layout area is the zone allocated by the Layout Engine for this particular primitive. Margins/Alignment will be computed based on this area.
  40735. * The setter should only be called by a Layout Engine class.
  40736. */
  40737. get: function () {
  40738. return this._layoutArea;
  40739. },
  40740. set: function (val) {
  40741. if (this._layoutArea.equals(val)) {
  40742. return;
  40743. }
  40744. this._positioningDirty();
  40745. this._layoutArea = val;
  40746. },
  40747. enumerable: true,
  40748. configurable: true
  40749. });
  40750. Object.defineProperty(Prim2DBase.prototype, "layoutAreaPos", {
  40751. /**
  40752. * Get/set the layout area position (relative to the parent primitive).
  40753. * The setter should only be called by a Layout Engine class.
  40754. */
  40755. get: function () {
  40756. return this._layoutAreaPos;
  40757. },
  40758. set: function (val) {
  40759. if (this._layoutAreaPos.equals(val)) {
  40760. return;
  40761. }
  40762. this._positioningDirty();
  40763. this._layoutAreaPos = val;
  40764. },
  40765. enumerable: true,
  40766. configurable: true
  40767. });
  40768. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  40769. /**
  40770. * Define if the Primitive can be subject to intersection test or not (default is true)
  40771. */
  40772. get: function () {
  40773. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsPickable);
  40774. },
  40775. set: function (value) {
  40776. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsPickable, value);
  40777. },
  40778. enumerable: true,
  40779. configurable: true
  40780. });
  40781. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  40782. /**
  40783. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  40784. */
  40785. get: function () {
  40786. return this._hierarchyDepth;
  40787. },
  40788. enumerable: true,
  40789. configurable: true
  40790. });
  40791. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  40792. /**
  40793. * Retrieve the Group that is responsible to render this primitive
  40794. */
  40795. get: function () {
  40796. return this._renderGroup;
  40797. },
  40798. enumerable: true,
  40799. configurable: true
  40800. });
  40801. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  40802. /**
  40803. * Get the global transformation matrix of the primitive
  40804. */
  40805. get: function () {
  40806. return this._globalTransform;
  40807. },
  40808. enumerable: true,
  40809. configurable: true
  40810. });
  40811. /**
  40812. * return the global position of the primitive, relative to its canvas
  40813. */
  40814. Prim2DBase.prototype.getGlobalPosition = function () {
  40815. var v = new BABYLON.Vector2(0, 0);
  40816. this.getGlobalPositionByRef(v);
  40817. return v;
  40818. };
  40819. /**
  40820. * return the global position of the primitive, relative to its canvas
  40821. * @param v the valid Vector2 object where the global position will be stored
  40822. */
  40823. Prim2DBase.prototype.getGlobalPositionByRef = function (v) {
  40824. v.x = this.globalTransform.m[12];
  40825. v.y = this.globalTransform.m[13];
  40826. };
  40827. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  40828. /**
  40829. * Get invert of the global transformation matrix of the primitive
  40830. */
  40831. get: function () {
  40832. return this._invGlobalTransform;
  40833. },
  40834. enumerable: true,
  40835. configurable: true
  40836. });
  40837. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  40838. /**
  40839. * Get the local transformation of the primitive
  40840. */
  40841. get: function () {
  40842. this._updateLocalTransform();
  40843. return this._localTransform;
  40844. },
  40845. enumerable: true,
  40846. configurable: true
  40847. });
  40848. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  40849. /**
  40850. * Get the boundingInfo associated to the primitive and its children.
  40851. * The value is supposed to be always up to date
  40852. */
  40853. get: function () {
  40854. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  40855. if (this.owner) {
  40856. this.owner.boundingInfoRecomputeCounter.addCount(1, false);
  40857. }
  40858. if (this.isSizedByContent) {
  40859. this._boundingInfo.clear();
  40860. }
  40861. else {
  40862. this._boundingInfo.copyFrom(this.levelBoundingInfo);
  40863. }
  40864. var bi = this._boundingInfo;
  40865. var tps = new BABYLON.BoundingInfo2D();
  40866. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40867. var curChild = _a[_i];
  40868. curChild.boundingInfo.transformToRef(curChild.localTransform, tps);
  40869. bi.unionToRef(tps, bi);
  40870. }
  40871. this._boundingInfo.maxToRef(Prim2DBase._bMax);
  40872. 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);
  40873. this._clearFlags(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
  40874. }
  40875. return this._boundingInfo;
  40876. },
  40877. enumerable: true,
  40878. configurable: true
  40879. });
  40880. Object.defineProperty(Prim2DBase.prototype, "isSizeAuto", {
  40881. /**
  40882. * Determine if the size is automatically computed or fixed because manually specified.
  40883. * Use the actualSize property to get the final/real size of the primitive
  40884. * @returns true if the size is automatically computed, false if it were manually specified.
  40885. */
  40886. get: function () {
  40887. return this._size == null;
  40888. },
  40889. enumerable: true,
  40890. configurable: true
  40891. });
  40892. Object.defineProperty(Prim2DBase.prototype, "isSizedByContent", {
  40893. /**
  40894. * Return true if this prim has an auto size which is set by the children's global bounding box
  40895. */
  40896. get: function () {
  40897. return (this._size == null) && (this._children.length > 0);
  40898. },
  40899. enumerable: true,
  40900. configurable: true
  40901. });
  40902. Object.defineProperty(Prim2DBase.prototype, "isPositionAuto", {
  40903. /**
  40904. * Determine if the position is automatically computed or fixed because manually specified.
  40905. * Use the actualPosition property to get the final/real position of the primitive
  40906. * @returns true if the position is automatically computed, false if it were manually specified.
  40907. */
  40908. get: function () {
  40909. return this._position == null;
  40910. },
  40911. enumerable: true,
  40912. configurable: true
  40913. });
  40914. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  40915. /**
  40916. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  40917. */
  40918. get: function () {
  40919. return this._pointerEventObservable;
  40920. },
  40921. enumerable: true,
  40922. configurable: true
  40923. });
  40924. Object.defineProperty(Prim2DBase.prototype, "zActualOrderChangedObservable", {
  40925. get: function () {
  40926. if (!this._actualZOrderChangedObservable) {
  40927. this._actualZOrderChangedObservable = new BABYLON.Observable();
  40928. }
  40929. return this._actualZOrderChangedObservable;
  40930. },
  40931. enumerable: true,
  40932. configurable: true
  40933. });
  40934. Prim2DBase.prototype.findById = function (id) {
  40935. if (this._id === id) {
  40936. return this;
  40937. }
  40938. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40939. var child = _a[_i];
  40940. var r = child.findById(id);
  40941. if (r != null) {
  40942. return r;
  40943. }
  40944. }
  40945. };
  40946. Prim2DBase.prototype.onZOrderChanged = function () {
  40947. };
  40948. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  40949. return false;
  40950. };
  40951. /**
  40952. * Capture all the Events of the given PointerId for this primitive.
  40953. * Don't forget to call releasePointerEventsCapture when done.
  40954. * @param pointerId the Id of the pointer to capture the events from.
  40955. */
  40956. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  40957. return this.owner._setPointerCapture(pointerId, this);
  40958. };
  40959. /**
  40960. * Release a captured pointer made with setPointerEventCapture.
  40961. * @param pointerId the Id of the pointer to release the capture from.
  40962. */
  40963. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  40964. return this.owner._releasePointerCapture(pointerId, this);
  40965. };
  40966. /**
  40967. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  40968. * @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.
  40969. */
  40970. Prim2DBase.prototype.intersect = function (intersectInfo) {
  40971. if (!intersectInfo) {
  40972. return false;
  40973. }
  40974. // If this is null it means this method is call for the first level, initialize stuffs
  40975. var firstLevel = !intersectInfo._globalPickPosition;
  40976. if (firstLevel) {
  40977. // 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).
  40978. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  40979. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  40980. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  40981. intersectInfo.intersectedPrimitives = new Array();
  40982. intersectInfo.topMostIntersectedPrimitive = null;
  40983. }
  40984. if (!intersectInfo.intersectHidden && !this.isVisible) {
  40985. return false;
  40986. }
  40987. // Fast rejection test with boundingInfo
  40988. if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  40989. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  40990. intersectInfo._exit(firstLevel);
  40991. return false;
  40992. }
  40993. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  40994. var levelIntersectRes = false;
  40995. if (this.isPickable) {
  40996. levelIntersectRes = this.levelIntersect(intersectInfo);
  40997. if (levelIntersectRes) {
  40998. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  40999. intersectInfo.intersectedPrimitives.push(pii);
  41000. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.actualZOffset > pii.prim.actualZOffset)) {
  41001. intersectInfo.topMostIntersectedPrimitive = pii;
  41002. }
  41003. // If we must stop at the first intersection, we're done, quit!
  41004. if (intersectInfo.findFirstOnly) {
  41005. intersectInfo._exit(firstLevel);
  41006. return true;
  41007. }
  41008. }
  41009. }
  41010. // Recurse to children if needed
  41011. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  41012. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41013. var curChild = _a[_i];
  41014. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  41015. if (!curChild.isPickable || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  41016. continue;
  41017. }
  41018. // Must compute the localPickLocation for the children level
  41019. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  41020. // If we got an intersection with the child and we only need to find the first one, quit!
  41021. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  41022. intersectInfo._exit(firstLevel);
  41023. return true;
  41024. }
  41025. }
  41026. }
  41027. intersectInfo._exit(firstLevel);
  41028. return intersectInfo.isIntersected;
  41029. };
  41030. Prim2DBase.prototype.moveChild = function (child, previous) {
  41031. if (child.parent !== this) {
  41032. return false;
  41033. }
  41034. var childIndex = this._children.indexOf(child);
  41035. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  41036. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  41037. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41038. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, prevIndex + 1);
  41039. }
  41040. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  41041. };
  41042. Prim2DBase.prototype.addChild = function (child) {
  41043. child._parent = this;
  41044. this._boundingBoxDirty();
  41045. var flat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  41046. if (flat) {
  41047. child._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  41048. child._setZOrder(this._zOrder, true);
  41049. child._zMax = this._zOrder;
  41050. }
  41051. else {
  41052. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41053. }
  41054. var length = this._children.push(child);
  41055. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, length - 1);
  41056. };
  41057. /**
  41058. * Dispose the primitive, remove it from its parent.
  41059. */
  41060. Prim2DBase.prototype.dispose = function () {
  41061. if (!_super.prototype.dispose.call(this)) {
  41062. return false;
  41063. }
  41064. if (this._actionManager) {
  41065. this._actionManager.dispose();
  41066. this._actionManager = null;
  41067. }
  41068. // If there's a parent, remove this object from its parent list
  41069. if (this._parent) {
  41070. var i = this._parent._children.indexOf(this);
  41071. if (i !== undefined) {
  41072. this._parent._children.splice(i, 1);
  41073. }
  41074. this._parent = null;
  41075. }
  41076. // Recurse dispose to children
  41077. if (this._children) {
  41078. while (this._children.length > 0) {
  41079. this._children[this._children.length - 1].dispose();
  41080. }
  41081. }
  41082. return true;
  41083. };
  41084. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  41085. if (this._renderGroup && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPrimInDirtyList)) {
  41086. this._renderGroup._addPrimToDirtyList(this);
  41087. this._setFlags(BABYLON.SmartPropertyPrim.flagPrimInDirtyList);
  41088. }
  41089. };
  41090. Prim2DBase.prototype._needPrepare = function () {
  41091. return this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagModelDirty) || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  41092. };
  41093. Prim2DBase.prototype._prepareRender = function (context) {
  41094. this._prepareRenderPre(context);
  41095. this._prepareRenderPost(context);
  41096. };
  41097. Prim2DBase.prototype._prepareRenderPre = function (context) {
  41098. };
  41099. Prim2DBase.prototype._prepareRenderPost = function (context) {
  41100. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  41101. if (this instanceof BABYLON.Group2D) {
  41102. var self = this;
  41103. if (self.isRenderableGroup) {
  41104. return;
  41105. }
  41106. }
  41107. // Check if we need to recurse the prepare to children primitives
  41108. // - must have children
  41109. // - the global transform of this level have changed, or
  41110. // - the visible state of primitive has changed
  41111. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  41112. this.checkPropertiesDirty(Prim2DBase.isVisibleProperty.flagId))) {
  41113. this._children.forEach(function (c) {
  41114. // As usual stop the recursion if we meet a renderable group
  41115. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  41116. c._prepareRender(context);
  41117. }
  41118. });
  41119. }
  41120. // Finally reset the dirty flags as we've processed everything
  41121. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  41122. this._instanceDirtyFlags = 0;
  41123. };
  41124. Prim2DBase.prototype._canvasPreInit = function (settings) {
  41125. };
  41126. Prim2DBase.CheckParent = function (parent) {
  41127. //if (!Prim2DBase._isCanvasInit && !parent) {
  41128. // 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)");
  41129. //}
  41130. };
  41131. Prim2DBase.prototype.updateCachedStatesOf = function (list, recurse) {
  41132. for (var _i = 0; _i < list.length; _i++) {
  41133. var cur = list[_i];
  41134. cur.updateCachedStates(recurse);
  41135. }
  41136. };
  41137. Prim2DBase.prototype._parentLayoutDirty = function () {
  41138. if (!this._parent || this._parent.isDisposed) {
  41139. return;
  41140. }
  41141. this._parent._setLayoutDirty();
  41142. };
  41143. Prim2DBase.prototype._setLayoutDirty = function () {
  41144. this.onPrimBecomesDirty();
  41145. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  41146. };
  41147. Prim2DBase.prototype._checkPositionChange = function () {
  41148. if (this.parent && this.parent.layoutEngine.isChildPositionAllowed === false) {
  41149. console.log("Can't manually set the position of " + this.id + ", the Layout Engine of its parent doesn't allow it");
  41150. return false;
  41151. }
  41152. return true;
  41153. };
  41154. Prim2DBase.prototype._positioningDirty = function () {
  41155. this.onPrimBecomesDirty();
  41156. this._setFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41157. };
  41158. Prim2DBase.prototype._spreadActualOpacityChanged = function () {
  41159. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41160. var child = _a[_i];
  41161. child._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  41162. child._spreadActualOpacityChanged();
  41163. }
  41164. };
  41165. Prim2DBase.prototype._changeLayoutEngine = function (engine) {
  41166. this._layoutEngine = engine;
  41167. };
  41168. Prim2DBase.prototype._updateLocalTransform = function () {
  41169. var tflags = Prim2DBase.actualPositionProperty.flagId | Prim2DBase.rotationProperty.flagId | Prim2DBase.scaleProperty.flagId | Prim2DBase.scaleXProperty.flagId | Prim2DBase.scaleYProperty.flagId | Prim2DBase.originProperty.flagId;
  41170. if (this.checkPropertiesDirty(tflags)) {
  41171. if (this.owner) {
  41172. this.owner.addupdateLocalTransformCounter(1);
  41173. }
  41174. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  41175. var local;
  41176. var pos = this.position;
  41177. if (this._origin.x === 0 && this._origin.y === 0) {
  41178. local = BABYLON.Matrix.Compose(new BABYLON.Vector3(this._scale.x, this._scale.y, 1), rot, new BABYLON.Vector3(pos.x, pos.y, 0));
  41179. this._localTransform = local;
  41180. }
  41181. else {
  41182. // -Origin offset
  41183. var as = this.actualSize;
  41184. BABYLON.Matrix.TranslationToRef((-as.width * this._origin.x), (-as.height * this._origin.y), 0, Prim2DBase._t0);
  41185. // -Origin * rotation
  41186. rot.toRotationMatrix(Prim2DBase._t1);
  41187. Prim2DBase._t0.multiplyToRef(Prim2DBase._t1, Prim2DBase._t2);
  41188. // -Origin * rotation * scale
  41189. BABYLON.Matrix.ScalingToRef(this._scale.x, this._scale.y, 1, Prim2DBase._t0);
  41190. Prim2DBase._t2.multiplyToRef(Prim2DBase._t0, Prim2DBase._t1);
  41191. // -Origin * rotation * scale * (Origin + Position)
  41192. BABYLON.Matrix.TranslationToRef((as.width * this._origin.x) + pos.x, (as.height * this._origin.y) + pos.y, 0, Prim2DBase._t2);
  41193. Prim2DBase._t1.multiplyToRef(Prim2DBase._t2, this._localTransform);
  41194. }
  41195. this.clearPropertiesDirty(tflags);
  41196. return true;
  41197. }
  41198. return false;
  41199. };
  41200. Prim2DBase.prototype.updateCachedStates = function (recurse) {
  41201. if (this.isDisposed) {
  41202. return;
  41203. }
  41204. this.owner.addCachedGroupRenderCounter(1);
  41205. // Check if the parent is synced
  41206. if (this._parent && ((this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || this._parent._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLayoutDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty | BABYLON.SmartPropertyPrim.flagZOrderDirty))) {
  41207. this._parent.updateCachedStates(false);
  41208. }
  41209. // Update Z-Order if needed
  41210. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  41211. this._updateZOrder();
  41212. }
  41213. // Update actualSize only if there' not positioning to recompute and the size changed
  41214. // Otherwise positioning will take care of it.
  41215. var sizeDirty = this.checkPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  41216. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty) && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) && sizeDirty) {
  41217. var size = this.size;
  41218. if (size) {
  41219. if (this.size.width != null) {
  41220. this.actualSize.width = this.size.width;
  41221. }
  41222. if (this.size.height != null) {
  41223. this.actualSize.height = this.size.height;
  41224. }
  41225. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  41226. }
  41227. }
  41228. // Check for layout update
  41229. var positioningDirty = this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41230. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  41231. this.owner.addUpdateLayoutCounter(1);
  41232. this._layoutEngine.updateLayout(this);
  41233. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  41234. }
  41235. var positioningComputed = positioningDirty && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41236. var autoContentChanged = false;
  41237. if (this.isSizeAuto) {
  41238. if (!this._lastAutoSizeArea) {
  41239. autoContentChanged = this.size !== null;
  41240. }
  41241. else {
  41242. autoContentChanged = (!this._lastAutoSizeArea.equals(this.size));
  41243. }
  41244. }
  41245. // Check for positioning update
  41246. if (!positioningComputed && (autoContentChanged || sizeDirty || this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) || (this._parent && !this._parent.contentArea.equals(this._parentContentArea)))) {
  41247. this._updatePositioning();
  41248. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41249. if (sizeDirty) {
  41250. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  41251. }
  41252. positioningComputed = true;
  41253. }
  41254. if (positioningComputed && this._parent) {
  41255. this._parentContentArea.copyFrom(this._parent.contentArea);
  41256. }
  41257. // Check if we must update this prim
  41258. if (this === this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  41259. this.owner.addUpdateGlobalTransformCounter(1);
  41260. var curVisibleState = this.isVisible;
  41261. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  41262. // Detect a change of visibility
  41263. this._changeFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged, curVisibleState !== this.isVisible);
  41264. // Get/compute the localTransform
  41265. var localDirty = this._updateLocalTransform();
  41266. var parentPaddingChanged = false;
  41267. var parentPaddingOffset = Prim2DBase._v0;
  41268. if (this._parent) {
  41269. parentPaddingOffset = this._parent._paddingOffset;
  41270. parentPaddingChanged = !parentPaddingOffset.equals(this._parentPaddingOffset);
  41271. }
  41272. // Check if there are changes in the parent that will force us to update the global matrix
  41273. var parentDirty = (this._parent != null) ? (this._parent._globalTransformStep !== this._parentTransformStep) : false;
  41274. // Check if we have to update the globalTransform
  41275. if (!this._globalTransform || localDirty || parentDirty || parentPaddingChanged) {
  41276. var globalTransform = this._parent ? this._parent._globalTransform : null;
  41277. var localTransform;
  41278. Prim2DBase._transMtx.copyFrom(this._localTransform);
  41279. Prim2DBase._transMtx.m[12] += this._layoutAreaPos.x + this._marginOffset.x + parentPaddingOffset.x;
  41280. Prim2DBase._transMtx.m[13] += this._layoutAreaPos.y + this._marginOffset.y + parentPaddingOffset.y;
  41281. localTransform = Prim2DBase._transMtx;
  41282. this._globalTransform = this._parent ? localTransform.multiply(globalTransform) : localTransform.clone();
  41283. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  41284. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  41285. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  41286. }
  41287. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  41288. }
  41289. if (recurse) {
  41290. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41291. var child = _a[_i];
  41292. // Stop the recursion if we meet a renderable group
  41293. child.updateCachedStates(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  41294. }
  41295. }
  41296. };
  41297. Prim2DBase.prototype._updatePositioning = function () {
  41298. if (this.owner) {
  41299. this.owner.addUpdatePositioningCounter(1);
  41300. }
  41301. // From this point we assume that the primitive layoutArea is computed and up to date.
  41302. // We know have to :
  41303. // 1. Determine the PaddingArea and the ActualPosition based on the margin/marginAlignment properties, which will also set the size property of the primitive
  41304. // 2. Determine the contentArea based on the padding property.
  41305. // 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
  41306. if (!this._hasMargin && (this.actualSize.width == null || this.actualSize.height == null)) {
  41307. if (this.actualSize.width == null) {
  41308. this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  41309. }
  41310. if (this.actualSize.height == null) {
  41311. this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  41312. }
  41313. }
  41314. // Apply margin
  41315. if (this._hasMargin) {
  41316. this.margin.computeWithAlignment(this.layoutArea, this.size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  41317. this.actualSize = Prim2DBase._size.clone();
  41318. }
  41319. var isSizeAuto = this.isSizeAuto;
  41320. if (this._hasPadding) {
  41321. // Two cases from here: the size of the Primitive is Auto, its content can't be shrink, so me resize the primitive itself
  41322. if (isSizeAuto) {
  41323. var content = this.size.clone();
  41324. this._getActualSizeFromContentToRef(content, Prim2DBase._icArea);
  41325. this.padding.enlarge(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  41326. this._contentArea.copyFrom(content);
  41327. this.actualSize = Prim2DBase._size.clone();
  41328. // Changing the padding has resize the prim, which forces us to recompute margin again
  41329. if (this._hasMargin) {
  41330. this.margin.computeWithAlignment(this.layoutArea, Prim2DBase._size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  41331. }
  41332. }
  41333. else {
  41334. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  41335. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  41336. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  41337. this.padding.compute(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  41338. this._paddingOffset.x += Prim2DBase._icPos.x;
  41339. this._paddingOffset.y += Prim2DBase._icPos.y;
  41340. this._contentArea.copyFrom(Prim2DBase._size);
  41341. }
  41342. }
  41343. else {
  41344. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  41345. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  41346. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  41347. this._paddingOffset.copyFrom(Prim2DBase._icPos);
  41348. this._contentArea.copyFrom(Prim2DBase._icArea);
  41349. }
  41350. if (!this._position) {
  41351. var aPos = new BABYLON.Vector2(this._layoutAreaPos.x + this._marginOffset.x, this._layoutAreaPos.y + this._marginOffset.y);
  41352. this.actualPosition = aPos;
  41353. }
  41354. if (isSizeAuto) {
  41355. this._lastAutoSizeArea = this.size;
  41356. }
  41357. };
  41358. Object.defineProperty(Prim2DBase.prototype, "contentArea", {
  41359. /**
  41360. * Get the content are of this primitive, this area is computed using the padding property and also possibly the primitive type itself.
  41361. * Children of this primitive will be positioned relative to the bottom/left corner of this area.
  41362. */
  41363. get: function () {
  41364. // Check for positioning update
  41365. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  41366. this._updatePositioning();
  41367. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41368. }
  41369. return this._contentArea;
  41370. },
  41371. enumerable: true,
  41372. configurable: true
  41373. });
  41374. Prim2DBase.prototype._patchHierarchy = function (owner) {
  41375. this._owner = owner;
  41376. // The only place we initialize the _renderGroup is this method, if it's set, we already been there, no need to execute more
  41377. if (this._renderGroup != null) {
  41378. return;
  41379. }
  41380. if (this instanceof BABYLON.Group2D) {
  41381. var group = this;
  41382. group.detectGroupStates();
  41383. if (group._trackedNode && !group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  41384. group.owner._registerTrackedNode(this);
  41385. }
  41386. }
  41387. this._renderGroup = this.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  41388. if (this._parent) {
  41389. this._parentLayoutDirty();
  41390. }
  41391. // Make sure the prim is in the dirtyList if it should be
  41392. if (this._renderGroup && this.isDirty) {
  41393. var list = this._renderGroup._renderableData._primDirtyList;
  41394. var i = list.indexOf(this);
  41395. if (i === -1) {
  41396. list.push(this);
  41397. }
  41398. }
  41399. // Recurse
  41400. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41401. var child = _a[_i];
  41402. child._hierarchyDepth = this._hierarchyDepth + 1;
  41403. child._patchHierarchy(owner);
  41404. }
  41405. };
  41406. Prim2DBase.prototype._updateZOrder = function () {
  41407. var prevLinPos = this._primLinearPosition;
  41408. var startI = 0;
  41409. var startZ = this._zOrder;
  41410. // 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
  41411. var childrenCount = this._children.length;
  41412. if (this._firstZDirtyIndex > 0) {
  41413. if ((this._firstZDirtyIndex - 1) < childrenCount) {
  41414. var prevPrim = this._children[this._firstZDirtyIndex - 1];
  41415. prevLinPos = prevPrim._primLinearPosition;
  41416. startI = this._firstZDirtyIndex - 1;
  41417. startZ = prevPrim._zOrder;
  41418. }
  41419. }
  41420. var startPos = prevLinPos;
  41421. // Update the linear position of the primitive from the first one to the last inside this primitive, compute the total number of prim traversed
  41422. Prim2DBase._totalCount = 0;
  41423. for (var i = startI; i < childrenCount; i++) {
  41424. var child = this._children[i];
  41425. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  41426. }
  41427. // Compute the new Z-Order for all the primitives
  41428. // Add 20% to the current total count to reserve space for future insertions, except if we're rebuilding due to a zMinDelta reached
  41429. var zDelta = (this._zMax - startZ) / (Prim2DBase._totalCount * (Prim2DBase._zRebuildReentrency ? 1 : 1.2));
  41430. // 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.
  41431. if (zDelta < BABYLON.Canvas2D._zMinDelta) {
  41432. // 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...
  41433. if (Prim2DBase._zRebuildReentrency) {
  41434. var p = this._parent;
  41435. if (p == null) {
  41436. // 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...)
  41437. console.log("Can't compute Z-Order for " + this.id + "'s children, zDelta is too small, Z-Order is now in an unstable state");
  41438. Prim2DBase._zRebuildReentrency = false;
  41439. return;
  41440. }
  41441. p._firstZDirtyIndex = 0;
  41442. return p._updateZOrder();
  41443. }
  41444. Prim2DBase._zRebuildReentrency = true;
  41445. this._firstZDirtyIndex = 0;
  41446. this._updateZOrder();
  41447. Prim2DBase._zRebuildReentrency = false;
  41448. }
  41449. for (var i = startI; i < childrenCount; i++) {
  41450. var child = this._children[i];
  41451. child._updatePrimitiveZOrder(startPos, startZ, zDelta);
  41452. }
  41453. // Notify the Observers that we found during the Z change (we do it after to avoid any kind of re-entrance)
  41454. for (var _i = 0, _a = Prim2DBase._zOrderChangedNotifList; _i < _a.length; _i++) {
  41455. var p = _a[_i];
  41456. p._actualZOrderChangedObservable.notifyObservers(p.actualZOffset);
  41457. }
  41458. Prim2DBase._zOrderChangedNotifList.splice(0);
  41459. this._firstZDirtyIndex = Prim2DBase._bigInt;
  41460. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41461. };
  41462. Prim2DBase.prototype._updatePrimitiveLinearPosition = function (prevLinPos) {
  41463. if (this.isManualZOrder) {
  41464. return prevLinPos;
  41465. }
  41466. this._primLinearPosition = ++prevLinPos;
  41467. Prim2DBase._totalCount++;
  41468. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  41469. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  41470. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41471. var child = _a[_i];
  41472. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  41473. }
  41474. }
  41475. return prevLinPos;
  41476. };
  41477. Prim2DBase.prototype._updatePrimitiveZOrder = function (startPos, startZ, deltaZ) {
  41478. if (this.isManualZOrder) {
  41479. return null;
  41480. }
  41481. var newZ = startZ + ((this._primLinearPosition - startPos) * deltaZ);
  41482. var isFlat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  41483. this._setZOrder(newZ, false);
  41484. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  41485. this._firstZDirtyIndex = Prim2DBase._bigInt;
  41486. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41487. }
  41488. var curZ = newZ;
  41489. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  41490. if (isFlat) {
  41491. if (this._children.length > 0) {
  41492. //let childrenZOrder = startZ + ((this._children[0]._primLinearPosition - startPos) * deltaZ);
  41493. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41494. var child = _a[_i];
  41495. child._updatePrimitiveFlatZOrder(this._zOrder);
  41496. }
  41497. }
  41498. }
  41499. else {
  41500. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  41501. var child = _c[_b];
  41502. var r = child._updatePrimitiveZOrder(startPos, startZ, deltaZ);
  41503. if (r != null) {
  41504. curZ = r;
  41505. }
  41506. }
  41507. }
  41508. this._zMax = isFlat ? newZ : (curZ + deltaZ);
  41509. return curZ;
  41510. };
  41511. Prim2DBase.prototype._updatePrimitiveFlatZOrder = function (newZ) {
  41512. if (this.isManualZOrder) {
  41513. return;
  41514. }
  41515. this._setZOrder(newZ, false);
  41516. this._zMax = newZ;
  41517. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  41518. this._firstZDirtyIndex = Prim2DBase._bigInt;
  41519. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41520. }
  41521. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41522. var child = _a[_i];
  41523. child._updatePrimitiveFlatZOrder(newZ);
  41524. }
  41525. };
  41526. Prim2DBase.prototype._setZOrder = function (newZ, directEmit) {
  41527. if (newZ !== this._zOrder) {
  41528. this._zOrder = newZ;
  41529. this.onPrimBecomesDirty();
  41530. this.onZOrderChanged();
  41531. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  41532. if (directEmit) {
  41533. this._actualZOrderChangedObservable.notifyObservers(newZ);
  41534. }
  41535. else {
  41536. Prim2DBase._zOrderChangedNotifList.push(this);
  41537. }
  41538. }
  41539. }
  41540. };
  41541. Prim2DBase.prototype._updateRenderMode = function () {
  41542. };
  41543. /**
  41544. * This method is used to alter the contentArea of the Primitive before margin is applied.
  41545. * 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.
  41546. * @param primSize the current size of the primitive
  41547. * @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!
  41548. * @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!
  41549. */
  41550. Prim2DBase.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  41551. initialContentArea.copyFrom(primSize);
  41552. initialContentPosition.x = initialContentPosition.y = 0;
  41553. };
  41554. /**
  41555. * This method is used to calculate the new size of the primitive based on the content which must stay the same
  41556. * Check the Rectangle2D implementation for a concrete application.
  41557. * @param primSize the current size of the primitive
  41558. * @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!
  41559. */
  41560. Prim2DBase.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  41561. newPrimSize.copyFrom(primSize);
  41562. };
  41563. Prim2DBase.PRIM2DBASE_PROPCOUNT = 16;
  41564. Prim2DBase._bigInt = Math.pow(2, 30);
  41565. Prim2DBase._nullPosition = BABYLON.Vector2.Zero();
  41566. Prim2DBase.boundinbBoxReentrency = false;
  41567. Prim2DBase.nullSize = BABYLON.Size.Zero();
  41568. Prim2DBase._bMax = BABYLON.Vector2.Zero();
  41569. Prim2DBase._isCanvasInit = false;
  41570. Prim2DBase._t0 = new BABYLON.Matrix();
  41571. Prim2DBase._t1 = new BABYLON.Matrix();
  41572. Prim2DBase._t2 = new BABYLON.Matrix();
  41573. Prim2DBase._v0 = BABYLON.Vector2.Zero(); // Must stay with the value 0,0
  41574. Prim2DBase._transMtx = BABYLON.Matrix.Zero();
  41575. Prim2DBase._icPos = BABYLON.Vector2.Zero();
  41576. Prim2DBase._icArea = BABYLON.Size.Zero();
  41577. Prim2DBase._size = BABYLON.Size.Zero();
  41578. Prim2DBase._zOrderChangedNotifList = new Array();
  41579. Prim2DBase._zRebuildReentrency = false;
  41580. Prim2DBase._totalCount = 0;
  41581. __decorate([
  41582. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase.actualPositionProperty = pi; }, false, false, true)
  41583. ], Prim2DBase.prototype, "actualPosition", null);
  41584. __decorate([
  41585. BABYLON.dynamicLevelProperty(2, function (pi) { return Prim2DBase.positionProperty = pi; }, false, false, true)
  41586. ], Prim2DBase.prototype, "position", null);
  41587. __decorate([
  41588. BABYLON.dynamicLevelProperty(3, function (pi) { return Prim2DBase.sizeProperty = pi; }, false, true)
  41589. ], Prim2DBase.prototype, "size", null);
  41590. __decorate([
  41591. BABYLON.instanceLevelProperty(4, function (pi) { return Prim2DBase.rotationProperty = pi; }, false, true)
  41592. ], Prim2DBase.prototype, "rotation", null);
  41593. __decorate([
  41594. BABYLON.instanceLevelProperty(5, function (pi) { return Prim2DBase.scaleProperty = pi; }, false, true)
  41595. ], Prim2DBase.prototype, "scale", null);
  41596. __decorate([
  41597. BABYLON.dynamicLevelProperty(6, function (pi) { return Prim2DBase.originProperty = pi; }, false, true)
  41598. ], Prim2DBase.prototype, "origin", null);
  41599. __decorate([
  41600. BABYLON.dynamicLevelProperty(7, function (pi) { return Prim2DBase.levelVisibleProperty = pi; })
  41601. ], Prim2DBase.prototype, "levelVisible", null);
  41602. __decorate([
  41603. BABYLON.instanceLevelProperty(8, function (pi) { return Prim2DBase.isVisibleProperty = pi; })
  41604. ], Prim2DBase.prototype, "isVisible", null);
  41605. __decorate([
  41606. BABYLON.instanceLevelProperty(9, function (pi) { return Prim2DBase.zOrderProperty = pi; })
  41607. ], Prim2DBase.prototype, "zOrder", null);
  41608. __decorate([
  41609. BABYLON.dynamicLevelProperty(10, function (pi) { return Prim2DBase.marginProperty = pi; })
  41610. ], Prim2DBase.prototype, "margin", null);
  41611. __decorate([
  41612. BABYLON.dynamicLevelProperty(11, function (pi) { return Prim2DBase.paddingProperty = pi; })
  41613. ], Prim2DBase.prototype, "padding", null);
  41614. __decorate([
  41615. BABYLON.dynamicLevelProperty(12, function (pi) { return Prim2DBase.marginAlignmentProperty = pi; })
  41616. ], Prim2DBase.prototype, "marginAlignment", null);
  41617. __decorate([
  41618. BABYLON.instanceLevelProperty(13, function (pi) { return Prim2DBase.opacityProperty = pi; })
  41619. ], Prim2DBase.prototype, "opacity", null);
  41620. __decorate([
  41621. BABYLON.instanceLevelProperty(14, function (pi) { return Prim2DBase.scaleXProperty = pi; }, false, true)
  41622. ], Prim2DBase.prototype, "scaleX", null);
  41623. __decorate([
  41624. BABYLON.instanceLevelProperty(15, function (pi) { return Prim2DBase.scaleYProperty = pi; }, false, true)
  41625. ], Prim2DBase.prototype, "scaleY", null);
  41626. Prim2DBase = __decorate([
  41627. BABYLON.className("Prim2DBase")
  41628. ], Prim2DBase);
  41629. return Prim2DBase;
  41630. })(BABYLON.SmartPropertyPrim);
  41631. BABYLON.Prim2DBase = Prim2DBase;
  41632. })(BABYLON || (BABYLON = {}));
  41633. var BABYLON;
  41634. (function (BABYLON) {
  41635. var GroupInstanceInfo = (function () {
  41636. function GroupInstanceInfo(owner, mrc, partCount) {
  41637. this._partCount = partCount;
  41638. this.owner = owner;
  41639. this.modelRenderCache = mrc;
  41640. this.modelRenderCache.addRef();
  41641. this.partIndexFromId = new BABYLON.StringDictionary();
  41642. this._usedShaderCategories = new Array(partCount);
  41643. this._strides = new Array(partCount);
  41644. this._opaqueData = null;
  41645. this._alphaTestData = null;
  41646. this._transparentData = null;
  41647. this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
  41648. }
  41649. GroupInstanceInfo.prototype.dispose = function () {
  41650. if (this._isDisposed) {
  41651. return false;
  41652. }
  41653. if (this.modelRenderCache) {
  41654. this.modelRenderCache.dispose();
  41655. }
  41656. var engine = this.owner.owner.engine;
  41657. if (this.opaqueData) {
  41658. this.opaqueData.forEach(function (d) { return d.dispose(engine); });
  41659. this.opaqueData = null;
  41660. }
  41661. this.partIndexFromId = null;
  41662. this._isDisposed = true;
  41663. return true;
  41664. };
  41665. Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
  41666. get: function () {
  41667. return this._opaqueData != null;
  41668. },
  41669. enumerable: true,
  41670. configurable: true
  41671. });
  41672. Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
  41673. get: function () {
  41674. return this._alphaTestData != null;
  41675. },
  41676. enumerable: true,
  41677. configurable: true
  41678. });
  41679. Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
  41680. get: function () {
  41681. return this._transparentData != null;
  41682. },
  41683. enumerable: true,
  41684. configurable: true
  41685. });
  41686. Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
  41687. get: function () {
  41688. if (!this._opaqueData) {
  41689. this._opaqueData = new Array(this._partCount);
  41690. for (var i = 0; i < this._partCount; i++) {
  41691. this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
  41692. }
  41693. }
  41694. return this._opaqueData;
  41695. },
  41696. enumerable: true,
  41697. configurable: true
  41698. });
  41699. Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
  41700. get: function () {
  41701. if (!this._alphaTestData) {
  41702. this._alphaTestData = new Array(this._partCount);
  41703. for (var i = 0; i < this._partCount; i++) {
  41704. this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
  41705. }
  41706. }
  41707. return this._alphaTestData;
  41708. },
  41709. enumerable: true,
  41710. configurable: true
  41711. });
  41712. Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
  41713. get: function () {
  41714. if (!this._transparentData) {
  41715. this._transparentData = new Array(this._partCount);
  41716. for (var i = 0; i < this._partCount; i++) {
  41717. var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
  41718. this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
  41719. }
  41720. }
  41721. return this._transparentData;
  41722. },
  41723. enumerable: true,
  41724. configurable: true
  41725. });
  41726. GroupInstanceInfo.prototype.sortTransparentData = function () {
  41727. if (!this.transparentOrderDirty) {
  41728. return;
  41729. }
  41730. for (var i = 0; i < this._transparentData.length; i++) {
  41731. var td = this._transparentData[i];
  41732. td._partData.sort();
  41733. }
  41734. this.transparentOrderDirty = false;
  41735. };
  41736. Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
  41737. get: function () {
  41738. return this._usedShaderCategories;
  41739. },
  41740. enumerable: true,
  41741. configurable: true
  41742. });
  41743. Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
  41744. get: function () {
  41745. return this._strides;
  41746. },
  41747. enumerable: true,
  41748. configurable: true
  41749. });
  41750. return GroupInstanceInfo;
  41751. })();
  41752. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  41753. var TransparentSegment = (function () {
  41754. function TransparentSegment() {
  41755. this.groupInsanceInfo = null;
  41756. this.startZ = 0;
  41757. this.endZ = 0;
  41758. this.startDataIndex = 0;
  41759. this.endDataIndex = 0;
  41760. this.partBuffers = null;
  41761. }
  41762. TransparentSegment.prototype.dispose = function (engine) {
  41763. if (this.partBuffers) {
  41764. this.partBuffers.forEach(function (b) { return engine._releaseBuffer(b); });
  41765. this.partBuffers.splice(0);
  41766. this.partBuffers = null;
  41767. }
  41768. };
  41769. return TransparentSegment;
  41770. })();
  41771. BABYLON.TransparentSegment = TransparentSegment;
  41772. var GroupInfoPartData = (function () {
  41773. function GroupInfoPartData(stride) {
  41774. this._partData = null;
  41775. this._partBuffer = null;
  41776. this._partBufferSize = 0;
  41777. this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
  41778. this._isDisposed = false;
  41779. }
  41780. GroupInfoPartData.prototype.dispose = function (engine) {
  41781. if (this._isDisposed) {
  41782. return false;
  41783. }
  41784. if (this._partBuffer) {
  41785. engine._releaseBuffer(this._partBuffer);
  41786. this._partBuffer = null;
  41787. }
  41788. this._partData = null;
  41789. this._isDisposed = true;
  41790. };
  41791. return GroupInfoPartData;
  41792. })();
  41793. BABYLON.GroupInfoPartData = GroupInfoPartData;
  41794. var TransparentGroupInfoPartData = (function (_super) {
  41795. __extends(TransparentGroupInfoPartData, _super);
  41796. function TransparentGroupInfoPartData(stride, zoff) {
  41797. _super.call(this, stride);
  41798. this._partData.compareValueOffset = zoff;
  41799. this._partData.sortingAscending = false;
  41800. }
  41801. return TransparentGroupInfoPartData;
  41802. })(GroupInfoPartData);
  41803. BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
  41804. var ModelRenderCache = (function () {
  41805. function ModelRenderCache(engine, modelKey) {
  41806. this._engine = engine;
  41807. this._modelKey = modelKey;
  41808. this._nextKey = 1;
  41809. this._refCounter = 1;
  41810. this._partData = null;
  41811. }
  41812. ModelRenderCache.prototype.dispose = function () {
  41813. if (--this._refCounter !== 0) {
  41814. return false;
  41815. }
  41816. // Remove the Model Render Cache from the global dictionary
  41817. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  41818. if (edata) {
  41819. edata.DisposeModelRenderCache(this);
  41820. }
  41821. return true;
  41822. };
  41823. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  41824. get: function () {
  41825. return this._refCounter <= 0;
  41826. },
  41827. enumerable: true,
  41828. configurable: true
  41829. });
  41830. ModelRenderCache.prototype.addRef = function () {
  41831. return ++this._refCounter;
  41832. };
  41833. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  41834. get: function () {
  41835. return this._modelKey;
  41836. },
  41837. enumerable: true,
  41838. configurable: true
  41839. });
  41840. /**
  41841. * Render the model instances
  41842. * @param instanceInfo
  41843. * @param context
  41844. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  41845. */
  41846. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  41847. return true;
  41848. };
  41849. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  41850. for (var i = 0; i < this._partData.length; i++) {
  41851. if (this._partData[i]._partId === partId) {
  41852. return i;
  41853. }
  41854. }
  41855. return null;
  41856. };
  41857. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  41858. var i = this.getPartIndexFromId(partId);
  41859. if (i === null) {
  41860. return null;
  41861. }
  41862. var ci = this._partsClassInfo[i];
  41863. var categories = this._partData[i]._partUsedCategories;
  41864. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  41865. return res;
  41866. };
  41867. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  41868. var pd = this._partData[partIndex];
  41869. var offset = (pd._partDataStride / 4) * elementCount;
  41870. var pci = this._partsClassInfo[partIndex];
  41871. var self = this;
  41872. pci.fullContent.forEach(function (k, v) {
  41873. if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
  41874. switch (v.dataType) {
  41875. case 4 /* float */:
  41876. {
  41877. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  41878. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  41879. break;
  41880. }
  41881. case 0 /* Vector2 */:
  41882. {
  41883. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  41884. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  41885. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  41886. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  41887. break;
  41888. }
  41889. case 5 /* Color3 */:
  41890. case 1 /* Vector3 */:
  41891. {
  41892. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  41893. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  41894. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  41895. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  41896. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  41897. break;
  41898. }
  41899. case 6 /* Color4 */:
  41900. case 2 /* Vector4 */:
  41901. {
  41902. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  41903. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  41904. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  41905. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  41906. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  41907. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  41908. break;
  41909. }
  41910. default:
  41911. }
  41912. }
  41913. });
  41914. };
  41915. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  41916. // let i = this.getPartIndexFromId(partId);
  41917. // if (i === null) {
  41918. // return null;
  41919. // }
  41920. // let pci = this._partsClassInfo[i];
  41921. // pci.fullContent.forEach((k, v) => {
  41922. // if (uniforms.indexOf(v.attributeName) !== -1) {
  41923. // v.uniformLocation = effect.getUniform(v.attributeName);
  41924. // }
  41925. // });
  41926. //}
  41927. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  41928. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  41929. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  41930. return ModelRenderCache;
  41931. })();
  41932. BABYLON.ModelRenderCache = ModelRenderCache;
  41933. var ModelRenderCachePartData = (function () {
  41934. function ModelRenderCachePartData() {
  41935. }
  41936. return ModelRenderCachePartData;
  41937. })();
  41938. BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
  41939. })(BABYLON || (BABYLON = {}));
  41940. var BABYLON;
  41941. (function (BABYLON) {
  41942. var InstanceClassInfo = (function () {
  41943. function InstanceClassInfo(base) {
  41944. this._baseInfo = base;
  41945. this._nextOffset = new BABYLON.StringDictionary();
  41946. this._attributes = new Array();
  41947. }
  41948. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  41949. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  41950. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  41951. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  41952. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  41953. if (push) {
  41954. this._attributes.push(propInfo);
  41955. }
  41956. };
  41957. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  41958. var catInline = ";" + categories.join(";") + ";";
  41959. var res = new Array();
  41960. var curInfo = this;
  41961. while (curInfo) {
  41962. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  41963. var attrib = _a[_i];
  41964. // 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
  41965. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  41966. var index = effect.getAttributeLocationByName(attrib.attributeName);
  41967. var iai = new BABYLON.InstancingAttributeInfo();
  41968. iai.index = index;
  41969. 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)
  41970. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  41971. iai.attributeName = attrib.attributeName;
  41972. res.push(iai);
  41973. }
  41974. }
  41975. curInfo = curInfo._baseInfo;
  41976. }
  41977. return res;
  41978. };
  41979. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  41980. var res = new Array();
  41981. var curInfo = this;
  41982. while (curInfo) {
  41983. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  41984. var attrib = _a[_i];
  41985. // 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
  41986. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  41987. res.push(attrib.attributeName);
  41988. }
  41989. }
  41990. curInfo = curInfo._baseInfo;
  41991. }
  41992. return res;
  41993. };
  41994. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  41995. var curOffset = 0;
  41996. var curBase = this._baseInfo;
  41997. while (curBase) {
  41998. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  41999. curBase = curBase._baseInfo;
  42000. }
  42001. return curOffset;
  42002. };
  42003. return InstanceClassInfo;
  42004. })();
  42005. BABYLON.InstanceClassInfo = InstanceClassInfo;
  42006. var InstancePropInfo = (function () {
  42007. function InstancePropInfo() {
  42008. this.instanceOffset = new BABYLON.StringDictionary();
  42009. }
  42010. InstancePropInfo.prototype.setSize = function (val) {
  42011. if (val instanceof BABYLON.Vector2) {
  42012. this.size = 8;
  42013. this.dataType = 0 /* Vector2 */;
  42014. return;
  42015. }
  42016. if (val instanceof BABYLON.Vector3) {
  42017. this.size = 12;
  42018. this.dataType = 1 /* Vector3 */;
  42019. return;
  42020. }
  42021. if (val instanceof BABYLON.Vector4) {
  42022. this.size = 16;
  42023. this.dataType = 2 /* Vector4 */;
  42024. return;
  42025. }
  42026. if (val instanceof BABYLON.Matrix) {
  42027. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  42028. }
  42029. if (typeof (val) === "number") {
  42030. this.size = 4;
  42031. this.dataType = 4 /* float */;
  42032. return;
  42033. }
  42034. if (val instanceof BABYLON.Color3) {
  42035. this.size = 12;
  42036. this.dataType = 5 /* Color3 */;
  42037. return;
  42038. }
  42039. if (val instanceof BABYLON.Color4) {
  42040. this.size = 16;
  42041. this.dataType = 6 /* Color4 */;
  42042. return;
  42043. }
  42044. if (val instanceof BABYLON.Size) {
  42045. this.size = 8;
  42046. this.dataType = 7 /* Size */;
  42047. return;
  42048. }
  42049. return;
  42050. };
  42051. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  42052. switch (this.dataType) {
  42053. case 0 /* Vector2 */:
  42054. {
  42055. var v = val;
  42056. array[offset + 0] = v.x;
  42057. array[offset + 1] = v.y;
  42058. break;
  42059. }
  42060. case 1 /* Vector3 */:
  42061. {
  42062. var v = val;
  42063. array[offset + 0] = v.x;
  42064. array[offset + 1] = v.y;
  42065. array[offset + 2] = v.z;
  42066. break;
  42067. }
  42068. case 2 /* Vector4 */:
  42069. {
  42070. var v = val;
  42071. array[offset + 0] = v.x;
  42072. array[offset + 1] = v.y;
  42073. array[offset + 2] = v.z;
  42074. array[offset + 3] = v.w;
  42075. break;
  42076. }
  42077. case 5 /* Color3 */:
  42078. {
  42079. var v = val;
  42080. array[offset + 0] = v.r;
  42081. array[offset + 1] = v.g;
  42082. array[offset + 2] = v.b;
  42083. break;
  42084. }
  42085. case 6 /* Color4 */:
  42086. {
  42087. var v = val;
  42088. array[offset + 0] = v.r;
  42089. array[offset + 1] = v.g;
  42090. array[offset + 2] = v.b;
  42091. array[offset + 3] = v.a;
  42092. break;
  42093. }
  42094. case 4 /* float */:
  42095. {
  42096. var v = val;
  42097. array[offset] = v;
  42098. break;
  42099. }
  42100. case 3 /* Matrix */:
  42101. {
  42102. var v = val;
  42103. for (var i = 0; i < 16; i++) {
  42104. array[offset + i] = v.m[i];
  42105. }
  42106. break;
  42107. }
  42108. case 7 /* Size */:
  42109. {
  42110. var s = val;
  42111. array[offset + 0] = s.width;
  42112. array[offset + 1] = s.height;
  42113. break;
  42114. }
  42115. }
  42116. };
  42117. return InstancePropInfo;
  42118. })();
  42119. BABYLON.InstancePropInfo = InstancePropInfo;
  42120. function instanceData(category, shaderAttributeName) {
  42121. return function (target, propName, descriptor) {
  42122. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  42123. var node = dic.getLevelOf(target);
  42124. var instanceDataName = propName;
  42125. shaderAttributeName = shaderAttributeName || instanceDataName;
  42126. var info = node.levelContent.get(instanceDataName);
  42127. if (info) {
  42128. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  42129. }
  42130. info = new InstancePropInfo();
  42131. info.attributeName = shaderAttributeName;
  42132. info.category = category || null;
  42133. if (info.category) {
  42134. info.delimitedCategory = ";" + info.category + ";";
  42135. }
  42136. node.levelContent.add(instanceDataName, info);
  42137. descriptor.get = function () {
  42138. return null;
  42139. };
  42140. descriptor.set = function (val) {
  42141. // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
  42142. // Quit if it's the case, otherwise we could overwrite data somewhere...
  42143. if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
  42144. return;
  42145. }
  42146. if (!info.size) {
  42147. info.setSize(val);
  42148. node.classContent.mapProperty(info, true);
  42149. }
  42150. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  42151. node.classContent.mapProperty(info, false);
  42152. }
  42153. var obj = this;
  42154. if (obj.dataBuffer && obj.dataElements) {
  42155. var offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  42156. info.writeData(obj.dataBuffer.buffer, offset, val);
  42157. }
  42158. };
  42159. };
  42160. }
  42161. BABYLON.instanceData = instanceData;
  42162. var InstanceDataBase = (function () {
  42163. function InstanceDataBase(partId, dataElementCount) {
  42164. this.id = partId;
  42165. this.curElement = 0;
  42166. this._dataElementCount = dataElementCount;
  42167. this.renderMode = 0;
  42168. this.arrayLengthChanged = false;
  42169. }
  42170. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  42171. get: function () {
  42172. return null;
  42173. },
  42174. enumerable: true,
  42175. configurable: true
  42176. });
  42177. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  42178. get: function () {
  42179. return null;
  42180. },
  42181. enumerable: true,
  42182. configurable: true
  42183. });
  42184. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  42185. get: function () {
  42186. return null;
  42187. },
  42188. enumerable: true,
  42189. configurable: true
  42190. });
  42191. Object.defineProperty(InstanceDataBase.prototype, "opacity", {
  42192. get: function () {
  42193. return null;
  42194. },
  42195. enumerable: true,
  42196. configurable: true
  42197. });
  42198. InstanceDataBase.prototype.getClassTreeInfo = function () {
  42199. if (!this.typeInfo) {
  42200. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  42201. }
  42202. return this.typeInfo;
  42203. };
  42204. InstanceDataBase.prototype.allocElements = function () {
  42205. if (!this.dataBuffer || this.dataElements) {
  42206. return;
  42207. }
  42208. var res = new Array(this.dataElementCount);
  42209. for (var i = 0; i < this.dataElementCount; i++) {
  42210. res[i] = this.dataBuffer.allocElement();
  42211. }
  42212. this.dataElements = res;
  42213. };
  42214. InstanceDataBase.prototype.freeElements = function () {
  42215. if (!this.dataElements) {
  42216. return;
  42217. }
  42218. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  42219. var ei = _a[_i];
  42220. this.dataBuffer.freeElement(ei);
  42221. }
  42222. this.dataElements = null;
  42223. };
  42224. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  42225. get: function () {
  42226. return this._dataElementCount;
  42227. },
  42228. set: function (value) {
  42229. if (value === this._dataElementCount) {
  42230. return;
  42231. }
  42232. this.arrayLengthChanged = true;
  42233. this.freeElements();
  42234. this._dataElementCount = value;
  42235. this.allocElements();
  42236. },
  42237. enumerable: true,
  42238. configurable: true
  42239. });
  42240. __decorate([
  42241. instanceData()
  42242. ], InstanceDataBase.prototype, "zBias", null);
  42243. __decorate([
  42244. instanceData()
  42245. ], InstanceDataBase.prototype, "transformX", null);
  42246. __decorate([
  42247. instanceData()
  42248. ], InstanceDataBase.prototype, "transformY", null);
  42249. __decorate([
  42250. instanceData()
  42251. ], InstanceDataBase.prototype, "opacity", null);
  42252. return InstanceDataBase;
  42253. })();
  42254. BABYLON.InstanceDataBase = InstanceDataBase;
  42255. var RenderablePrim2D = (function (_super) {
  42256. __extends(RenderablePrim2D, _super);
  42257. function RenderablePrim2D(settings) {
  42258. _super.call(this, settings);
  42259. this._isTransparent = false;
  42260. this._isAlphaTest = false;
  42261. this._transparentPrimitiveInfo = null;
  42262. }
  42263. Object.defineProperty(RenderablePrim2D.prototype, "isAlphaTest", {
  42264. get: function () {
  42265. return this._isAlphaTest;
  42266. },
  42267. set: function (value) {
  42268. if (this._isAlphaTest === value) {
  42269. return;
  42270. }
  42271. this._isAlphaTest = value;
  42272. this._updateRenderMode();
  42273. },
  42274. enumerable: true,
  42275. configurable: true
  42276. });
  42277. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  42278. get: function () {
  42279. return this._isTransparent || (this._opacity < 1);
  42280. },
  42281. set: function (value) {
  42282. if (this._isTransparent === value) {
  42283. return;
  42284. }
  42285. this._isTransparent = value;
  42286. this._updateRenderMode();
  42287. },
  42288. enumerable: true,
  42289. configurable: true
  42290. });
  42291. Object.defineProperty(RenderablePrim2D.prototype, "renderMode", {
  42292. get: function () {
  42293. return this._renderMode;
  42294. },
  42295. enumerable: true,
  42296. configurable: true
  42297. });
  42298. /**
  42299. * Dispose the primitive and its resources, remove it from its parent
  42300. */
  42301. RenderablePrim2D.prototype.dispose = function () {
  42302. if (!_super.prototype.dispose.call(this)) {
  42303. return false;
  42304. }
  42305. if (this.renderGroup) {
  42306. this.renderGroup._setCacheGroupDirty();
  42307. }
  42308. if (this._transparentPrimitiveInfo) {
  42309. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  42310. this._transparentPrimitiveInfo = null;
  42311. }
  42312. if (this._instanceDataParts) {
  42313. this._cleanupInstanceDataParts();
  42314. }
  42315. if (this._modelRenderCache) {
  42316. this._modelRenderCache.dispose();
  42317. this._modelRenderCache = null;
  42318. }
  42319. if (this._instanceDataParts) {
  42320. this._instanceDataParts.forEach(function (p) {
  42321. p.freeElements();
  42322. });
  42323. this._instanceDataParts = null;
  42324. }
  42325. return true;
  42326. };
  42327. RenderablePrim2D.prototype._cleanupInstanceDataParts = function () {
  42328. var gii = null;
  42329. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  42330. var part = _a[_i];
  42331. part.freeElements();
  42332. gii = part.groupInstanceInfo;
  42333. }
  42334. if (gii) {
  42335. var usedCount = 0;
  42336. if (gii.hasOpaqueData) {
  42337. var od = gii.opaqueData[0];
  42338. usedCount += od._partData.usedElementCount;
  42339. }
  42340. if (gii.hasAlphaTestData) {
  42341. var atd = gii.alphaTestData[0];
  42342. usedCount += atd._partData.usedElementCount;
  42343. }
  42344. if (gii.hasTransparentData) {
  42345. var td = gii.transparentData[0];
  42346. usedCount += td._partData.usedElementCount;
  42347. }
  42348. if (usedCount === 0) {
  42349. this.renderGroup._renderableData._renderGroupInstancesInfo.remove(gii.modelRenderCache.modelKey);
  42350. }
  42351. gii.modelRenderCache.dispose();
  42352. }
  42353. this._instanceDataParts = null;
  42354. };
  42355. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  42356. _super.prototype._prepareRenderPre.call(this, context);
  42357. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  42358. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty) && this._instanceDataParts) {
  42359. this._cleanupInstanceDataParts();
  42360. }
  42361. // Need to create the model?
  42362. var setupModelRenderCache = false;
  42363. if (!this._modelRenderCache || this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty)) {
  42364. setupModelRenderCache = this._createModelRenderCache();
  42365. }
  42366. var gii = null;
  42367. var newInstance = false;
  42368. // Need to create the instance data parts?
  42369. if (!this._instanceDataParts) {
  42370. // Yes, flag it for later, more processing will have to be done
  42371. newInstance = true;
  42372. gii = this._createModelDataParts();
  42373. }
  42374. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  42375. if (setupModelRenderCache) {
  42376. this.setupModelRenderCache(this._modelRenderCache);
  42377. }
  42378. // 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.
  42379. // 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.
  42380. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged) || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep)) {
  42381. this._updateInstanceDataParts(gii);
  42382. }
  42383. };
  42384. RenderablePrim2D.prototype._createModelRenderCache = function () {
  42385. var _this = this;
  42386. var setupModelRenderCache = false;
  42387. if (this._modelRenderCache) {
  42388. this._modelRenderCache.dispose();
  42389. }
  42390. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  42391. var mrc = _this.createModelRenderCache(key);
  42392. setupModelRenderCache = true;
  42393. return mrc;
  42394. });
  42395. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  42396. // if this is still false it means the MRC already exists, so we add a reference to it
  42397. if (!setupModelRenderCache) {
  42398. this._modelRenderCache.addRef();
  42399. }
  42400. return setupModelRenderCache;
  42401. };
  42402. RenderablePrim2D.prototype._createModelDataParts = function () {
  42403. var _this = this;
  42404. // Create the instance data parts of the primitive and store them
  42405. var parts = this.createInstanceDataParts();
  42406. this._instanceDataParts = parts;
  42407. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  42408. if (!this._modelRenderCache._partData) {
  42409. this._setupModelRenderCache(parts);
  42410. }
  42411. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  42412. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  42413. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  42414. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) {
  42415. var res = new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache, _this._modelRenderCache._partData.length);
  42416. for (var j = 0; j < _this._modelRenderCache._partData.length; j++) {
  42417. var part = _this._instanceDataParts[j];
  42418. res.partIndexFromId.add(part.id.toString(), j);
  42419. res.usedShaderCategories[j] = ";" + _this.getUsedShaderCategories(part).join(";") + ";";
  42420. res.strides[j] = _this._modelRenderCache._partData[j]._partDataStride;
  42421. }
  42422. return res;
  42423. });
  42424. // Get the GroupInfoDataPart corresponding to the render category of the part
  42425. var rm = 0;
  42426. var gipd = null;
  42427. if (this.isTransparent) {
  42428. gipd = gii.transparentData;
  42429. rm = BABYLON.Render2DContext.RenderModeTransparent;
  42430. }
  42431. else if (this.isAlphaTest) {
  42432. gipd = gii.alphaTestData;
  42433. rm = BABYLON.Render2DContext.RenderModeAlphaTest;
  42434. }
  42435. else {
  42436. gipd = gii.opaqueData;
  42437. rm = BABYLON.Render2DContext.RenderModeOpaque;
  42438. }
  42439. // For each instance data part of the primitive, allocate the instanced element it needs for render
  42440. for (var i = 0; i < parts.length; i++) {
  42441. var part = parts[i];
  42442. part.dataBuffer = gipd[i]._partData;
  42443. part.allocElements();
  42444. part.renderMode = rm;
  42445. part.groupInstanceInfo = gii;
  42446. }
  42447. return gii;
  42448. };
  42449. RenderablePrim2D.prototype._setupModelRenderCache = function (parts) {
  42450. var ctiArray = new Array();
  42451. this._modelRenderCache._partData = new Array();
  42452. for (var _i = 0; _i < parts.length; _i++) {
  42453. var dataPart = parts[_i];
  42454. var pd = new BABYLON.ModelRenderCachePartData();
  42455. this._modelRenderCache._partData.push(pd);
  42456. var cat = this.getUsedShaderCategories(dataPart);
  42457. var cti = dataPart.getClassTreeInfo();
  42458. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  42459. var curVisible = this.isVisible;
  42460. this.isVisible = true;
  42461. // 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.
  42462. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  42463. var joinCat = ";" + cat.join(";") + ";";
  42464. pd._partJoinedUsedCategories = joinCat;
  42465. InstanceClassInfo._CurCategories = joinCat;
  42466. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  42467. if (!this.refreshInstanceDataPart(dataPart)) {
  42468. console.log("Layout construction for " + BABYLON.Tools.getClassName(this._instanceDataParts[0]) + " failed because refresh returned false");
  42469. }
  42470. this.afterRefreshForLayoutConstruction(dataPart, obj);
  42471. this.isVisible = curVisible;
  42472. var size = 0;
  42473. cti.fullContent.forEach(function (k, v) {
  42474. if (!v.category || cat.indexOf(v.category) !== -1) {
  42475. if (v.attributeName === "zBias") {
  42476. pd._zBiasOffset = v.instanceOffset.get(joinCat);
  42477. }
  42478. if (!v.size) {
  42479. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  42480. }
  42481. else {
  42482. size += v.size;
  42483. }
  42484. }
  42485. });
  42486. pd._partDataStride = size;
  42487. pd._partUsedCategories = cat;
  42488. pd._partId = dataPart.id;
  42489. ctiArray.push(cti);
  42490. }
  42491. this._modelRenderCache._partsClassInfo = ctiArray;
  42492. };
  42493. RenderablePrim2D.prototype.onZOrderChanged = function () {
  42494. if (this.isTransparent && this._transparentPrimitiveInfo) {
  42495. this.renderGroup._renderableData.transparentPrimitiveZChanged(this._transparentPrimitiveInfo);
  42496. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  42497. // Flag the transparentData dirty has will have to sort it again
  42498. gii.transparentOrderDirty = true;
  42499. }
  42500. };
  42501. RenderablePrim2D.prototype._updateInstanceDataParts = function (gii) {
  42502. // Fetch the GroupInstanceInfo if we don't already have it
  42503. var rd = this.renderGroup._renderableData;
  42504. if (!gii) {
  42505. gii = rd._renderGroupInstancesInfo.get(this.modelKey);
  42506. }
  42507. var isTransparent = this.isTransparent;
  42508. var isAlphaTest = this.isAlphaTest;
  42509. var wereTransparent = false;
  42510. // Check a render mode change
  42511. var rmChanged = false;
  42512. if (this._instanceDataParts.length > 0) {
  42513. var firstPart = this._instanceDataParts[0];
  42514. var partRM = firstPart.renderMode;
  42515. var curRM = this.renderMode;
  42516. if (partRM !== curRM) {
  42517. wereTransparent = partRM === BABYLON.Render2DContext.RenderModeTransparent;
  42518. rmChanged = true;
  42519. var gipd;
  42520. switch (curRM) {
  42521. case BABYLON.Render2DContext.RenderModeTransparent:
  42522. gipd = gii.transparentData;
  42523. break;
  42524. case BABYLON.Render2DContext.RenderModeAlphaTest:
  42525. gipd = gii.alphaTestData;
  42526. break;
  42527. default:
  42528. gipd = gii.opaqueData;
  42529. }
  42530. for (var i = 0; i < this._instanceDataParts.length; i++) {
  42531. var part = this._instanceDataParts[i];
  42532. part.freeElements();
  42533. part.dataBuffer = gipd[i]._partData;
  42534. part.renderMode = curRM;
  42535. }
  42536. }
  42537. }
  42538. // Handle changes related to ZOffset
  42539. var visChanged = this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged);
  42540. if (isTransparent || wereTransparent) {
  42541. // Handle visibility change, which is also triggered when the primitive just got created
  42542. if (visChanged || rmChanged) {
  42543. if (this.isVisible && !wereTransparent) {
  42544. if (!this._transparentPrimitiveInfo) {
  42545. // Add the primitive to the list of transparent ones in the group that render is
  42546. this._transparentPrimitiveInfo = rd.addNewTransparentPrimitiveInfo(this, gii);
  42547. }
  42548. }
  42549. else {
  42550. if (this._transparentPrimitiveInfo) {
  42551. rd.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  42552. this._transparentPrimitiveInfo = null;
  42553. }
  42554. }
  42555. gii.transparentOrderDirty = true;
  42556. }
  42557. }
  42558. var rebuildTrans = false;
  42559. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  42560. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  42561. var part = _a[_i];
  42562. var justAllocated = false;
  42563. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  42564. if (!part.dataElements && (visChanged || rmChanged || this.isVisible)) {
  42565. part.allocElements();
  42566. justAllocated = true;
  42567. }
  42568. InstanceClassInfo._CurCategories = gii.usedShaderCategories[gii.partIndexFromId.get(part.id.toString())];
  42569. // Will return false if the instance should not be rendered (not visible or other any reasons)
  42570. part.arrayLengthChanged = false;
  42571. if (!this.refreshInstanceDataPart(part)) {
  42572. // Free the data element
  42573. if (part.dataElements) {
  42574. part.freeElements();
  42575. }
  42576. }
  42577. rebuildTrans = rebuildTrans || part.arrayLengthChanged || justAllocated;
  42578. }
  42579. this._instanceDirtyFlags = 0;
  42580. // Make the appropriate data dirty
  42581. if (isTransparent) {
  42582. gii.transparentDirty = true;
  42583. if (rebuildTrans) {
  42584. rd._transparentListChanged = true;
  42585. }
  42586. }
  42587. else if (isAlphaTest) {
  42588. gii.alphaTestDirty = true;
  42589. }
  42590. else {
  42591. gii.opaqueDirty = true;
  42592. }
  42593. this._clearFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged); // Reset the flag as we've handled the case
  42594. };
  42595. RenderablePrim2D.prototype._updateTransparentSegmentIndices = function (ts) {
  42596. var minOff = BABYLON.Prim2DBase._bigInt;
  42597. var maxOff = 0;
  42598. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  42599. var part = _a[_i];
  42600. if (part && part.dataElements) {
  42601. part.dataBuffer.pack();
  42602. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  42603. var el = _c[_b];
  42604. minOff = Math.min(minOff, el.offset);
  42605. maxOff = Math.max(maxOff, el.offset);
  42606. }
  42607. ts.startDataIndex = minOff / part.dataBuffer.stride;
  42608. ts.endDataIndex = (maxOff / part.dataBuffer.stride) + 1; // +1 for exclusive
  42609. }
  42610. }
  42611. };
  42612. RenderablePrim2D.prototype._getPrimitiveLastIndex = function () {
  42613. var maxOff = 0;
  42614. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  42615. var part = _a[_i];
  42616. if (part) {
  42617. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  42618. var el = _c[_b];
  42619. maxOff = Math.max(maxOff, el.offset);
  42620. }
  42621. return (maxOff / part.dataBuffer.stride) + 1; // +1 for exclusive
  42622. }
  42623. }
  42624. };
  42625. // This internal method is mainly used for transparency processing
  42626. RenderablePrim2D.prototype._getNextPrimZOrder = function () {
  42627. var length = this._instanceDataParts.length;
  42628. for (var i = 0; i < length; i++) {
  42629. var part = this._instanceDataParts[i];
  42630. if (part) {
  42631. var stride = part.dataBuffer.stride;
  42632. var lastElementOffset = part.dataElements[part.dataElements.length - 1].offset;
  42633. // check if it's the last in the DFA
  42634. if (part.dataBuffer.totalElementCount * stride <= lastElementOffset) {
  42635. return null;
  42636. }
  42637. // Return the Z of the next primitive that lies in the DFA
  42638. return part.dataBuffer[lastElementOffset + stride + this.modelRenderCache._partData[i]._zBiasOffset];
  42639. }
  42640. }
  42641. return null;
  42642. };
  42643. // This internal method is mainly used for transparency processing
  42644. RenderablePrim2D.prototype._getPrevPrimZOrder = function () {
  42645. var length = this._instanceDataParts.length;
  42646. for (var i = 0; i < length; i++) {
  42647. var part = this._instanceDataParts[i];
  42648. if (part) {
  42649. var stride = part.dataBuffer.stride;
  42650. var firstElementOffset = part.dataElements[0].offset;
  42651. // check if it's the first in the DFA
  42652. if (firstElementOffset === 0) {
  42653. return null;
  42654. }
  42655. // Return the Z of the previous primitive that lies in the DFA
  42656. return part.dataBuffer[firstElementOffset - stride + this.modelRenderCache._partData[i]._zBiasOffset];
  42657. }
  42658. }
  42659. return null;
  42660. };
  42661. /**
  42662. * Transform a given point using the Primitive's origin setting.
  42663. * This method requires the Primitive's actualSize to be accurate
  42664. * @param p the point to transform
  42665. * @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.
  42666. * @param res an allocated Vector2 that will receive the transformed content
  42667. */
  42668. RenderablePrim2D.prototype.transformPointWithOriginByRef = function (p, originOffset, res) {
  42669. var actualSize = this.actualSize;
  42670. res.x = p.x - ((this.origin.x + (originOffset ? originOffset.x : 0)) * actualSize.width);
  42671. res.y = p.y - ((this.origin.y + (originOffset ? originOffset.y : 0)) * actualSize.height);
  42672. };
  42673. RenderablePrim2D.prototype.transformPointWithOriginToRef = function (p, originOffset, res) {
  42674. this.transformPointWithOriginByRef(p, originOffset, res);
  42675. return res;
  42676. };
  42677. /**
  42678. * Get the info for a given effect based on the dataPart metadata
  42679. * @param dataPartId partId in part list to get the info
  42680. * @param vertexBufferAttributes vertex buffer attributes to manually add
  42681. * @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
  42682. */
  42683. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes, useInstanced) {
  42684. if (useInstanced === void 0) { useInstanced = null; }
  42685. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  42686. if (!dataPart) {
  42687. return null;
  42688. }
  42689. var instancedArray = this.owner.supportInstancedArray;
  42690. if (useInstanced != null) {
  42691. // Check if the caller ask for Instanced Array and the engine does not support it, return null if it's the case
  42692. if (useInstanced && instancedArray === false) {
  42693. return null;
  42694. }
  42695. // Use the caller's setting
  42696. instancedArray = useInstanced;
  42697. }
  42698. var cti = dataPart.getClassTreeInfo();
  42699. var categories = this.getUsedShaderCategories(dataPart);
  42700. var att = cti.classContent.getShaderAttributes(categories);
  42701. var defines = "";
  42702. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  42703. if (instancedArray) {
  42704. defines += "#define Instanced\n";
  42705. }
  42706. return { attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes, uniforms: instancedArray ? [] : att, defines: defines };
  42707. };
  42708. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  42709. get: function () {
  42710. return this._modelRenderCache;
  42711. },
  42712. enumerable: true,
  42713. configurable: true
  42714. });
  42715. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey) {
  42716. return null;
  42717. };
  42718. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  42719. };
  42720. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  42721. return null;
  42722. };
  42723. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  42724. return [];
  42725. };
  42726. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  42727. };
  42728. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  42729. };
  42730. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  42731. if (!this.isVisible) {
  42732. return false;
  42733. }
  42734. part.isVisible = this.isVisible;
  42735. // 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)
  42736. if (part.dataElementCount === 1) {
  42737. part.curElement = 0;
  42738. this.updateInstanceDataPart(part);
  42739. }
  42740. return true;
  42741. };
  42742. /**
  42743. * Update the instanceDataBase level properties of a part
  42744. * @param part the part to update
  42745. * @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).
  42746. */
  42747. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset) {
  42748. if (positionOffset === void 0) { positionOffset = null; }
  42749. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform);
  42750. var size = this.renderGroup.viewportSize;
  42751. var zBias = this.actualZOffset;
  42752. var offX = 0;
  42753. var offY = 0;
  42754. // If there's an offset, apply the global transformation matrix on it to get a global offset
  42755. if (positionOffset) {
  42756. offX = positionOffset.x * t.m[0] + positionOffset.y * t.m[4];
  42757. offY = positionOffset.x * t.m[1] + positionOffset.y * t.m[5];
  42758. }
  42759. // 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
  42760. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  42761. // So for X:
  42762. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  42763. // - 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].
  42764. var w = size.width;
  42765. var h = size.height;
  42766. var invZBias = 1 / zBias;
  42767. 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);
  42768. 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);
  42769. part.transformX = tx;
  42770. part.transformY = ty;
  42771. part.opacity = this.actualOpacity;
  42772. // 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)
  42773. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  42774. };
  42775. RenderablePrim2D.prototype._updateRenderMode = function () {
  42776. if (this.isTransparent) {
  42777. this._renderMode = BABYLON.Render2DContext.RenderModeTransparent;
  42778. }
  42779. else if (this.isAlphaTest) {
  42780. this._renderMode = BABYLON.Render2DContext.RenderModeAlphaTest;
  42781. }
  42782. else {
  42783. this._renderMode = BABYLON.Render2DContext.RenderModeOpaque;
  42784. }
  42785. };
  42786. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  42787. __decorate([
  42788. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 0, function (pi) { return RenderablePrim2D.isAlphaTestProperty = pi; })
  42789. ], RenderablePrim2D.prototype, "isAlphaTest", null);
  42790. __decorate([
  42791. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D.isTransparentProperty = pi; })
  42792. ], RenderablePrim2D.prototype, "isTransparent", null);
  42793. RenderablePrim2D = __decorate([
  42794. BABYLON.className("RenderablePrim2D")
  42795. ], RenderablePrim2D);
  42796. return RenderablePrim2D;
  42797. })(BABYLON.Prim2DBase);
  42798. BABYLON.RenderablePrim2D = RenderablePrim2D;
  42799. })(BABYLON || (BABYLON = {}));
  42800. var BABYLON;
  42801. (function (BABYLON) {
  42802. var Shape2D = (function (_super) {
  42803. __extends(Shape2D, _super);
  42804. function Shape2D(settings) {
  42805. _super.call(this, settings);
  42806. if (!settings) {
  42807. settings = {};
  42808. }
  42809. var borderBrush = null;
  42810. if (settings.border) {
  42811. if (typeof (settings.border) === "string") {
  42812. borderBrush = BABYLON.Canvas2D.GetBrushFromString(settings.border);
  42813. }
  42814. else {
  42815. borderBrush = settings.border;
  42816. }
  42817. }
  42818. var fillBrush = null;
  42819. if (settings.fill) {
  42820. if (typeof (settings.fill) === "string") {
  42821. fillBrush = BABYLON.Canvas2D.GetBrushFromString(settings.fill);
  42822. }
  42823. else {
  42824. fillBrush = settings.fill;
  42825. }
  42826. }
  42827. this.border = borderBrush;
  42828. this.fill = fillBrush;
  42829. this.borderThickness = settings.borderThickness;
  42830. }
  42831. Object.defineProperty(Shape2D.prototype, "border", {
  42832. get: function () {
  42833. return this._border;
  42834. },
  42835. set: function (value) {
  42836. this._border = value;
  42837. this._updateTransparencyStatus();
  42838. },
  42839. enumerable: true,
  42840. configurable: true
  42841. });
  42842. Object.defineProperty(Shape2D.prototype, "fill", {
  42843. /**
  42844. * Get/set the brush to render the Fill part of the Primitive
  42845. */
  42846. get: function () {
  42847. return this._fill;
  42848. },
  42849. set: function (value) {
  42850. this._fill = value;
  42851. this._updateTransparencyStatus();
  42852. },
  42853. enumerable: true,
  42854. configurable: true
  42855. });
  42856. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  42857. get: function () {
  42858. return this._borderThickness;
  42859. },
  42860. set: function (value) {
  42861. this._borderThickness = value;
  42862. },
  42863. enumerable: true,
  42864. configurable: true
  42865. });
  42866. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  42867. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  42868. // Fill Part
  42869. if (dataPart.id === Shape2D.SHAPE2D_FILLPARTID) {
  42870. var fill = this.fill;
  42871. if (fill instanceof BABYLON.SolidColorBrush2D) {
  42872. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLSOLID);
  42873. }
  42874. if (fill instanceof BABYLON.GradientColorBrush2D) {
  42875. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT);
  42876. }
  42877. }
  42878. // Border Part
  42879. if (dataPart.id === Shape2D.SHAPE2D_BORDERPARTID) {
  42880. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDER);
  42881. var border = this.border;
  42882. if (border instanceof BABYLON.SolidColorBrush2D) {
  42883. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID);
  42884. }
  42885. if (border instanceof BABYLON.GradientColorBrush2D) {
  42886. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT);
  42887. }
  42888. }
  42889. return cat;
  42890. };
  42891. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  42892. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  42893. return false;
  42894. }
  42895. // Fill Part
  42896. if (part.id === Shape2D.SHAPE2D_FILLPARTID) {
  42897. var d = part;
  42898. if (this.fill) {
  42899. var fill = this.fill;
  42900. if (fill instanceof BABYLON.SolidColorBrush2D) {
  42901. d.fillSolidColor = fill.color;
  42902. }
  42903. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  42904. d.fillGradientColor1 = fill.color1;
  42905. d.fillGradientColor2 = fill.color2;
  42906. 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));
  42907. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  42908. d.fillGradientTY = ty;
  42909. }
  42910. }
  42911. }
  42912. else if (part.id === Shape2D.SHAPE2D_BORDERPARTID) {
  42913. var d = part;
  42914. if (this.border) {
  42915. d.borderThickness = this.borderThickness;
  42916. var border = this.border;
  42917. if (border instanceof BABYLON.SolidColorBrush2D) {
  42918. d.borderSolidColor = border.color;
  42919. }
  42920. else if (border instanceof BABYLON.GradientColorBrush2D) {
  42921. d.borderGradientColor1 = border.color1;
  42922. d.borderGradientColor2 = border.color2;
  42923. 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));
  42924. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  42925. d.borderGradientTY = ty;
  42926. }
  42927. }
  42928. }
  42929. return true;
  42930. };
  42931. Shape2D.prototype._updateTransparencyStatus = function () {
  42932. this.isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent()) || (this.actualOpacity < 1);
  42933. };
  42934. Shape2D.SHAPE2D_BORDERPARTID = 1;
  42935. Shape2D.SHAPE2D_FILLPARTID = 2;
  42936. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  42937. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  42938. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  42939. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  42940. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  42941. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  42942. __decorate([
  42943. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D.borderProperty = pi; }, true)
  42944. ], Shape2D.prototype, "border", null);
  42945. __decorate([
  42946. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D.fillProperty = pi; }, true)
  42947. ], Shape2D.prototype, "fill", null);
  42948. __decorate([
  42949. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D.borderThicknessProperty = pi; })
  42950. ], Shape2D.prototype, "borderThickness", null);
  42951. Shape2D = __decorate([
  42952. BABYLON.className("Shape2D")
  42953. ], Shape2D);
  42954. return Shape2D;
  42955. })(BABYLON.RenderablePrim2D);
  42956. BABYLON.Shape2D = Shape2D;
  42957. var Shape2DInstanceData = (function (_super) {
  42958. __extends(Shape2DInstanceData, _super);
  42959. function Shape2DInstanceData() {
  42960. _super.apply(this, arguments);
  42961. }
  42962. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  42963. // FILL ATTRIBUTES
  42964. get: function () {
  42965. return null;
  42966. },
  42967. enumerable: true,
  42968. configurable: true
  42969. });
  42970. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  42971. get: function () {
  42972. return null;
  42973. },
  42974. enumerable: true,
  42975. configurable: true
  42976. });
  42977. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  42978. get: function () {
  42979. return null;
  42980. },
  42981. enumerable: true,
  42982. configurable: true
  42983. });
  42984. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  42985. get: function () {
  42986. return null;
  42987. },
  42988. enumerable: true,
  42989. configurable: true
  42990. });
  42991. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  42992. // BORDER ATTRIBUTES
  42993. get: function () {
  42994. return null;
  42995. },
  42996. enumerable: true,
  42997. configurable: true
  42998. });
  42999. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  43000. get: function () {
  43001. return null;
  43002. },
  43003. enumerable: true,
  43004. configurable: true
  43005. });
  43006. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  43007. get: function () {
  43008. return null;
  43009. },
  43010. enumerable: true,
  43011. configurable: true
  43012. });
  43013. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  43014. get: function () {
  43015. return null;
  43016. },
  43017. enumerable: true,
  43018. configurable: true
  43019. });
  43020. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  43021. get: function () {
  43022. return null;
  43023. },
  43024. enumerable: true,
  43025. configurable: true
  43026. });
  43027. __decorate([
  43028. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  43029. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  43030. __decorate([
  43031. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  43032. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  43033. __decorate([
  43034. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  43035. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  43036. __decorate([
  43037. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  43038. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  43039. __decorate([
  43040. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  43041. ], Shape2DInstanceData.prototype, "borderThickness", null);
  43042. __decorate([
  43043. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  43044. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  43045. __decorate([
  43046. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  43047. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  43048. __decorate([
  43049. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  43050. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  43051. __decorate([
  43052. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  43053. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  43054. return Shape2DInstanceData;
  43055. })(BABYLON.InstanceDataBase);
  43056. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  43057. })(BABYLON || (BABYLON = {}));
  43058. var BABYLON;
  43059. (function (BABYLON) {
  43060. var Group2D = (function (_super) {
  43061. __extends(Group2D, _super);
  43062. /**
  43063. * Create an Logical or Renderable Group.
  43064. * @param settings a combination of settings, possible ones are
  43065. * - 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)
  43066. * - children: an array of direct children
  43067. * - id a text identifier, for information purpose
  43068. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  43069. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  43070. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  43071. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  43072. * - origin: define the normalized origin point location, default [0.5;0.5]
  43073. * - 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.
  43074. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  43075. * - 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).
  43076. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  43077. * - 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!
  43078. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43079. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43080. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43081. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43082. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  43083. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  43084. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  43085. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  43086. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43087. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43088. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43089. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43090. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  43091. */
  43092. function Group2D(settings) {
  43093. if (settings == null) {
  43094. settings = {};
  43095. }
  43096. if (settings.origin == null) {
  43097. settings.origin = new BABYLON.Vector2(0, 0);
  43098. }
  43099. _super.call(this, settings);
  43100. var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));
  43101. this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;
  43102. if (this._trackedNode && this.owner) {
  43103. this.owner._registerTrackedNode(this);
  43104. }
  43105. this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;
  43106. this.size = size;
  43107. this._viewportPosition = BABYLON.Vector2.Zero();
  43108. }
  43109. Group2D._createCachedCanvasGroup = function (owner) {
  43110. var g = new Group2D({ parent: owner, id: "__cachedCanvasGroup__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), size: null, isVisible: true });
  43111. return g;
  43112. };
  43113. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  43114. this._bindCacheTarget();
  43115. if (vertexData) {
  43116. var uv = vertexData.uvs;
  43117. var nodeuv = this._renderableData._cacheNodeUVs;
  43118. for (var i = 0; i < 4; i++) {
  43119. uv[i * 2 + 0] = nodeuv[i].x;
  43120. uv[i * 2 + 1] = nodeuv[i].y;
  43121. }
  43122. }
  43123. if (material) {
  43124. material.diffuseTexture = this._renderableData._cacheTexture;
  43125. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  43126. }
  43127. this._renderableData._cacheTexture.hasAlpha = true;
  43128. this._unbindCacheTarget();
  43129. };
  43130. Object.defineProperty(Group2D.prototype, "cachedRect", {
  43131. /**
  43132. * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
  43133. * 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.
  43134. */
  43135. get: function () {
  43136. if (!this._renderableData) {
  43137. return null;
  43138. }
  43139. return this._renderableData._cacheNode;
  43140. },
  43141. enumerable: true,
  43142. configurable: true
  43143. });
  43144. Object.defineProperty(Group2D.prototype, "cachedUVs", {
  43145. /**
  43146. * The UVs into the MapTexture that map the cached group
  43147. */
  43148. get: function () {
  43149. if (!this._renderableData) {
  43150. return null;
  43151. }
  43152. return this._renderableData._cacheNodeUVs;
  43153. },
  43154. enumerable: true,
  43155. configurable: true
  43156. });
  43157. Object.defineProperty(Group2D.prototype, "cachedUVsChanged", {
  43158. get: function () {
  43159. if (!this._renderableData) {
  43160. return null;
  43161. }
  43162. if (!this._renderableData._cacheNodeUVsChangedObservable) {
  43163. this._renderableData._cacheNodeUVsChangedObservable = new BABYLON.Observable();
  43164. }
  43165. return this._renderableData._cacheNodeUVsChangedObservable;
  43166. },
  43167. enumerable: true,
  43168. configurable: true
  43169. });
  43170. Object.defineProperty(Group2D.prototype, "cacheTexture", {
  43171. /**
  43172. * Access the texture that maintains a cached version of the Group2D.
  43173. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
  43174. */
  43175. get: function () {
  43176. if (!this._renderableData) {
  43177. return null;
  43178. }
  43179. return this._renderableData._cacheTexture;
  43180. },
  43181. enumerable: true,
  43182. configurable: true
  43183. });
  43184. /**
  43185. * Call this method to remove this Group and its children from the Canvas
  43186. */
  43187. Group2D.prototype.dispose = function () {
  43188. if (!_super.prototype.dispose.call(this)) {
  43189. return false;
  43190. }
  43191. if (this._trackedNode != null) {
  43192. this.owner._unregisterTrackedNode(this);
  43193. this._trackedNode = null;
  43194. }
  43195. if (this._renderableData) {
  43196. this._renderableData.dispose(this.owner.engine);
  43197. this._renderableData = null;
  43198. }
  43199. return true;
  43200. };
  43201. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  43202. /**
  43203. * @returns Returns true if the Group render content, false if it's a logical group only
  43204. */
  43205. get: function () {
  43206. return this._isRenderableGroup;
  43207. },
  43208. enumerable: true,
  43209. configurable: true
  43210. });
  43211. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  43212. /**
  43213. * @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
  43214. */
  43215. get: function () {
  43216. return this._isCachedGroup;
  43217. },
  43218. enumerable: true,
  43219. configurable: true
  43220. });
  43221. Object.defineProperty(Group2D.prototype, "size", {
  43222. get: function () {
  43223. return this._size;
  43224. },
  43225. /**
  43226. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  43227. * 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.
  43228. */
  43229. set: function (val) {
  43230. this._size = val;
  43231. },
  43232. enumerable: true,
  43233. configurable: true
  43234. });
  43235. Object.defineProperty(Group2D.prototype, "viewportSize", {
  43236. get: function () {
  43237. return this._viewportSize;
  43238. },
  43239. enumerable: true,
  43240. configurable: true
  43241. });
  43242. Object.defineProperty(Group2D.prototype, "actualSize", {
  43243. get: function () {
  43244. // The computed size will be floor on both width and height
  43245. var actualSize;
  43246. // Return the size if set by the user
  43247. if (this._size) {
  43248. actualSize = new BABYLON.Size(Math.ceil(this._size.width), Math.ceil(this._size.height));
  43249. }
  43250. else {
  43251. var m = this.boundingInfo.max();
  43252. actualSize = new BABYLON.Size(Math.ceil(m.x), Math.ceil(m.y));
  43253. }
  43254. // 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)
  43255. if (!actualSize.equals(this._actualSize)) {
  43256. this.onPrimitivePropertyDirty(Group2D.actualSizeProperty.flagId);
  43257. this._actualSize = actualSize;
  43258. this.handleGroupChanged(Group2D.actualSizeProperty);
  43259. }
  43260. return actualSize;
  43261. },
  43262. enumerable: true,
  43263. configurable: true
  43264. });
  43265. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  43266. /**
  43267. * 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.
  43268. * 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.
  43269. */
  43270. get: function () {
  43271. return this._cacheBehavior;
  43272. },
  43273. enumerable: true,
  43274. configurable: true
  43275. });
  43276. Group2D.prototype._addPrimToDirtyList = function (prim) {
  43277. this._renderableData._primDirtyList.push(prim);
  43278. };
  43279. Group2D.prototype._renderCachedCanvas = function () {
  43280. this.owner._addGroupRenderCount(1);
  43281. this.updateCachedStates(true);
  43282. var context = new BABYLON.PrepareRender2DContext();
  43283. this._prepareGroupRender(context);
  43284. this._groupRender();
  43285. };
  43286. Object.defineProperty(Group2D.prototype, "trackedNode", {
  43287. /**
  43288. * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node.
  43289. */
  43290. get: function () {
  43291. return this._trackedNode;
  43292. },
  43293. set: function (val) {
  43294. if (val != null) {
  43295. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  43296. this.owner._registerTrackedNode(this);
  43297. }
  43298. this._trackedNode = val;
  43299. }
  43300. else {
  43301. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  43302. this.owner._unregisterTrackedNode(this);
  43303. }
  43304. this._trackedNode = null;
  43305. }
  43306. },
  43307. enumerable: true,
  43308. configurable: true
  43309. });
  43310. Group2D.prototype.levelIntersect = function (intersectInfo) {
  43311. // 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
  43312. return true;
  43313. };
  43314. Group2D.prototype.updateLevelBoundingInfo = function () {
  43315. var size;
  43316. // If the size is set by the user, the boundingInfo is computed from this value
  43317. if (this.size) {
  43318. size = this.size;
  43319. }
  43320. else {
  43321. size = new BABYLON.Size(0, 0);
  43322. }
  43323. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  43324. };
  43325. // Method called only on renderable groups to prepare the rendering
  43326. Group2D.prototype._prepareGroupRender = function (context) {
  43327. var sortedDirtyList = null;
  43328. // Update the Global Transformation and visibility status of the changed primitives
  43329. if ((this._renderableData._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  43330. sortedDirtyList = this._renderableData._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  43331. this.updateCachedStatesOf(sortedDirtyList, true);
  43332. }
  43333. // Setup the size of the rendering viewport
  43334. // 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
  43335. if (!this._isCachedGroup) {
  43336. // Compute the WebGL viewport's location/size
  43337. var t = this._globalTransform.getTranslation();
  43338. var s = this.actualSize.clone();
  43339. var rs = this.owner._renderingSize;
  43340. s.height = Math.min(s.height, rs.height - t.y);
  43341. s.width = Math.min(s.width, rs.width - t.x);
  43342. var x = t.x;
  43343. var y = t.y;
  43344. // 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
  43345. this._viewportPosition.x = x;
  43346. this._viewportPosition.y = y;
  43347. var vw = s.width;
  43348. var vh = s.height;
  43349. if (!this._viewportSize) {
  43350. this._viewportSize = new BABYLON.Size(vw, vh);
  43351. }
  43352. else {
  43353. if (this._viewportSize.width !== vw || this._viewportSize.height !== vh) {
  43354. context.forceRefreshPrimitive = true;
  43355. }
  43356. this._viewportSize.width = vw;
  43357. this._viewportSize.height = vh;
  43358. }
  43359. }
  43360. else {
  43361. var newSize = this.actualSize.clone();
  43362. if (!newSize.equals(this._viewportSize)) {
  43363. context.forceRefreshPrimitive = true;
  43364. }
  43365. this._viewportSize = newSize;
  43366. }
  43367. if ((this._renderableData._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  43368. // If the group is cached, set the dirty flag to true because of the incoming changes
  43369. this._cacheGroupDirty = this._isCachedGroup;
  43370. // If it's a force refresh, prepare all the children
  43371. if (context.forceRefreshPrimitive) {
  43372. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  43373. var p = _a[_i];
  43374. p._prepareRender(context);
  43375. }
  43376. }
  43377. else {
  43378. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  43379. // the hierarchyDepth in order to prepare primitives from top to bottom
  43380. if (!sortedDirtyList) {
  43381. sortedDirtyList = this._renderableData._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  43382. }
  43383. sortedDirtyList.forEach(function (p) {
  43384. // 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.
  43385. // 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.
  43386. if (!p.isDisposed && p._needPrepare()) {
  43387. p._prepareRender(context);
  43388. }
  43389. });
  43390. }
  43391. // Everything is updated, clear the dirty list
  43392. this._renderableData._primDirtyList.forEach(function (p) { return p._resetPropertiesDirty(); });
  43393. this._renderableData._primDirtyList.splice(0);
  43394. }
  43395. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  43396. this._renderableData._childrenRenderableGroups.forEach(function (g) {
  43397. g._prepareGroupRender(context);
  43398. });
  43399. };
  43400. Group2D.prototype._groupRender = function () {
  43401. var _this = this;
  43402. var engine = this.owner.engine;
  43403. var failedCount = 0;
  43404. // First recurse to children render group to render them (in their cache or on screen)
  43405. for (var _i = 0, _a = this._renderableData._childrenRenderableGroups; _i < _a.length; _i++) {
  43406. var childGroup = _a[_i];
  43407. childGroup._groupRender();
  43408. }
  43409. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  43410. if (!this.isCachedGroup || this._cacheGroupDirty) {
  43411. this.owner._addGroupRenderCount(1);
  43412. if (this.isCachedGroup) {
  43413. this._bindCacheTarget();
  43414. }
  43415. else {
  43416. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  43417. }
  43418. var curAlphaTest = engine.getAlphaTesting() === true;
  43419. var curDepthWrite = engine.getDepthWrite() === true;
  43420. // ===================================================================
  43421. // First pass, update the InstancedArray and render Opaque primitives
  43422. // Disable Alpha Testing, Enable Depth Write
  43423. engine.setAlphaTesting(false);
  43424. engine.setDepthWrite(true);
  43425. // For each different model of primitive to render
  43426. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeOpaque);
  43427. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  43428. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  43429. var renderCount = _this._prepareContext(engine, context, v);
  43430. // If null is returned, there's no opaque data to render
  43431. if (renderCount === null) {
  43432. return;
  43433. }
  43434. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  43435. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  43436. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  43437. var renderFailed = !v.modelRenderCache.render(v, context);
  43438. // Update dirty flag/related
  43439. v.opaqueDirty = renderFailed;
  43440. failedCount += renderFailed ? 1 : 0;
  43441. }
  43442. });
  43443. // =======================================================================
  43444. // Second pass, update the InstancedArray and render AlphaTest primitives
  43445. // Enable Alpha Testing, Enable Depth Write
  43446. engine.setAlphaTesting(true);
  43447. engine.setDepthWrite(true);
  43448. // For each different model of primitive to render
  43449. context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeAlphaTest);
  43450. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  43451. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  43452. var renderCount = _this._prepareContext(engine, context, v);
  43453. // If null is returned, there's no opaque data to render
  43454. if (renderCount === null) {
  43455. return;
  43456. }
  43457. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  43458. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  43459. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  43460. var renderFailed = !v.modelRenderCache.render(v, context);
  43461. // Update dirty flag/related
  43462. v.opaqueDirty = renderFailed;
  43463. failedCount += renderFailed ? 1 : 0;
  43464. }
  43465. });
  43466. // =======================================================================
  43467. // Third pass, transparent primitive rendering
  43468. // Enable Alpha Testing, Disable Depth Write
  43469. engine.setAlphaTesting(true);
  43470. engine.setDepthWrite(false);
  43471. // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
  43472. if (this._renderableData._transparentListChanged) {
  43473. this._updateTransparentData();
  43474. }
  43475. // From this point on we have up to date data to render, so let's go
  43476. failedCount += this._renderTransparentData();
  43477. // =======================================================================
  43478. // Unbind target/restore viewport setting, clear dirty flag, and quit
  43479. // The group's content is no longer dirty
  43480. this._cacheGroupDirty = failedCount !== 0;
  43481. if (this.isCachedGroup) {
  43482. this._unbindCacheTarget();
  43483. }
  43484. else {
  43485. if (curVP) {
  43486. engine.setViewport(curVP);
  43487. }
  43488. }
  43489. // Restore saved states
  43490. engine.setAlphaTesting(curAlphaTest);
  43491. engine.setDepthWrite(curDepthWrite);
  43492. }
  43493. };
  43494. Group2D.prototype._setCacheGroupDirty = function () {
  43495. this._cacheGroupDirty = true;
  43496. };
  43497. Group2D.prototype._updateTransparentData = function () {
  43498. this.owner._addUpdateTransparentDataCount(1);
  43499. var rd = this._renderableData;
  43500. // Sort all the primitive from their depth, max (bottom) to min (top)
  43501. rd._transparentPrimitives.sort(function (a, b) { return b._primitive.actualZOffset - a._primitive.actualZOffset; });
  43502. var checkAndAddPrimInSegment = function (seg, tpiI) {
  43503. var tpi = rd._transparentPrimitives[tpiI];
  43504. // Fast rejection: if gii are different
  43505. if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
  43506. return false;
  43507. }
  43508. //let tpiZ = tpi._primitive.actualZOffset;
  43509. // We've made it so far, the tpi can be part of the segment, add it
  43510. tpi._transparentSegment = seg;
  43511. seg.endDataIndex = tpi._primitive._getPrimitiveLastIndex();
  43512. return true;
  43513. };
  43514. // Free the existing TransparentSegments
  43515. for (var _i = 0, _a = rd._transparentSegments; _i < _a.length; _i++) {
  43516. var ts = _a[_i];
  43517. ts.dispose(this.owner.engine);
  43518. }
  43519. rd._transparentSegments.splice(0);
  43520. var prevSeg = null;
  43521. for (var tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
  43522. var tpi = rd._transparentPrimitives[tpiI];
  43523. // Check if the Data in which the primitive is stored is not sorted properly
  43524. if (tpi._groupInstanceInfo.transparentOrderDirty) {
  43525. tpi._groupInstanceInfo.sortTransparentData();
  43526. }
  43527. // Reset the segment, we have to create/rebuild it
  43528. tpi._transparentSegment = null;
  43529. // If there's a previous valid segment, check if this prim can be part of it
  43530. if (prevSeg) {
  43531. checkAndAddPrimInSegment(prevSeg, tpiI);
  43532. }
  43533. // If we couldn't insert in the adjacent segments, he have to create one
  43534. if (!tpi._transparentSegment) {
  43535. var ts = new BABYLON.TransparentSegment();
  43536. ts.groupInsanceInfo = tpi._groupInstanceInfo;
  43537. var prim = tpi._primitive;
  43538. ts.startZ = prim.actualZOffset;
  43539. prim._updateTransparentSegmentIndices(ts);
  43540. ts.endZ = ts.startZ;
  43541. tpi._transparentSegment = ts;
  43542. rd._transparentSegments.push(ts);
  43543. }
  43544. // Update prevSeg
  43545. prevSeg = tpi._transparentSegment;
  43546. }
  43547. //rd._firstChangedPrim = null;
  43548. rd._transparentListChanged = false;
  43549. };
  43550. Group2D.prototype._renderTransparentData = function () {
  43551. var failedCount = 0;
  43552. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeTransparent);
  43553. var rd = this._renderableData;
  43554. var useInstanced = this.owner.supportInstancedArray;
  43555. var length = rd._transparentSegments.length;
  43556. for (var i = 0; i < length; i++) {
  43557. context.instancedBuffers = null;
  43558. var ts = rd._transparentSegments[i];
  43559. var gii = ts.groupInsanceInfo;
  43560. var mrc = gii.modelRenderCache;
  43561. var engine = this.owner.engine;
  43562. var count = ts.endDataIndex - ts.startDataIndex;
  43563. // Use Instanced Array if it's supported and if there's at least 5 prims to draw.
  43564. // We don't want to create an Instanced Buffer for less that 5 prims
  43565. if (useInstanced && count >= 5) {
  43566. if (!ts.partBuffers) {
  43567. var buffers = new Array();
  43568. for (var j = 0; j < gii.transparentData.length; j++) {
  43569. var gitd = gii.transparentData[j];
  43570. var dfa = gitd._partData;
  43571. var data = dfa.pack();
  43572. var stride = dfa.stride;
  43573. var neededSize = count * stride * 4;
  43574. var buffer = engine.createInstancesBuffer(neededSize); // Create + bind
  43575. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  43576. engine.updateArrayBuffer(segData);
  43577. buffers.push(buffer);
  43578. }
  43579. ts.partBuffers = buffers;
  43580. }
  43581. else if (gii.transparentDirty) {
  43582. for (var j = 0; j < gii.transparentData.length; j++) {
  43583. var gitd = gii.transparentData[j];
  43584. var dfa = gitd._partData;
  43585. var data = dfa.pack();
  43586. var stride = dfa.stride;
  43587. var buffer = ts.partBuffers[j];
  43588. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  43589. engine.bindArrayBuffer(buffer);
  43590. engine.updateArrayBuffer(segData);
  43591. }
  43592. }
  43593. context.useInstancing = true;
  43594. context.instancesCount = count;
  43595. context.instancedBuffers = ts.partBuffers;
  43596. context.groupInfoPartData = gii.transparentData;
  43597. var renderFailed = !mrc.render(gii, context);
  43598. failedCount += renderFailed ? 1 : 0;
  43599. }
  43600. else {
  43601. context.useInstancing = false;
  43602. context.partDataStartIndex = ts.startDataIndex;
  43603. context.partDataEndIndex = ts.endDataIndex;
  43604. context.groupInfoPartData = gii.transparentData;
  43605. var renderFailed = !mrc.render(gii, context);
  43606. failedCount += renderFailed ? 1 : 0;
  43607. }
  43608. }
  43609. return failedCount;
  43610. };
  43611. Group2D.prototype._prepareContext = function (engine, context, gii) {
  43612. var gipd = null;
  43613. var setDirty;
  43614. var getDirty;
  43615. // Render Mode specifics
  43616. switch (context.renderMode) {
  43617. case BABYLON.Render2DContext.RenderModeOpaque:
  43618. {
  43619. if (!gii.hasOpaqueData) {
  43620. return null;
  43621. }
  43622. setDirty = function (dirty) { gii.opaqueDirty = dirty; };
  43623. getDirty = function () { return gii.opaqueDirty; };
  43624. context.groupInfoPartData = gii.opaqueData;
  43625. gipd = gii.opaqueData;
  43626. break;
  43627. }
  43628. case BABYLON.Render2DContext.RenderModeAlphaTest:
  43629. {
  43630. if (!gii.hasAlphaTestData) {
  43631. return null;
  43632. }
  43633. setDirty = function (dirty) { gii.alphaTestDirty = dirty; };
  43634. getDirty = function () { return gii.alphaTestDirty; };
  43635. context.groupInfoPartData = gii.alphaTestData;
  43636. gipd = gii.alphaTestData;
  43637. break;
  43638. }
  43639. default:
  43640. throw new Error("_prepareContext is only for opaque or alphaTest");
  43641. }
  43642. var renderCount = 0;
  43643. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  43644. // Skip it if instanced arrays are not supported
  43645. if (this.owner.supportInstancedArray) {
  43646. // Flag for instancing
  43647. context.useInstancing = true;
  43648. // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
  43649. for (var i = 0; i < gipd.length; i++) {
  43650. var pid = gipd[i];
  43651. // If the instances of the model was changed, pack the data
  43652. var array = pid._partData;
  43653. var instanceData_1 = array.pack();
  43654. renderCount += array.usedElementCount;
  43655. // Compute the size the instance buffer should have
  43656. var neededSize = array.usedElementCount * array.stride * 4;
  43657. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  43658. if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
  43659. if (pid._partBuffer) {
  43660. engine.deleteInstancesBuffer(pid._partBuffer);
  43661. }
  43662. pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
  43663. pid._partBufferSize = neededSize;
  43664. setDirty(false);
  43665. // Update the WebGL buffer to match the new content of the instances data
  43666. engine.updateArrayBuffer(instanceData_1);
  43667. }
  43668. else if (getDirty()) {
  43669. // Update the WebGL buffer to match the new content of the instances data
  43670. engine.bindArrayBuffer(pid._partBuffer);
  43671. engine.updateArrayBuffer(instanceData_1);
  43672. }
  43673. }
  43674. setDirty(false);
  43675. }
  43676. else {
  43677. context.partDataStartIndex = 0;
  43678. // Find the first valid object to get the count
  43679. if (context.groupInfoPartData.length > 0) {
  43680. var i = 0;
  43681. while (!context.groupInfoPartData[i]) {
  43682. i++;
  43683. }
  43684. context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
  43685. }
  43686. }
  43687. return renderCount;
  43688. };
  43689. Group2D.prototype._setRenderingScale = function (scale) {
  43690. if (this._renderableData._renderingScale === scale) {
  43691. return;
  43692. }
  43693. this._renderableData._renderingScale = scale;
  43694. };
  43695. Group2D.prototype._bindCacheTarget = function () {
  43696. var curWidth;
  43697. var curHeight;
  43698. var rd = this._renderableData;
  43699. var rs = rd._renderingScale;
  43700. Group2D._s.width = Math.ceil(this.actualSize.width * rs);
  43701. Group2D._s.height = Math.ceil(this.actualSize.height * rs);
  43702. var sizeChanged = !Group2D._s.equals(rd._cacheSize);
  43703. if (rd._cacheNode) {
  43704. var size = rd._cacheNode.contentSize;
  43705. // Check if we have to deallocate because the size is too small
  43706. if ((size.width < Group2D._s.width) || (size.height < Group2D._s.height)) {
  43707. // For Screen space: over-provisioning of 7% more to avoid frequent resizing for few pixels...
  43708. // For World space: no over-provisioning
  43709. var overprovisioning = this.owner.isScreenSpace ? 1.07 : 1;
  43710. curWidth = Math.floor(Group2D._s.width * overprovisioning);
  43711. curHeight = Math.floor(Group2D._s.height * overprovisioning);
  43712. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  43713. rd._cacheTexture.freeRect(rd._cacheNode);
  43714. rd._cacheNode = null;
  43715. }
  43716. }
  43717. if (!rd._cacheNode) {
  43718. // Check if we have to allocate a rendering zone in the global cache texture
  43719. var res = this.owner._allocateGroupCache(this, this.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null, rd._useMipMap, rd._anisotropicLevel);
  43720. rd._cacheNode = res.node;
  43721. rd._cacheTexture = res.texture;
  43722. rd._cacheRenderSprite = res.sprite;
  43723. sizeChanged = true;
  43724. }
  43725. if (sizeChanged) {
  43726. rd._cacheSize.copyFrom(Group2D._s);
  43727. rd._cacheNodeUVs = rd._cacheNode.getUVsForCustomSize(rd._cacheSize);
  43728. this.scale = this._renderableData._renderingScale;
  43729. if (rd._cacheNodeUVsChangedObservable && rd._cacheNodeUVsChangedObservable.hasObservers()) {
  43730. rd._cacheNodeUVsChangedObservable.notifyObservers(rd._cacheNodeUVs);
  43731. }
  43732. this._setFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  43733. }
  43734. var n = rd._cacheNode;
  43735. rd._cacheTexture.bindTextureForPosSize(n.pos, Group2D._s, true);
  43736. };
  43737. Group2D.prototype._unbindCacheTarget = function () {
  43738. if (this._renderableData._cacheTexture) {
  43739. this._renderableData._cacheTexture.unbindTexture();
  43740. }
  43741. };
  43742. Group2D.prototype.handleGroupChanged = function (prop) {
  43743. // This method is only for cachedGroup
  43744. var rd = this._renderableData;
  43745. if (!this.isCachedGroup || !rd._cacheRenderSprite) {
  43746. return;
  43747. }
  43748. // For now we only support these property changes
  43749. // TODO: add more! :)
  43750. if (prop.id === BABYLON.Prim2DBase.actualPositionProperty.id) {
  43751. rd._cacheRenderSprite.actualPosition = this.actualPosition.clone();
  43752. }
  43753. else if (prop.id === BABYLON.Prim2DBase.rotationProperty.id) {
  43754. rd._cacheRenderSprite.rotation = this.rotation;
  43755. }
  43756. else if (prop.id === BABYLON.Prim2DBase.scaleProperty.id) {
  43757. rd._cacheRenderSprite.scale = this.scale;
  43758. }
  43759. else if (prop.id === BABYLON.Prim2DBase.originProperty.id) {
  43760. rd._cacheRenderSprite.origin = this.origin.clone();
  43761. }
  43762. else if (prop.id === Group2D.actualSizeProperty.id) {
  43763. rd._cacheRenderSprite.size = this.actualSize.clone();
  43764. }
  43765. };
  43766. Group2D.prototype.detectGroupStates = function () {
  43767. var isCanvas = this instanceof BABYLON.Canvas2D;
  43768. var canvasStrat = this.owner.cachingStrategy;
  43769. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  43770. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  43771. this._isRenderableGroup = isCanvas;
  43772. this._isCachedGroup = false;
  43773. }
  43774. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  43775. if (isCanvas) {
  43776. this._isRenderableGroup = true;
  43777. this._isCachedGroup = true;
  43778. }
  43779. else {
  43780. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  43781. this._isCachedGroup = false;
  43782. }
  43783. }
  43784. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  43785. if (isCanvas) {
  43786. this._isRenderableGroup = true;
  43787. this._isCachedGroup = false;
  43788. }
  43789. else {
  43790. if (this.hierarchyDepth === 1) {
  43791. this._isRenderableGroup = true;
  43792. this._isCachedGroup = true;
  43793. }
  43794. else {
  43795. this._isRenderableGroup = false;
  43796. this._isCachedGroup = false;
  43797. }
  43798. }
  43799. }
  43800. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  43801. var gcb = this.cacheBehavior;
  43802. if ((gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  43803. this._isRenderableGroup = gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  43804. this._isCachedGroup = false;
  43805. }
  43806. if (gcb === Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  43807. this._isRenderableGroup = true;
  43808. this._isCachedGroup = true;
  43809. }
  43810. }
  43811. if (this._isRenderableGroup) {
  43812. // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object...
  43813. if (!this._renderableData) {
  43814. this._renderableData = new RenderableGroupData();
  43815. }
  43816. }
  43817. // If the group is tagged as renderable we add it to the renderable tree
  43818. if (this._isCachedGroup) {
  43819. var cur = this.parent;
  43820. while (cur) {
  43821. if (cur instanceof Group2D && cur._isRenderableGroup) {
  43822. if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) {
  43823. cur._renderableData._childrenRenderableGroups.push(this);
  43824. }
  43825. break;
  43826. }
  43827. cur = cur.parent;
  43828. }
  43829. }
  43830. };
  43831. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  43832. /**
  43833. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  43834. */
  43835. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  43836. /**
  43837. * When used, this group's content won't be cached, no matter which strategy used.
  43838. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  43839. */
  43840. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  43841. /**
  43842. * When used, the group's content will be cached in the nearest cached parent group/canvas
  43843. */
  43844. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  43845. Group2D._s = BABYLON.Size.Zero();
  43846. __decorate([
  43847. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D.sizeProperty = pi; }, false, true)
  43848. ], Group2D.prototype, "size", null);
  43849. __decorate([
  43850. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 2, function (pi) { return Group2D.actualSizeProperty = pi; })
  43851. ], Group2D.prototype, "actualSize", null);
  43852. Group2D = __decorate([
  43853. BABYLON.className("Group2D")
  43854. ], Group2D);
  43855. return Group2D;
  43856. })(BABYLON.Prim2DBase);
  43857. BABYLON.Group2D = Group2D;
  43858. var RenderableGroupData = (function () {
  43859. function RenderableGroupData() {
  43860. this._primDirtyList = new Array();
  43861. this._childrenRenderableGroups = new Array();
  43862. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  43863. this._transparentPrimitives = new Array();
  43864. this._transparentSegments = new Array();
  43865. this._transparentListChanged = false;
  43866. this._cacheNode = null;
  43867. this._cacheTexture = null;
  43868. this._cacheRenderSprite = null;
  43869. this._renderingScale = 1;
  43870. this._cacheNodeUVs = null;
  43871. this._cacheNodeUVsChangedObservable = null;
  43872. this._cacheSize = BABYLON.Size.Zero();
  43873. this._useMipMap = false;
  43874. this._anisotropicLevel = 1;
  43875. }
  43876. RenderableGroupData.prototype.dispose = function (engine) {
  43877. if (this._cacheRenderSprite) {
  43878. this._cacheRenderSprite.dispose();
  43879. this._cacheRenderSprite = null;
  43880. }
  43881. if (this._cacheTexture && this._cacheNode) {
  43882. this._cacheTexture.freeRect(this._cacheNode);
  43883. this._cacheTexture = null;
  43884. this._cacheNode = null;
  43885. }
  43886. if (this._primDirtyList) {
  43887. this._primDirtyList.splice(0);
  43888. this._primDirtyList = null;
  43889. }
  43890. if (this._renderGroupInstancesInfo) {
  43891. this._renderGroupInstancesInfo.forEach(function (k, v) {
  43892. v.dispose();
  43893. });
  43894. this._renderGroupInstancesInfo = null;
  43895. }
  43896. if (this._cacheNodeUVsChangedObservable) {
  43897. this._cacheNodeUVsChangedObservable.clear();
  43898. this._cacheNodeUVsChangedObservable = null;
  43899. }
  43900. if (this._transparentSegments) {
  43901. for (var _i = 0, _a = this._transparentSegments; _i < _a.length; _i++) {
  43902. var ts = _a[_i];
  43903. ts.dispose(engine);
  43904. }
  43905. this._transparentSegments.splice(0);
  43906. this._transparentSegments = null;
  43907. }
  43908. };
  43909. RenderableGroupData.prototype.addNewTransparentPrimitiveInfo = function (prim, gii) {
  43910. var tpi = new TransparentPrimitiveInfo();
  43911. tpi._primitive = prim;
  43912. tpi._groupInstanceInfo = gii;
  43913. tpi._transparentSegment = null;
  43914. this._transparentPrimitives.push(tpi);
  43915. this._transparentListChanged = true;
  43916. return tpi;
  43917. };
  43918. RenderableGroupData.prototype.removeTransparentPrimitiveInfo = function (tpi) {
  43919. var index = this._transparentPrimitives.indexOf(tpi);
  43920. if (index !== -1) {
  43921. this._transparentPrimitives.splice(index, 1);
  43922. this._transparentListChanged = true;
  43923. }
  43924. };
  43925. RenderableGroupData.prototype.transparentPrimitiveZChanged = function (tpi) {
  43926. this._transparentListChanged = true;
  43927. //this.updateSmallestZChangedPrim(tpi);
  43928. };
  43929. return RenderableGroupData;
  43930. })();
  43931. BABYLON.RenderableGroupData = RenderableGroupData;
  43932. var TransparentPrimitiveInfo = (function () {
  43933. function TransparentPrimitiveInfo() {
  43934. }
  43935. return TransparentPrimitiveInfo;
  43936. })();
  43937. BABYLON.TransparentPrimitiveInfo = TransparentPrimitiveInfo;
  43938. })(BABYLON || (BABYLON = {}));
  43939. var BABYLON;
  43940. (function (BABYLON) {
  43941. var Rectangle2DRenderCache = (function (_super) {
  43942. __extends(Rectangle2DRenderCache, _super);
  43943. function Rectangle2DRenderCache(engine, modelKey) {
  43944. _super.call(this, engine, modelKey);
  43945. this.effectsReady = false;
  43946. this.fillVB = null;
  43947. this.fillIB = null;
  43948. this.fillIndicesCount = 0;
  43949. this.instancingFillAttributes = null;
  43950. this.effectFill = null;
  43951. this.effectFillInstanced = null;
  43952. this.borderVB = null;
  43953. this.borderIB = null;
  43954. this.borderIndicesCount = 0;
  43955. this.instancingBorderAttributes = null;
  43956. this.effectBorder = null;
  43957. this.effectBorderInstanced = null;
  43958. }
  43959. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  43960. // Do nothing if the shader is still loading/preparing
  43961. if (!this.effectsReady) {
  43962. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  43963. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  43964. return false;
  43965. }
  43966. this.effectsReady = true;
  43967. }
  43968. var canvas = instanceInfo.owner.owner;
  43969. var engine = canvas.engine;
  43970. var depthFunction = 0;
  43971. if (this.effectFill && this.effectBorder) {
  43972. depthFunction = engine.getDepthFunction();
  43973. engine.setDepthFunctionToLessOrEqual();
  43974. }
  43975. var curAlphaMode = engine.getAlphaMode();
  43976. if (this.effectFill) {
  43977. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  43978. var pid = context.groupInfoPartData[partIndex];
  43979. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  43980. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  43981. }
  43982. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  43983. engine.enableEffect(effect);
  43984. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  43985. if (context.useInstancing) {
  43986. if (!this.instancingFillAttributes) {
  43987. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  43988. }
  43989. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  43990. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  43991. canvas._addDrawCallCount(1, context.renderMode);
  43992. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  43993. engine.draw(true, 0, this.fillIndicesCount, count);
  43994. engine.unbindInstanceAttributes();
  43995. }
  43996. else {
  43997. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  43998. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  43999. this.setupUniforms(effect, partIndex, pid._partData, i);
  44000. engine.draw(true, 0, this.fillIndicesCount);
  44001. }
  44002. }
  44003. }
  44004. if (this.effectBorder) {
  44005. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  44006. var pid = context.groupInfoPartData[partIndex];
  44007. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44008. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  44009. }
  44010. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  44011. engine.enableEffect(effect);
  44012. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  44013. if (context.useInstancing) {
  44014. if (!this.instancingBorderAttributes) {
  44015. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  44016. }
  44017. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44018. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44019. canvas._addDrawCallCount(1, context.renderMode);
  44020. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  44021. engine.draw(true, 0, this.borderIndicesCount, count);
  44022. engine.unbindInstanceAttributes();
  44023. }
  44024. else {
  44025. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44026. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44027. this.setupUniforms(effect, partIndex, pid._partData, i);
  44028. engine.draw(true, 0, this.borderIndicesCount);
  44029. }
  44030. }
  44031. }
  44032. engine.setAlphaMode(curAlphaMode, true);
  44033. if (this.effectFill && this.effectBorder) {
  44034. engine.setDepthFunction(depthFunction);
  44035. }
  44036. return true;
  44037. };
  44038. Rectangle2DRenderCache.prototype.dispose = function () {
  44039. if (!_super.prototype.dispose.call(this)) {
  44040. return false;
  44041. }
  44042. if (this.fillVB) {
  44043. this._engine._releaseBuffer(this.fillVB);
  44044. this.fillVB = null;
  44045. }
  44046. if (this.fillIB) {
  44047. this._engine._releaseBuffer(this.fillIB);
  44048. this.fillIB = null;
  44049. }
  44050. this.effectFill = null;
  44051. this.effectFillInstanced = null;
  44052. this.effectBorder = null;
  44053. this.effectBorderInstanced = null;
  44054. if (this.borderVB) {
  44055. this._engine._releaseBuffer(this.borderVB);
  44056. this.borderVB = null;
  44057. }
  44058. if (this.borderIB) {
  44059. this._engine._releaseBuffer(this.borderIB);
  44060. this.borderIB = null;
  44061. }
  44062. return true;
  44063. };
  44064. return Rectangle2DRenderCache;
  44065. })(BABYLON.ModelRenderCache);
  44066. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  44067. var Rectangle2DInstanceData = (function (_super) {
  44068. __extends(Rectangle2DInstanceData, _super);
  44069. function Rectangle2DInstanceData(partId) {
  44070. _super.call(this, partId, 1);
  44071. }
  44072. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  44073. get: function () {
  44074. return null;
  44075. },
  44076. enumerable: true,
  44077. configurable: true
  44078. });
  44079. __decorate([
  44080. BABYLON.instanceData()
  44081. ], Rectangle2DInstanceData.prototype, "properties", null);
  44082. return Rectangle2DInstanceData;
  44083. })(BABYLON.Shape2DInstanceData);
  44084. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  44085. var Rectangle2D = (function (_super) {
  44086. __extends(Rectangle2D, _super);
  44087. /**
  44088. * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
  44089. * @param settings a combination of settings, possible ones are
  44090. * - 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)
  44091. * - children: an array of direct children
  44092. * - id a text identifier, for information purpose
  44093. * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0]
  44094. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  44095. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  44096. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  44097. * - origin: define the normalized origin point location, default [0.5;0.5]
  44098. * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10].
  44099. * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle).
  44100. * - 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)
  44101. * - 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)
  44102. * - borderThickness: the thickness of the drawn border, default is 1.
  44103. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  44104. * - 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!
  44105. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44106. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44107. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44108. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44109. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  44110. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  44111. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  44112. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  44113. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44114. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44115. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44116. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44117. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  44118. */
  44119. function Rectangle2D(settings) {
  44120. // Avoid checking every time if the object exists
  44121. if (settings == null) {
  44122. settings = {};
  44123. }
  44124. _super.call(this, settings);
  44125. if (settings.size != null) {
  44126. this.size = settings.size;
  44127. }
  44128. else if (settings.width || settings.height) {
  44129. var size = new BABYLON.Size(settings.width, settings.height);
  44130. this.size = size;
  44131. }
  44132. //let size = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
  44133. var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
  44134. var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
  44135. //this.size = size;
  44136. this.roundRadius = roundRadius;
  44137. this.borderThickness = borderThickness;
  44138. }
  44139. Object.defineProperty(Rectangle2D.prototype, "actualSize", {
  44140. get: function () {
  44141. if (this._actualSize) {
  44142. return this._actualSize;
  44143. }
  44144. return this.size;
  44145. },
  44146. set: function (value) {
  44147. this._actualSize = value;
  44148. },
  44149. enumerable: true,
  44150. configurable: true
  44151. });
  44152. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  44153. get: function () {
  44154. return this._notRounded;
  44155. },
  44156. set: function (value) {
  44157. this._notRounded = value;
  44158. },
  44159. enumerable: true,
  44160. configurable: true
  44161. });
  44162. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  44163. get: function () {
  44164. return this._roundRadius;
  44165. },
  44166. set: function (value) {
  44167. this._roundRadius = value;
  44168. this.notRounded = value === 0;
  44169. this._positioningDirty();
  44170. },
  44171. enumerable: true,
  44172. configurable: true
  44173. });
  44174. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  44175. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  44176. if (this.notRounded) {
  44177. return true;
  44178. }
  44179. // 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.
  44180. // 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)
  44181. // 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.
  44182. // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
  44183. var size = this.size;
  44184. Rectangle2D._i0.x = intersectInfo._localPickPosition.x;
  44185. Rectangle2D._i0.y = intersectInfo._localPickPosition.y;
  44186. var rr = this.roundRadius;
  44187. var rrs = rr * rr;
  44188. // Check if the point is in the bottom/left quarter area
  44189. Rectangle2D._i1.x = rr;
  44190. Rectangle2D._i1.y = rr;
  44191. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  44192. // Compute the intersection point in the quarter local space
  44193. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  44194. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  44195. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  44196. return Rectangle2D._i2.lengthSquared() <= rrs;
  44197. }
  44198. // Check if the point is in the top/left quarter area
  44199. Rectangle2D._i1.x = rr;
  44200. Rectangle2D._i1.y = size.height - rr;
  44201. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  44202. // Compute the intersection point in the quarter local space
  44203. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  44204. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  44205. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  44206. return Rectangle2D._i2.lengthSquared() <= rrs;
  44207. }
  44208. // Check if the point is in the top/right quarter area
  44209. Rectangle2D._i1.x = size.width - rr;
  44210. Rectangle2D._i1.y = size.height - rr;
  44211. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  44212. // Compute the intersection point in the quarter local space
  44213. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  44214. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  44215. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  44216. return Rectangle2D._i2.lengthSquared() <= rrs;
  44217. }
  44218. // Check if the point is in the bottom/right quarter area
  44219. Rectangle2D._i1.x = size.width - rr;
  44220. Rectangle2D._i1.y = rr;
  44221. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  44222. // Compute the intersection point in the quarter local space
  44223. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  44224. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  44225. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  44226. return Rectangle2D._i2.lengthSquared() <= rrs;
  44227. }
  44228. // At any other locations the point is guarantied to be inside
  44229. return true;
  44230. };
  44231. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  44232. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  44233. };
  44234. Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
  44235. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
  44236. return renderCache;
  44237. };
  44238. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  44239. var renderCache = modelRenderCache;
  44240. var engine = this.owner.engine;
  44241. // Need to create WebGL resources for fill part?
  44242. if (this.fill) {
  44243. var vbSize = ((this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4) + 1;
  44244. var vb = new Float32Array(vbSize);
  44245. for (var i = 0; i < vbSize; i++) {
  44246. vb[i] = i;
  44247. }
  44248. renderCache.fillVB = engine.createVertexBuffer(vb);
  44249. var triCount = vbSize - 1;
  44250. var ib = new Float32Array(triCount * 3);
  44251. for (var i = 0; i < triCount; i++) {
  44252. ib[i * 3 + 0] = 0;
  44253. ib[i * 3 + 2] = i + 1;
  44254. ib[i * 3 + 1] = i + 2;
  44255. }
  44256. ib[triCount * 3 - 2] = 1;
  44257. renderCache.fillIB = engine.createIndexBuffer(ib);
  44258. renderCache.fillIndicesCount = triCount * 3;
  44259. // 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
  44260. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], true);
  44261. if (ei) {
  44262. renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44263. }
  44264. // Get the non instanced version
  44265. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], false);
  44266. renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44267. }
  44268. // Need to create WebGL resource for border part?
  44269. if (this.border) {
  44270. var vbSize = (this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4 * 2;
  44271. var vb = new Float32Array(vbSize);
  44272. for (var i = 0; i < vbSize; i++) {
  44273. vb[i] = i;
  44274. }
  44275. renderCache.borderVB = engine.createVertexBuffer(vb);
  44276. var triCount = vbSize;
  44277. var rs = triCount / 2;
  44278. var ib = new Float32Array(triCount * 3);
  44279. for (var i = 0; i < rs; i++) {
  44280. var r0 = i;
  44281. var r1 = (i + 1) % rs;
  44282. ib[i * 6 + 0] = rs + r1;
  44283. ib[i * 6 + 1] = rs + r0;
  44284. ib[i * 6 + 2] = r0;
  44285. ib[i * 6 + 3] = r1;
  44286. ib[i * 6 + 4] = rs + r1;
  44287. ib[i * 6 + 5] = r0;
  44288. }
  44289. renderCache.borderIB = engine.createIndexBuffer(ib);
  44290. renderCache.borderIndicesCount = triCount * 3;
  44291. // 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
  44292. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], true);
  44293. if (ei) {
  44294. renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44295. }
  44296. // Get the non instanced version
  44297. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], false);
  44298. renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44299. }
  44300. return renderCache;
  44301. };
  44302. // 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
  44303. Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  44304. // Fall back to default implementation if there's no round Radius
  44305. if (this._notRounded) {
  44306. _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
  44307. }
  44308. else {
  44309. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  44310. initialContentPosition.x = initialContentPosition.y = rr;
  44311. initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
  44312. initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
  44313. }
  44314. };
  44315. Rectangle2D.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  44316. // Fall back to default implementation if there's no round Radius
  44317. if (this._notRounded) {
  44318. _super.prototype._getActualSizeFromContentToRef.call(this, primSize, newPrimSize);
  44319. }
  44320. else {
  44321. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  44322. newPrimSize.copyFrom(primSize);
  44323. newPrimSize.width += rr * 2;
  44324. newPrimSize.height += rr * 2;
  44325. }
  44326. };
  44327. Rectangle2D.prototype.createInstanceDataParts = function () {
  44328. var res = new Array();
  44329. if (this.border) {
  44330. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  44331. }
  44332. if (this.fill) {
  44333. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  44334. }
  44335. return res;
  44336. };
  44337. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  44338. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  44339. return false;
  44340. }
  44341. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  44342. var d = part;
  44343. var size = this.actualSize;
  44344. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  44345. }
  44346. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  44347. var d = part;
  44348. var size = this.actualSize;
  44349. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  44350. }
  44351. return true;
  44352. };
  44353. Rectangle2D._i0 = BABYLON.Vector2.Zero();
  44354. Rectangle2D._i1 = BABYLON.Vector2.Zero();
  44355. Rectangle2D._i2 = BABYLON.Vector2.Zero();
  44356. Rectangle2D.roundSubdivisions = 16;
  44357. __decorate([
  44358. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D.actualSizeProperty = pi; }, false, true)
  44359. ], Rectangle2D.prototype, "actualSize", null);
  44360. __decorate([
  44361. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D.notRoundedProperty = pi; })
  44362. ], Rectangle2D.prototype, "notRounded", null);
  44363. __decorate([
  44364. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D.roundRadiusProperty = pi; })
  44365. ], Rectangle2D.prototype, "roundRadius", null);
  44366. Rectangle2D = __decorate([
  44367. BABYLON.className("Rectangle2D")
  44368. ], Rectangle2D);
  44369. return Rectangle2D;
  44370. })(BABYLON.Shape2D);
  44371. BABYLON.Rectangle2D = Rectangle2D;
  44372. })(BABYLON || (BABYLON = {}));
  44373. var BABYLON;
  44374. (function (BABYLON) {
  44375. var Ellipse2DRenderCache = (function (_super) {
  44376. __extends(Ellipse2DRenderCache, _super);
  44377. function Ellipse2DRenderCache(engine, modelKey) {
  44378. _super.call(this, engine, modelKey);
  44379. this.effectsReady = false;
  44380. this.fillVB = null;
  44381. this.fillIB = null;
  44382. this.fillIndicesCount = 0;
  44383. this.instancingFillAttributes = null;
  44384. this.effectFillInstanced = null;
  44385. this.effectFill = null;
  44386. this.borderVB = null;
  44387. this.borderIB = null;
  44388. this.borderIndicesCount = 0;
  44389. this.instancingBorderAttributes = null;
  44390. this.effectBorderInstanced = null;
  44391. this.effectBorder = null;
  44392. }
  44393. Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
  44394. // Do nothing if the shader is still loading/preparing
  44395. if (!this.effectsReady) {
  44396. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  44397. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  44398. return false;
  44399. }
  44400. this.effectsReady = true;
  44401. }
  44402. var canvas = instanceInfo.owner.owner;
  44403. var engine = canvas.engine;
  44404. var depthFunction = 0;
  44405. if (this.effectFill && this.effectBorder) {
  44406. depthFunction = engine.getDepthFunction();
  44407. engine.setDepthFunctionToLessOrEqual();
  44408. }
  44409. var curAlphaMode = engine.getAlphaMode();
  44410. if (this.effectFill) {
  44411. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  44412. var pid = context.groupInfoPartData[partIndex];
  44413. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44414. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  44415. }
  44416. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  44417. engine.enableEffect(effect);
  44418. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  44419. if (context.useInstancing) {
  44420. if (!this.instancingFillAttributes) {
  44421. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  44422. }
  44423. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44424. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44425. canvas._addDrawCallCount(1, context.renderMode);
  44426. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  44427. engine.draw(true, 0, this.fillIndicesCount, count);
  44428. engine.unbindInstanceAttributes();
  44429. }
  44430. else {
  44431. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44432. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44433. this.setupUniforms(effect, partIndex, pid._partData, i);
  44434. engine.draw(true, 0, this.fillIndicesCount);
  44435. }
  44436. }
  44437. }
  44438. if (this.effectBorder) {
  44439. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  44440. var pid = context.groupInfoPartData[partIndex];
  44441. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44442. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  44443. }
  44444. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  44445. engine.enableEffect(effect);
  44446. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  44447. if (context.useInstancing) {
  44448. if (!this.instancingBorderAttributes) {
  44449. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  44450. }
  44451. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44452. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44453. canvas._addDrawCallCount(1, context.renderMode);
  44454. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  44455. engine.draw(true, 0, this.borderIndicesCount, count);
  44456. engine.unbindInstanceAttributes();
  44457. }
  44458. else {
  44459. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44460. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44461. this.setupUniforms(effect, partIndex, pid._partData, i);
  44462. engine.draw(true, 0, this.borderIndicesCount);
  44463. }
  44464. }
  44465. }
  44466. engine.setAlphaMode(curAlphaMode, true);
  44467. if (this.effectFill && this.effectBorder) {
  44468. engine.setDepthFunction(depthFunction);
  44469. }
  44470. return true;
  44471. };
  44472. Ellipse2DRenderCache.prototype.dispose = function () {
  44473. if (!_super.prototype.dispose.call(this)) {
  44474. return false;
  44475. }
  44476. if (this.fillVB) {
  44477. this._engine._releaseBuffer(this.fillVB);
  44478. this.fillVB = null;
  44479. }
  44480. if (this.fillIB) {
  44481. this._engine._releaseBuffer(this.fillIB);
  44482. this.fillIB = null;
  44483. }
  44484. this.effectFill = null;
  44485. this.effectFillInstanced = null;
  44486. this.effectBorder = null;
  44487. this.effectBorderInstanced = null;
  44488. if (this.borderVB) {
  44489. this._engine._releaseBuffer(this.borderVB);
  44490. this.borderVB = null;
  44491. }
  44492. if (this.borderIB) {
  44493. this._engine._releaseBuffer(this.borderIB);
  44494. this.borderIB = null;
  44495. }
  44496. return true;
  44497. };
  44498. return Ellipse2DRenderCache;
  44499. })(BABYLON.ModelRenderCache);
  44500. BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
  44501. var Ellipse2DInstanceData = (function (_super) {
  44502. __extends(Ellipse2DInstanceData, _super);
  44503. function Ellipse2DInstanceData(partId) {
  44504. _super.call(this, partId, 1);
  44505. }
  44506. Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
  44507. get: function () {
  44508. return null;
  44509. },
  44510. enumerable: true,
  44511. configurable: true
  44512. });
  44513. __decorate([
  44514. BABYLON.instanceData()
  44515. ], Ellipse2DInstanceData.prototype, "properties", null);
  44516. return Ellipse2DInstanceData;
  44517. })(BABYLON.Shape2DInstanceData);
  44518. BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
  44519. var Ellipse2D = (function (_super) {
  44520. __extends(Ellipse2D, _super);
  44521. /**
  44522. * Create an Ellipse 2D Shape primitive
  44523. * @param settings a combination of settings, possible ones are
  44524. * - 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)
  44525. * - children: an array of direct children
  44526. * - id: a text identifier, for information purpose
  44527. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  44528. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  44529. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  44530. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  44531. * - origin: define the normalized origin point location, default [0.5;0.5]
  44532. * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
  44533. * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
  44534. * - 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)
  44535. * - 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)
  44536. * - borderThickness: the thickness of the drawn border, default is 1.
  44537. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  44538. * - 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!
  44539. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44540. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44541. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44542. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44543. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  44544. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  44545. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  44546. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  44547. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44548. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44549. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44550. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44551. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  44552. */
  44553. function Ellipse2D(settings) {
  44554. // Avoid checking every time if the object exists
  44555. if (settings == null) {
  44556. settings = {};
  44557. }
  44558. _super.call(this, settings);
  44559. if (settings.size != null) {
  44560. this.size = settings.size;
  44561. }
  44562. else if (settings.width || settings.height) {
  44563. var size = new BABYLON.Size(settings.width, settings.height);
  44564. this.size = size;
  44565. }
  44566. var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
  44567. this.subdivisions = sub;
  44568. }
  44569. Object.defineProperty(Ellipse2D.prototype, "actualSize", {
  44570. get: function () {
  44571. if (this._actualSize) {
  44572. return this._actualSize;
  44573. }
  44574. return this.size;
  44575. },
  44576. set: function (value) {
  44577. this._actualSize = value;
  44578. },
  44579. enumerable: true,
  44580. configurable: true
  44581. });
  44582. Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
  44583. get: function () {
  44584. return this._subdivisions;
  44585. },
  44586. set: function (value) {
  44587. this._subdivisions = value;
  44588. },
  44589. enumerable: true,
  44590. configurable: true
  44591. });
  44592. Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
  44593. var w = this.size.width / 2;
  44594. var h = this.size.height / 2;
  44595. var x = intersectInfo._localPickPosition.x - w;
  44596. var y = intersectInfo._localPickPosition.y - h;
  44597. return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
  44598. };
  44599. Ellipse2D.prototype.updateLevelBoundingInfo = function () {
  44600. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  44601. };
  44602. Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
  44603. var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
  44604. return renderCache;
  44605. };
  44606. Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  44607. var renderCache = modelRenderCache;
  44608. var engine = this.owner.engine;
  44609. // Need to create WebGL resources for fill part?
  44610. if (this.fill) {
  44611. var vbSize = this.subdivisions + 1;
  44612. var vb = new Float32Array(vbSize);
  44613. for (var i = 0; i < vbSize; i++) {
  44614. vb[i] = i;
  44615. }
  44616. renderCache.fillVB = engine.createVertexBuffer(vb);
  44617. var triCount = vbSize - 1;
  44618. var ib = new Float32Array(triCount * 3);
  44619. for (var i = 0; i < triCount; i++) {
  44620. ib[i * 3 + 0] = 0;
  44621. ib[i * 3 + 2] = i + 1;
  44622. ib[i * 3 + 1] = i + 2;
  44623. }
  44624. ib[triCount * 3 - 2] = 1;
  44625. renderCache.fillIB = engine.createIndexBuffer(ib);
  44626. renderCache.fillIndicesCount = triCount * 3;
  44627. // 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
  44628. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], true);
  44629. if (ei) {
  44630. renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  44631. }
  44632. // Get the non instanced version
  44633. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], false);
  44634. renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  44635. }
  44636. // Need to create WebGL resource for border part?
  44637. if (this.border) {
  44638. var vbSize = this.subdivisions * 2;
  44639. var vb = new Float32Array(vbSize);
  44640. for (var i = 0; i < vbSize; i++) {
  44641. vb[i] = i;
  44642. }
  44643. renderCache.borderVB = engine.createVertexBuffer(vb);
  44644. var triCount = vbSize;
  44645. var rs = triCount / 2;
  44646. var ib = new Float32Array(triCount * 3);
  44647. for (var i = 0; i < rs; i++) {
  44648. var r0 = i;
  44649. var r1 = (i + 1) % rs;
  44650. ib[i * 6 + 0] = rs + r1;
  44651. ib[i * 6 + 1] = rs + r0;
  44652. ib[i * 6 + 2] = r0;
  44653. ib[i * 6 + 3] = r1;
  44654. ib[i * 6 + 4] = rs + r1;
  44655. ib[i * 6 + 5] = r0;
  44656. }
  44657. renderCache.borderIB = engine.createIndexBuffer(ib);
  44658. renderCache.borderIndicesCount = (triCount * 3);
  44659. // 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
  44660. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], true);
  44661. if (ei) {
  44662. renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44663. }
  44664. // Get the non instanced version
  44665. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], false);
  44666. renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44667. }
  44668. return renderCache;
  44669. };
  44670. Ellipse2D.prototype.createInstanceDataParts = function () {
  44671. var res = new Array();
  44672. if (this.border) {
  44673. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  44674. }
  44675. if (this.fill) {
  44676. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  44677. }
  44678. return res;
  44679. };
  44680. Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
  44681. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  44682. return false;
  44683. }
  44684. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  44685. var d = part;
  44686. var size = this.actualSize;
  44687. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  44688. }
  44689. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  44690. var d = part;
  44691. var size = this.actualSize;
  44692. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  44693. }
  44694. return true;
  44695. };
  44696. __decorate([
  44697. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Ellipse2D.acutalSizeProperty = pi; }, false, true)
  44698. ], Ellipse2D.prototype, "actualSize", null);
  44699. __decorate([
  44700. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D.subdivisionsProperty = pi; })
  44701. ], Ellipse2D.prototype, "subdivisions", null);
  44702. Ellipse2D = __decorate([
  44703. BABYLON.className("Ellipse2D")
  44704. ], Ellipse2D);
  44705. return Ellipse2D;
  44706. })(BABYLON.Shape2D);
  44707. BABYLON.Ellipse2D = Ellipse2D;
  44708. })(BABYLON || (BABYLON = {}));
  44709. var BABYLON;
  44710. (function (BABYLON) {
  44711. var Sprite2DRenderCache = (function (_super) {
  44712. __extends(Sprite2DRenderCache, _super);
  44713. function Sprite2DRenderCache() {
  44714. _super.apply(this, arguments);
  44715. this.effectsReady = false;
  44716. this.vb = null;
  44717. this.ib = null;
  44718. this.instancingAttributes = null;
  44719. this.texture = null;
  44720. this.effect = null;
  44721. this.effectInstanced = null;
  44722. }
  44723. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  44724. // Do nothing if the shader is still loading/preparing
  44725. if (!this.effectsReady) {
  44726. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  44727. return false;
  44728. }
  44729. this.effectsReady = true;
  44730. }
  44731. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  44732. var canvas = instanceInfo.owner.owner;
  44733. var engine = canvas.engine;
  44734. var cur = engine.getAlphaMode();
  44735. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  44736. engine.enableEffect(effect);
  44737. effect.setTexture("diffuseSampler", this.texture);
  44738. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  44739. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44740. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  44741. }
  44742. var pid = context.groupInfoPartData[0];
  44743. if (context.useInstancing) {
  44744. if (!this.instancingAttributes) {
  44745. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
  44746. }
  44747. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  44748. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44749. canvas._addDrawCallCount(1, context.renderMode);
  44750. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  44751. engine.draw(true, 0, 6, count);
  44752. engine.unbindInstanceAttributes();
  44753. }
  44754. else {
  44755. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44756. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44757. this.setupUniforms(effect, 0, pid._partData, i);
  44758. engine.draw(true, 0, 6);
  44759. }
  44760. }
  44761. engine.setAlphaMode(cur, true);
  44762. return true;
  44763. };
  44764. Sprite2DRenderCache.prototype.dispose = function () {
  44765. if (!_super.prototype.dispose.call(this)) {
  44766. return false;
  44767. }
  44768. if (this.vb) {
  44769. this._engine._releaseBuffer(this.vb);
  44770. this.vb = null;
  44771. }
  44772. if (this.ib) {
  44773. this._engine._releaseBuffer(this.ib);
  44774. this.ib = null;
  44775. }
  44776. if (this.texture) {
  44777. this.texture.dispose();
  44778. this.texture = null;
  44779. }
  44780. this.effect = null;
  44781. this.effectInstanced = null;
  44782. return true;
  44783. };
  44784. return Sprite2DRenderCache;
  44785. })(BABYLON.ModelRenderCache);
  44786. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  44787. var Sprite2DInstanceData = (function (_super) {
  44788. __extends(Sprite2DInstanceData, _super);
  44789. function Sprite2DInstanceData(partId) {
  44790. _super.call(this, partId, 1);
  44791. }
  44792. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  44793. get: function () {
  44794. return null;
  44795. },
  44796. enumerable: true,
  44797. configurable: true
  44798. });
  44799. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  44800. get: function () {
  44801. return null;
  44802. },
  44803. enumerable: true,
  44804. configurable: true
  44805. });
  44806. Object.defineProperty(Sprite2DInstanceData.prototype, "scaleFactor", {
  44807. get: function () {
  44808. return null;
  44809. },
  44810. enumerable: true,
  44811. configurable: true
  44812. });
  44813. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  44814. get: function () {
  44815. return null;
  44816. },
  44817. enumerable: true,
  44818. configurable: true
  44819. });
  44820. Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
  44821. // 3 floats being:
  44822. // - x: frame number to display
  44823. // - y: invertY setting
  44824. // - z: alignToPixel setting
  44825. get: function () {
  44826. return null;
  44827. },
  44828. enumerable: true,
  44829. configurable: true
  44830. });
  44831. __decorate([
  44832. BABYLON.instanceData()
  44833. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  44834. __decorate([
  44835. BABYLON.instanceData()
  44836. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  44837. __decorate([
  44838. BABYLON.instanceData()
  44839. ], Sprite2DInstanceData.prototype, "scaleFactor", null);
  44840. __decorate([
  44841. BABYLON.instanceData()
  44842. ], Sprite2DInstanceData.prototype, "textureSize", null);
  44843. __decorate([
  44844. BABYLON.instanceData()
  44845. ], Sprite2DInstanceData.prototype, "properties", null);
  44846. return Sprite2DInstanceData;
  44847. })(BABYLON.InstanceDataBase);
  44848. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  44849. var Sprite2D = (function (_super) {
  44850. __extends(Sprite2D, _super);
  44851. /**
  44852. * Create an 2D Sprite primitive
  44853. * @param texture the texture that stores the sprite to render
  44854. * @param settings a combination of settings, possible ones are
  44855. * - 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)
  44856. * - children: an array of direct children
  44857. * - id a text identifier, for information purpose
  44858. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  44859. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  44860. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  44861. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  44862. * - origin: define the normalized origin point location, default [0.5;0.5]
  44863. * - spriteSize: the size of the sprite (in pixels), if null the size of the given texture will be used, default is null.
  44864. * - spriteLocation: the location (in pixels) in the texture of the top/left corner of the Sprite to display, default is null (0,0)
  44865. * - 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.
  44866. * - invertY: if true the texture Y will be inverted, default is false.
  44867. * - 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.
  44868. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  44869. * - 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!
  44870. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44871. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44872. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44873. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44874. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  44875. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  44876. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  44877. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  44878. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44879. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44880. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44881. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44882. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  44883. */
  44884. function Sprite2D(texture, settings) {
  44885. var _this = this;
  44886. if (!settings) {
  44887. settings = {};
  44888. }
  44889. _super.call(this, settings);
  44890. this.texture = texture;
  44891. this.texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44892. this.texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44893. this.size = settings.spriteSize;
  44894. this.spriteLocation = settings.spriteLocation || new BABYLON.Vector2(0, 0);
  44895. this.spriteScaleFactor = settings.spriteScaleFactor || new BABYLON.Vector2(1, 1);
  44896. this.spriteFrame = 0;
  44897. this.invertY = (settings.invertY == null) ? false : settings.invertY;
  44898. this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  44899. this.isAlphaTest = true;
  44900. if (settings.spriteSize == null || !texture.isReady()) {
  44901. if (texture.isReady()) {
  44902. this.size = texture.getBaseSize();
  44903. }
  44904. else {
  44905. texture.onLoadObservable.add(function () {
  44906. if (settings.spriteSize == null) {
  44907. _this.size = texture.getBaseSize();
  44908. }
  44909. _this._positioningDirty();
  44910. _this._instanceDirtyFlags |= Sprite2D.textureProperty.flagId; // To make sure the sprite is issued again for render
  44911. });
  44912. }
  44913. }
  44914. }
  44915. Object.defineProperty(Sprite2D.prototype, "texture", {
  44916. get: function () {
  44917. return this._texture;
  44918. },
  44919. set: function (value) {
  44920. this._texture = value;
  44921. },
  44922. enumerable: true,
  44923. configurable: true
  44924. });
  44925. Object.defineProperty(Sprite2D.prototype, "actualSize", {
  44926. get: function () {
  44927. if (this._actualSize) {
  44928. return this._actualSize;
  44929. }
  44930. return this.size;
  44931. },
  44932. set: function (value) {
  44933. this._actualSize = value;
  44934. },
  44935. enumerable: true,
  44936. configurable: true
  44937. });
  44938. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  44939. get: function () {
  44940. return this._location;
  44941. },
  44942. set: function (value) {
  44943. this._location = value;
  44944. },
  44945. enumerable: true,
  44946. configurable: true
  44947. });
  44948. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  44949. get: function () {
  44950. return this._spriteFrame;
  44951. },
  44952. set: function (value) {
  44953. this._spriteFrame = value;
  44954. },
  44955. enumerable: true,
  44956. configurable: true
  44957. });
  44958. Object.defineProperty(Sprite2D.prototype, "invertY", {
  44959. get: function () {
  44960. return this._invertY;
  44961. },
  44962. set: function (value) {
  44963. this._invertY = value;
  44964. },
  44965. enumerable: true,
  44966. configurable: true
  44967. });
  44968. Object.defineProperty(Sprite2D.prototype, "spriteScaleFactor", {
  44969. get: function () {
  44970. return this._spriteScaleFactor;
  44971. },
  44972. set: function (value) {
  44973. this._spriteScaleFactor = value;
  44974. },
  44975. enumerable: true,
  44976. configurable: true
  44977. });
  44978. Object.defineProperty(Sprite2D.prototype, "alignToPixel", {
  44979. /**
  44980. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  44981. */
  44982. get: function () {
  44983. return this._alignToPixel;
  44984. },
  44985. set: function (value) {
  44986. this._alignToPixel = value;
  44987. },
  44988. enumerable: true,
  44989. configurable: true
  44990. });
  44991. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  44992. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
  44993. };
  44994. /**
  44995. * Get the animatable array (see http://doc.babylonjs.com/tutorials/Animations)
  44996. */
  44997. Sprite2D.prototype.getAnimatables = function () {
  44998. var res = new Array();
  44999. if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
  45000. res.push(this.texture);
  45001. }
  45002. return res;
  45003. };
  45004. Sprite2D.prototype.levelIntersect = function (intersectInfo) {
  45005. // 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
  45006. return true;
  45007. };
  45008. Sprite2D._createCachedCanvasSprite = function (owner, texture, size, pos) {
  45009. var sprite = new Sprite2D(texture, { parent: owner, id: "__cachedCanvasSprite__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), spriteSize: size, spriteLocation: pos, alignToPixel: true });
  45010. return sprite;
  45011. };
  45012. Sprite2D.prototype.createModelRenderCache = function (modelKey) {
  45013. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
  45014. return renderCache;
  45015. };
  45016. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  45017. var renderCache = modelRenderCache;
  45018. var engine = this.owner.engine;
  45019. var vb = new Float32Array(4);
  45020. for (var i = 0; i < 4; i++) {
  45021. vb[i] = i;
  45022. }
  45023. renderCache.vb = engine.createVertexBuffer(vb);
  45024. var ib = new Float32Array(6);
  45025. ib[0] = 0;
  45026. ib[1] = 2;
  45027. ib[2] = 1;
  45028. ib[3] = 0;
  45029. ib[4] = 3;
  45030. ib[5] = 2;
  45031. renderCache.ib = engine.createIndexBuffer(ib);
  45032. renderCache.texture = this.texture;
  45033. // 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
  45034. var ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], true);
  45035. if (ei) {
  45036. renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  45037. }
  45038. ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], false);
  45039. renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  45040. return renderCache;
  45041. };
  45042. Sprite2D.prototype.createInstanceDataParts = function () {
  45043. return [new Sprite2DInstanceData(Sprite2D.SPRITE2D_MAINPARTID)];
  45044. };
  45045. Sprite2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  45046. Sprite2D.layoutConstructMode = true;
  45047. };
  45048. // if obj contains something, we restore the _text property
  45049. Sprite2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  45050. Sprite2D.layoutConstructMode = false;
  45051. };
  45052. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  45053. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  45054. return false;
  45055. }
  45056. if (!this.texture.isReady() && !Sprite2D.layoutConstructMode) {
  45057. return false;
  45058. }
  45059. if (part.id === Sprite2D.SPRITE2D_MAINPARTID) {
  45060. var d = this._instanceDataParts[0];
  45061. if (Sprite2D.layoutConstructMode) {
  45062. d.topLeftUV = BABYLON.Vector2.Zero();
  45063. d.sizeUV = BABYLON.Vector2.Zero();
  45064. d.properties = BABYLON.Vector3.Zero();
  45065. d.textureSize = BABYLON.Vector2.Zero();
  45066. d.scaleFactor = BABYLON.Vector2.Zero();
  45067. }
  45068. else {
  45069. var ts = this.texture.getBaseSize();
  45070. var sl = this.spriteLocation;
  45071. var ss = this.actualSize;
  45072. var ssf = this.spriteScaleFactor;
  45073. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  45074. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  45075. d.sizeUV = suv;
  45076. d.scaleFactor = ssf;
  45077. Sprite2D._prop.x = this.spriteFrame;
  45078. Sprite2D._prop.y = this.invertY ? 1 : 0;
  45079. Sprite2D._prop.z = this.alignToPixel ? 1 : 0;
  45080. d.properties = Sprite2D._prop;
  45081. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  45082. }
  45083. }
  45084. return true;
  45085. };
  45086. Sprite2D.SPRITE2D_MAINPARTID = 1;
  45087. Sprite2D._prop = BABYLON.Vector3.Zero();
  45088. Sprite2D.layoutConstructMode = false;
  45089. __decorate([
  45090. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D.textureProperty = pi; })
  45091. ], Sprite2D.prototype, "texture", null);
  45092. __decorate([
  45093. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D.actualSizeProperty = pi; }, false, true)
  45094. ], Sprite2D.prototype, "actualSize", null);
  45095. __decorate([
  45096. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Sprite2D.spriteLocationProperty = pi; })
  45097. ], Sprite2D.prototype, "spriteLocation", null);
  45098. __decorate([
  45099. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D.spriteFrameProperty = pi; })
  45100. ], Sprite2D.prototype, "spriteFrame", null);
  45101. __decorate([
  45102. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D.invertYProperty = pi; })
  45103. ], Sprite2D.prototype, "invertY", null);
  45104. __decorate([
  45105. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Sprite2D.spriteScaleFactorProperty = pi; })
  45106. ], Sprite2D.prototype, "spriteScaleFactor", null);
  45107. Sprite2D = __decorate([
  45108. BABYLON.className("Sprite2D")
  45109. ], Sprite2D);
  45110. return Sprite2D;
  45111. })(BABYLON.RenderablePrim2D);
  45112. BABYLON.Sprite2D = Sprite2D;
  45113. })(BABYLON || (BABYLON = {}));
  45114. var BABYLON;
  45115. (function (BABYLON) {
  45116. var Text2DRenderCache = (function (_super) {
  45117. __extends(Text2DRenderCache, _super);
  45118. function Text2DRenderCache() {
  45119. _super.apply(this, arguments);
  45120. this.effectsReady = false;
  45121. this.vb = null;
  45122. this.ib = null;
  45123. this.instancingAttributes = null;
  45124. this.fontTexture = null;
  45125. this.effect = null;
  45126. this.effectInstanced = null;
  45127. }
  45128. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  45129. // Do nothing if the shader is still loading/preparing
  45130. if (!this.effectsReady) {
  45131. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  45132. return false;
  45133. }
  45134. this.effectsReady = true;
  45135. }
  45136. var canvas = instanceInfo.owner.owner;
  45137. var engine = canvas.engine;
  45138. this.fontTexture.update();
  45139. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  45140. engine.enableEffect(effect);
  45141. effect.setTexture("diffuseSampler", this.fontTexture);
  45142. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  45143. var curAlphaMode = engine.getAlphaMode();
  45144. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45145. var pid = context.groupInfoPartData[0];
  45146. if (context.useInstancing) {
  45147. if (!this.instancingAttributes) {
  45148. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
  45149. }
  45150. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  45151. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45152. canvas._addDrawCallCount(1, context.renderMode);
  45153. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  45154. engine.draw(true, 0, 6, count);
  45155. engine.unbindInstanceAttributes();
  45156. }
  45157. else {
  45158. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45159. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45160. this.setupUniforms(effect, 0, pid._partData, i);
  45161. engine.draw(true, 0, 6);
  45162. }
  45163. }
  45164. engine.setAlphaMode(curAlphaMode, true);
  45165. return true;
  45166. };
  45167. Text2DRenderCache.prototype.dispose = function () {
  45168. if (!_super.prototype.dispose.call(this)) {
  45169. return false;
  45170. }
  45171. if (this.vb) {
  45172. this._engine._releaseBuffer(this.vb);
  45173. this.vb = null;
  45174. }
  45175. if (this.ib) {
  45176. this._engine._releaseBuffer(this.ib);
  45177. this.ib = null;
  45178. }
  45179. if (this.fontTexture) {
  45180. this.fontTexture.decCachedFontTextureCounter();
  45181. this.fontTexture = null;
  45182. }
  45183. this.effect = null;
  45184. this.effectInstanced = null;
  45185. return true;
  45186. };
  45187. return Text2DRenderCache;
  45188. })(BABYLON.ModelRenderCache);
  45189. BABYLON.Text2DRenderCache = Text2DRenderCache;
  45190. var Text2DInstanceData = (function (_super) {
  45191. __extends(Text2DInstanceData, _super);
  45192. function Text2DInstanceData(partId, dataElementCount) {
  45193. _super.call(this, partId, dataElementCount);
  45194. }
  45195. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  45196. get: function () {
  45197. return null;
  45198. },
  45199. enumerable: true,
  45200. configurable: true
  45201. });
  45202. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  45203. get: function () {
  45204. return null;
  45205. },
  45206. enumerable: true,
  45207. configurable: true
  45208. });
  45209. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  45210. get: function () {
  45211. return null;
  45212. },
  45213. enumerable: true,
  45214. configurable: true
  45215. });
  45216. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  45217. get: function () {
  45218. return null;
  45219. },
  45220. enumerable: true,
  45221. configurable: true
  45222. });
  45223. Object.defineProperty(Text2DInstanceData.prototype, "superSampleFactor", {
  45224. get: function () {
  45225. return null;
  45226. },
  45227. enumerable: true,
  45228. configurable: true
  45229. });
  45230. __decorate([
  45231. BABYLON.instanceData()
  45232. ], Text2DInstanceData.prototype, "topLeftUV", null);
  45233. __decorate([
  45234. BABYLON.instanceData()
  45235. ], Text2DInstanceData.prototype, "sizeUV", null);
  45236. __decorate([
  45237. BABYLON.instanceData()
  45238. ], Text2DInstanceData.prototype, "textureSize", null);
  45239. __decorate([
  45240. BABYLON.instanceData()
  45241. ], Text2DInstanceData.prototype, "color", null);
  45242. __decorate([
  45243. BABYLON.instanceData()
  45244. ], Text2DInstanceData.prototype, "superSampleFactor", null);
  45245. return Text2DInstanceData;
  45246. })(BABYLON.InstanceDataBase);
  45247. BABYLON.Text2DInstanceData = Text2DInstanceData;
  45248. var Text2D = (function (_super) {
  45249. __extends(Text2D, _super);
  45250. /**
  45251. * Create a Text primitive
  45252. * @param text the text to display
  45253. * @param settings a combination of settings, possible ones are
  45254. * - 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)
  45255. * - children: an array of direct children
  45256. * - id a text identifier, for information purpose
  45257. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  45258. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  45259. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  45260. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  45261. * - origin: define the normalized origin point location, default [0.5;0.5]
  45262. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  45263. * - 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.
  45264. * - defaultColor: the color by default to apply on each letter of the text to display, default is plain white.
  45265. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  45266. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  45267. * - isVisible: true if the text must be visible, false for hidden. Default is true.
  45268. * - 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!
  45269. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45270. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45271. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45272. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45273. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  45274. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  45275. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  45276. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  45277. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45278. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45279. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45280. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45281. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  45282. */
  45283. function Text2D(text, settings) {
  45284. if (!settings) {
  45285. settings = {};
  45286. }
  45287. _super.call(this, settings);
  45288. this.fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
  45289. this._fontSuperSample = (settings.fontSuperSample != null && settings.fontSuperSample);
  45290. this.defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor;
  45291. this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
  45292. this._textSize = null;
  45293. this.text = text;
  45294. this.size = (settings.size == null) ? null : settings.size;
  45295. this.isTransparent = true;
  45296. }
  45297. Object.defineProperty(Text2D.prototype, "fontName", {
  45298. get: function () {
  45299. return this._fontName;
  45300. },
  45301. set: function (value) {
  45302. if (this._fontName) {
  45303. throw new Error("Font Name change is not supported right now.");
  45304. }
  45305. this._fontName = value;
  45306. },
  45307. enumerable: true,
  45308. configurable: true
  45309. });
  45310. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  45311. get: function () {
  45312. return this._defaultFontColor;
  45313. },
  45314. set: function (value) {
  45315. this._defaultFontColor = value;
  45316. },
  45317. enumerable: true,
  45318. configurable: true
  45319. });
  45320. Object.defineProperty(Text2D.prototype, "text", {
  45321. get: function () {
  45322. return this._text;
  45323. },
  45324. set: function (value) {
  45325. this._text = value;
  45326. this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
  45327. this._size = null;
  45328. this._updateCharCount();
  45329. // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
  45330. var s = this.textSize;
  45331. },
  45332. enumerable: true,
  45333. configurable: true
  45334. });
  45335. Object.defineProperty(Text2D.prototype, "size", {
  45336. get: function () {
  45337. if (this._size != null) {
  45338. return this._size;
  45339. }
  45340. return this.textSize;
  45341. },
  45342. set: function (value) {
  45343. this._size = value;
  45344. },
  45345. enumerable: true,
  45346. configurable: true
  45347. });
  45348. Object.defineProperty(Text2D.prototype, "actualSize", {
  45349. /**
  45350. * Get the actual size of the Text2D primitive
  45351. */
  45352. get: function () {
  45353. if (this._actualSize) {
  45354. return this._actualSize;
  45355. }
  45356. return this.size;
  45357. },
  45358. enumerable: true,
  45359. configurable: true
  45360. });
  45361. Object.defineProperty(Text2D.prototype, "textSize", {
  45362. /**
  45363. * Get the area that bounds the text associated to the primitive
  45364. */
  45365. get: function () {
  45366. if (!this._textSize) {
  45367. if (this.owner) {
  45368. var newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  45369. if (!newSize.equals(this._textSize)) {
  45370. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  45371. this._positioningDirty();
  45372. }
  45373. this._textSize = newSize;
  45374. }
  45375. else {
  45376. return Text2D.nullSize;
  45377. }
  45378. }
  45379. return this._textSize;
  45380. },
  45381. enumerable: true,
  45382. configurable: true
  45383. });
  45384. Object.defineProperty(Text2D.prototype, "fontTexture", {
  45385. get: function () {
  45386. if (this._fontTexture) {
  45387. return this._fontTexture;
  45388. }
  45389. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  45390. return this._fontTexture;
  45391. },
  45392. enumerable: true,
  45393. configurable: true
  45394. });
  45395. /**
  45396. * Dispose the primitive, remove it from its parent
  45397. */
  45398. Text2D.prototype.dispose = function () {
  45399. if (!_super.prototype.dispose.call(this)) {
  45400. return false;
  45401. }
  45402. if (this._fontTexture) {
  45403. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  45404. this._fontTexture = null;
  45405. }
  45406. return true;
  45407. };
  45408. Text2D.prototype.updateLevelBoundingInfo = function () {
  45409. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  45410. };
  45411. Text2D.prototype.levelIntersect = function (intersectInfo) {
  45412. // 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...
  45413. return true;
  45414. };
  45415. Text2D.prototype.createModelRenderCache = function (modelKey) {
  45416. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
  45417. return renderCache;
  45418. };
  45419. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  45420. var renderCache = modelRenderCache;
  45421. var engine = this.owner.engine;
  45422. renderCache.fontTexture = this.fontTexture;
  45423. renderCache.fontTexture.incCachedFontTextureCounter();
  45424. var vb = new Float32Array(4);
  45425. for (var i = 0; i < 4; i++) {
  45426. vb[i] = i;
  45427. }
  45428. renderCache.vb = engine.createVertexBuffer(vb);
  45429. var ib = new Float32Array(6);
  45430. ib[0] = 0;
  45431. ib[1] = 2;
  45432. ib[2] = 1;
  45433. ib[3] = 0;
  45434. ib[4] = 3;
  45435. ib[5] = 2;
  45436. renderCache.ib = engine.createIndexBuffer(ib);
  45437. // 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
  45438. var ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], true);
  45439. if (ei) {
  45440. renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  45441. }
  45442. ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], false);
  45443. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  45444. return renderCache;
  45445. };
  45446. Text2D.prototype.createInstanceDataParts = function () {
  45447. return [new Text2DInstanceData(Text2D.TEXT2D_MAINPARTID, this._charCount)];
  45448. };
  45449. // Looks like a hack!? Yes! Because that's what it is!
  45450. // 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
  45451. // 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)
  45452. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  45453. if (!this._charCount) {
  45454. var curText = this._text;
  45455. this.text = "A";
  45456. return curText;
  45457. }
  45458. };
  45459. // if obj contains something, we restore the _text property
  45460. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  45461. if (obj !== undefined) {
  45462. this.text = obj;
  45463. }
  45464. };
  45465. Text2D.prototype.refreshInstanceDataPart = function (part) {
  45466. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  45467. return false;
  45468. }
  45469. if (part.id === Text2D.TEXT2D_MAINPARTID) {
  45470. var d = part;
  45471. var texture = this.fontTexture;
  45472. var superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
  45473. var ts = texture.getSize();
  45474. var offset = BABYLON.Vector2.Zero();
  45475. var lh = this.fontTexture.lineHeight;
  45476. 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
  45477. var charxpos = 0;
  45478. d.dataElementCount = this._charCount;
  45479. d.curElement = 0;
  45480. for (var _i = 0, _a = this.text; _i < _a.length; _i++) {
  45481. var char = _a[_i];
  45482. // Line feed
  45483. if (char === "\n") {
  45484. offset.x = 0;
  45485. offset.y -= texture.lineHeight;
  45486. }
  45487. // Tabulation ?
  45488. if (char === "\t") {
  45489. var nextPos = charxpos + this._tabulationSize;
  45490. nextPos = nextPos - (nextPos % this._tabulationSize);
  45491. offset.x += (nextPos - charxpos) * texture.spaceWidth;
  45492. charxpos = nextPos;
  45493. continue;
  45494. }
  45495. if (char < " ") {
  45496. continue;
  45497. }
  45498. this.updateInstanceDataPart(d, offset);
  45499. var ci = texture.getChar(char);
  45500. offset.x += ci.charWidth;
  45501. d.topLeftUV = ci.topLeftUV;
  45502. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  45503. d.sizeUV = suv;
  45504. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  45505. d.color = this.defaultFontColor;
  45506. d.superSampleFactor = superSampleFactor;
  45507. ++d.curElement;
  45508. }
  45509. }
  45510. return true;
  45511. };
  45512. Text2D.prototype._updateCharCount = function () {
  45513. var count = 0;
  45514. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  45515. var char = _a[_i];
  45516. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  45517. continue;
  45518. }
  45519. ++count;
  45520. }
  45521. this._charCount = count;
  45522. };
  45523. Text2D.TEXT2D_MAINPARTID = 1;
  45524. __decorate([
  45525. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D.fontProperty = pi; }, false, true)
  45526. ], Text2D.prototype, "fontName", null);
  45527. __decorate([
  45528. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D.defaultFontColorProperty = pi; })
  45529. ], Text2D.prototype, "defaultFontColor", null);
  45530. __decorate([
  45531. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D.textProperty = pi; }, false, true)
  45532. ], Text2D.prototype, "text", null);
  45533. __decorate([
  45534. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D.sizeProperty = pi; })
  45535. ], Text2D.prototype, "size", null);
  45536. Text2D = __decorate([
  45537. BABYLON.className("Text2D")
  45538. ], Text2D);
  45539. return Text2D;
  45540. })(BABYLON.RenderablePrim2D);
  45541. BABYLON.Text2D = Text2D;
  45542. })(BABYLON || (BABYLON = {}));
  45543. var BABYLON;
  45544. (function (BABYLON) {
  45545. var Lines2DRenderCache = (function (_super) {
  45546. __extends(Lines2DRenderCache, _super);
  45547. function Lines2DRenderCache(engine, modelKey) {
  45548. _super.call(this, engine, modelKey);
  45549. this.effectsReady = false;
  45550. this.fillVB = null;
  45551. this.fillIB = null;
  45552. this.fillIndicesCount = 0;
  45553. this.instancingFillAttributes = null;
  45554. this.effectFill = null;
  45555. this.effectFillInstanced = null;
  45556. this.borderVB = null;
  45557. this.borderIB = null;
  45558. this.borderIndicesCount = 0;
  45559. this.instancingBorderAttributes = null;
  45560. this.effectBorder = null;
  45561. this.effectBorderInstanced = null;
  45562. }
  45563. Lines2DRenderCache.prototype.render = function (instanceInfo, context) {
  45564. // Do nothing if the shader is still loading/preparing
  45565. if (!this.effectsReady) {
  45566. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  45567. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  45568. return false;
  45569. }
  45570. this.effectsReady = true;
  45571. }
  45572. var canvas = instanceInfo.owner.owner;
  45573. var engine = canvas.engine;
  45574. var depthFunction = 0;
  45575. if (this.effectFill && this.effectBorder) {
  45576. depthFunction = engine.getDepthFunction();
  45577. engine.setDepthFunctionToLessOrEqual();
  45578. }
  45579. var curAlphaMode = engine.getAlphaMode();
  45580. if (this.effectFill) {
  45581. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  45582. var pid = context.groupInfoPartData[partIndex];
  45583. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45584. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45585. }
  45586. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  45587. engine.enableEffect(effect);
  45588. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [2], 2 * 4, effect);
  45589. if (context.useInstancing) {
  45590. if (!this.instancingFillAttributes) {
  45591. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  45592. }
  45593. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  45594. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45595. canvas._addDrawCallCount(1, context.renderMode);
  45596. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  45597. engine.draw(true, 0, this.fillIndicesCount, count);
  45598. engine.unbindInstanceAttributes();
  45599. }
  45600. else {
  45601. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45602. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45603. this.setupUniforms(effect, partIndex, pid._partData, i);
  45604. engine.draw(true, 0, this.fillIndicesCount);
  45605. }
  45606. }
  45607. }
  45608. if (this.effectBorder) {
  45609. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  45610. var pid = context.groupInfoPartData[partIndex];
  45611. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45612. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45613. }
  45614. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  45615. engine.enableEffect(effect);
  45616. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [2], 2 * 4, effect);
  45617. if (context.useInstancing) {
  45618. if (!this.instancingBorderAttributes) {
  45619. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  45620. }
  45621. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  45622. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45623. canvas._addDrawCallCount(1, context.renderMode);
  45624. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  45625. engine.draw(true, 0, this.borderIndicesCount, count);
  45626. engine.unbindInstanceAttributes();
  45627. }
  45628. else {
  45629. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45630. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45631. this.setupUniforms(effect, partIndex, pid._partData, i);
  45632. engine.draw(true, 0, this.borderIndicesCount);
  45633. }
  45634. }
  45635. }
  45636. engine.setAlphaMode(curAlphaMode, true);
  45637. if (this.effectFill && this.effectBorder) {
  45638. engine.setDepthFunction(depthFunction);
  45639. }
  45640. return true;
  45641. };
  45642. Lines2DRenderCache.prototype.dispose = function () {
  45643. if (!_super.prototype.dispose.call(this)) {
  45644. return false;
  45645. }
  45646. if (this.fillVB) {
  45647. this._engine._releaseBuffer(this.fillVB);
  45648. this.fillVB = null;
  45649. }
  45650. if (this.fillIB) {
  45651. this._engine._releaseBuffer(this.fillIB);
  45652. this.fillIB = null;
  45653. }
  45654. this.effectFill = null;
  45655. this.effectFillInstanced = null;
  45656. this.effectBorder = null;
  45657. this.effectBorderInstanced = null;
  45658. if (this.borderVB) {
  45659. this._engine._releaseBuffer(this.borderVB);
  45660. this.borderVB = null;
  45661. }
  45662. if (this.borderIB) {
  45663. this._engine._releaseBuffer(this.borderIB);
  45664. this.borderIB = null;
  45665. }
  45666. return true;
  45667. };
  45668. return Lines2DRenderCache;
  45669. })(BABYLON.ModelRenderCache);
  45670. BABYLON.Lines2DRenderCache = Lines2DRenderCache;
  45671. var Lines2DInstanceData = (function (_super) {
  45672. __extends(Lines2DInstanceData, _super);
  45673. function Lines2DInstanceData(partId) {
  45674. _super.call(this, partId, 1);
  45675. }
  45676. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMin", {
  45677. get: function () {
  45678. return null;
  45679. },
  45680. enumerable: true,
  45681. configurable: true
  45682. });
  45683. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMax", {
  45684. get: function () {
  45685. return null;
  45686. },
  45687. enumerable: true,
  45688. configurable: true
  45689. });
  45690. __decorate([
  45691. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  45692. ], Lines2DInstanceData.prototype, "boundingMin", null);
  45693. __decorate([
  45694. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  45695. ], Lines2DInstanceData.prototype, "boundingMax", null);
  45696. return Lines2DInstanceData;
  45697. })(BABYLON.Shape2DInstanceData);
  45698. BABYLON.Lines2DInstanceData = Lines2DInstanceData;
  45699. var Lines2D = (function (_super) {
  45700. __extends(Lines2D, _super);
  45701. /**
  45702. * Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below)
  45703. * @param points an array that describe the points to use to draw the line, must contain at least two entries.
  45704. * @param settings a combination of settings, possible ones are
  45705. * - 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)
  45706. * - children: an array of direct children
  45707. * - id a text identifier, for information purpose
  45708. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  45709. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  45710. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  45711. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  45712. * - origin: define the normalized origin point location, default [0.5;0.5]
  45713. * - 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.
  45714. * - 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.
  45715. * - 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.
  45716. * - 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.
  45717. * - 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)
  45718. * - 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)
  45719. * - borderThickness: the thickness of the drawn border, default is 1.
  45720. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  45721. * - 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!
  45722. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45723. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45724. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45725. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45726. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  45727. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  45728. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  45729. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  45730. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45731. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45732. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45733. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45734. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  45735. */
  45736. function Lines2D(points, settings) {
  45737. if (!settings) {
  45738. settings = {};
  45739. }
  45740. _super.call(this, settings);
  45741. this._fillVB = null;
  45742. this._fillIB = null;
  45743. this._borderVB = null;
  45744. this._borderIB = null;
  45745. this._size = BABYLON.Size.Zero();
  45746. this._boundingMin = null;
  45747. this._boundingMax = null;
  45748. var fillThickness = (settings.fillThickness == null) ? 1 : settings.fillThickness;
  45749. var startCap = (settings.startCap == null) ? 0 : settings.startCap;
  45750. var endCap = (settings.endCap == null) ? 0 : settings.endCap;
  45751. var closed = (settings.closed == null) ? false : settings.closed;
  45752. this.points = points;
  45753. this.fillThickness = fillThickness;
  45754. this.startCap = startCap;
  45755. this.endCap = endCap;
  45756. this.closed = closed;
  45757. }
  45758. Object.defineProperty(Lines2D, "NoCap", {
  45759. /**
  45760. * No Cap to apply on the extremity
  45761. */
  45762. get: function () { return Lines2D._noCap; },
  45763. enumerable: true,
  45764. configurable: true
  45765. });
  45766. Object.defineProperty(Lines2D, "RoundCap", {
  45767. /**
  45768. * A round cap, will use the line thickness as diameter
  45769. */
  45770. get: function () { return Lines2D._roundCap; },
  45771. enumerable: true,
  45772. configurable: true
  45773. });
  45774. Object.defineProperty(Lines2D, "TriangleCap", {
  45775. /**
  45776. * Creates a triangle at the extremity.
  45777. */
  45778. get: function () { return Lines2D._triangleCap; },
  45779. enumerable: true,
  45780. configurable: true
  45781. });
  45782. Object.defineProperty(Lines2D, "SquareAnchorCap", {
  45783. /**
  45784. * Creates a Square anchor at the extremity, the square size is twice the thickness of the line
  45785. */
  45786. get: function () { return Lines2D._squareAnchorCap; },
  45787. enumerable: true,
  45788. configurable: true
  45789. });
  45790. Object.defineProperty(Lines2D, "RoundAnchorCap", {
  45791. /**
  45792. * Creates a round anchor at the extremity, the diameter is twice the thickness of the line
  45793. */
  45794. get: function () { return Lines2D._roundAnchorCap; },
  45795. enumerable: true,
  45796. configurable: true
  45797. });
  45798. Object.defineProperty(Lines2D, "DiamondAnchorCap", {
  45799. /**
  45800. * Creates a diamond anchor at the extremity.
  45801. */
  45802. get: function () { return Lines2D._diamondAnchorCap; },
  45803. enumerable: true,
  45804. configurable: true
  45805. });
  45806. Object.defineProperty(Lines2D, "ArrowCap", {
  45807. /**
  45808. * Creates an arrow anchor at the extremity. the arrow base size is twice the thickness of the line
  45809. */
  45810. get: function () { return Lines2D._arrowCap; },
  45811. enumerable: true,
  45812. configurable: true
  45813. });
  45814. Object.defineProperty(Lines2D.prototype, "points", {
  45815. get: function () {
  45816. return this._points;
  45817. },
  45818. set: function (value) {
  45819. this._points = value;
  45820. this._contour = null;
  45821. this._boundingBoxDirty();
  45822. },
  45823. enumerable: true,
  45824. configurable: true
  45825. });
  45826. Object.defineProperty(Lines2D.prototype, "fillThickness", {
  45827. get: function () {
  45828. return this._fillThickness;
  45829. },
  45830. set: function (value) {
  45831. this._fillThickness = value;
  45832. },
  45833. enumerable: true,
  45834. configurable: true
  45835. });
  45836. Object.defineProperty(Lines2D.prototype, "closed", {
  45837. get: function () {
  45838. return this._closed;
  45839. },
  45840. set: function (value) {
  45841. this._closed = value;
  45842. },
  45843. enumerable: true,
  45844. configurable: true
  45845. });
  45846. Object.defineProperty(Lines2D.prototype, "startCap", {
  45847. get: function () {
  45848. return this._startCap;
  45849. },
  45850. set: function (value) {
  45851. this._startCap = value;
  45852. },
  45853. enumerable: true,
  45854. configurable: true
  45855. });
  45856. Object.defineProperty(Lines2D.prototype, "endCap", {
  45857. get: function () {
  45858. return this._endCap;
  45859. },
  45860. set: function (value) {
  45861. this._endCap = value;
  45862. },
  45863. enumerable: true,
  45864. configurable: true
  45865. });
  45866. Lines2D.prototype.levelIntersect = function (intersectInfo) {
  45867. var _this = this;
  45868. if (this._contour == null) {
  45869. this._computeLines2D();
  45870. }
  45871. var pl = this.points.length;
  45872. var l = this.closed ? pl + 1 : pl;
  45873. var p = intersectInfo._localPickPosition;
  45874. this.transformPointWithOriginToRef(this._contour[0], null, Lines2D._prevA);
  45875. this.transformPointWithOriginToRef(this._contour[1], null, Lines2D._prevB);
  45876. for (var i = 1; i < l; i++) {
  45877. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 0], null, Lines2D._curA);
  45878. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 1], null, Lines2D._curB);
  45879. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curA)) {
  45880. return true;
  45881. }
  45882. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._curA, Lines2D._prevB, Lines2D._curB)) {
  45883. return true;
  45884. }
  45885. Lines2D._prevA.x = Lines2D._curA.x;
  45886. Lines2D._prevA.y = Lines2D._curA.y;
  45887. Lines2D._prevB.x = Lines2D._curB.x;
  45888. Lines2D._prevB.y = Lines2D._curB.y;
  45889. }
  45890. var capIntersect = function (tri, points) {
  45891. var l = tri.length;
  45892. for (var i = 0; i < l; i += 3) {
  45893. Lines2D._curA.x = points[tri[i + 0] * 2 + 0];
  45894. Lines2D._curA.y = points[tri[i + 0] * 2 + 1];
  45895. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._curB);
  45896. Lines2D._curA.x = points[tri[i + 1] * 2 + 0];
  45897. Lines2D._curA.y = points[tri[i + 1] * 2 + 1];
  45898. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevA);
  45899. Lines2D._curA.x = points[tri[i + 2] * 2 + 0];
  45900. Lines2D._curA.y = points[tri[i + 2] * 2 + 1];
  45901. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevB);
  45902. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curB)) {
  45903. return true;
  45904. }
  45905. }
  45906. return false;
  45907. };
  45908. if (this._startCapTriIndices) {
  45909. if (this._startCapTriIndices && capIntersect(this._startCapTriIndices, this._startCapContour)) {
  45910. return true;
  45911. }
  45912. if (this._endCapTriIndices && capIntersect(this._endCapTriIndices, this._endCapContour)) {
  45913. return true;
  45914. }
  45915. }
  45916. return false;
  45917. };
  45918. Object.defineProperty(Lines2D.prototype, "boundingMin", {
  45919. get: function () {
  45920. if (!this._boundingMin) {
  45921. this._computeLines2D();
  45922. }
  45923. return this._boundingMin;
  45924. },
  45925. enumerable: true,
  45926. configurable: true
  45927. });
  45928. Object.defineProperty(Lines2D.prototype, "boundingMax", {
  45929. get: function () {
  45930. if (!this._boundingMax) {
  45931. this._computeLines2D();
  45932. }
  45933. return this._boundingMax;
  45934. },
  45935. enumerable: true,
  45936. configurable: true
  45937. });
  45938. Lines2D.prototype.getUsedShaderCategories = function (dataPart) {
  45939. var res = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  45940. // Remove the BORDER category, we don't use it in the VertexShader
  45941. var i = res.indexOf(BABYLON.Shape2D.SHAPE2D_CATEGORY_BORDER);
  45942. if (i !== -1) {
  45943. res.splice(i, 1);
  45944. }
  45945. return res;
  45946. };
  45947. Lines2D.prototype.updateLevelBoundingInfo = function () {
  45948. if (!this._boundingMin) {
  45949. this._computeLines2D();
  45950. }
  45951. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(this._boundingMin.x, this._boundingMax.x, this._boundingMin.y, this._boundingMax.y, this._levelBoundingInfo);
  45952. };
  45953. Lines2D.prototype.createModelRenderCache = function (modelKey) {
  45954. var renderCache = new Lines2DRenderCache(this.owner.engine, modelKey);
  45955. return renderCache;
  45956. };
  45957. ///////////////////////////////////////////////////////////////////////////////////
  45958. // Methods for Lines building
  45959. Lines2D.prototype._perp = function (v, res) {
  45960. res.x = v.y;
  45961. res.y = -v.x;
  45962. };
  45963. ;
  45964. Lines2D.prototype._direction = function (a, b, res) {
  45965. a.subtractToRef(b, res);
  45966. res.normalize();
  45967. };
  45968. Lines2D.prototype._computeMiter = function (tangent, miter, a, b) {
  45969. a.addToRef(b, tangent);
  45970. tangent.normalize();
  45971. miter.x = -tangent.y;
  45972. miter.y = tangent.x;
  45973. Lines2D._miterTps.x = -a.y;
  45974. Lines2D._miterTps.y = a.x;
  45975. return 1 / BABYLON.Vector2.Dot(miter, Lines2D._miterTps);
  45976. };
  45977. Lines2D.prototype._intersect = function (x1, y1, x2, y2, x3, y3, x4, y4) {
  45978. var d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  45979. if (d === 0)
  45980. return false;
  45981. var xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; // Intersection point is xi/yi, just in case...
  45982. //let yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; // That's why I left it commented
  45983. if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2))
  45984. return false;
  45985. if (xi < Math.min(x3, x4) || xi > Math.max(x3, x4))
  45986. return false;
  45987. return true;
  45988. };
  45989. Lines2D.prototype._updateMinMax = function (array, offset) {
  45990. if (offset >= array.length) {
  45991. return;
  45992. }
  45993. this._boundingMin.x = Math.min(this._boundingMin.x, array[offset]);
  45994. this._boundingMax.x = Math.max(this._boundingMax.x, array[offset]);
  45995. this._boundingMin.y = Math.min(this._boundingMin.y, array[offset + 1]);
  45996. this._boundingMax.y = Math.max(this._boundingMax.y, array[offset + 1]);
  45997. };
  45998. Lines2D.prototype._store = function (array, contour, index, max, p, n, halfThickness, borderThickness, detectFlip) {
  45999. var borderMode = borderThickness != null && !isNaN(borderThickness);
  46000. var off = index * (borderMode ? 8 : 4);
  46001. // 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)
  46002. if (off >= array.length) {
  46003. return;
  46004. }
  46005. // Store start/end normal, we need it for the cap construction
  46006. if (index === 0) {
  46007. this._perp(n, Lines2D._startDir);
  46008. }
  46009. else if (index === max - 1) {
  46010. this._perp(n, Lines2D._endDir);
  46011. Lines2D._endDir.x *= -1;
  46012. Lines2D._endDir.y *= -1;
  46013. }
  46014. var swap = false;
  46015. array[off + 0] = p.x + n.x * halfThickness;
  46016. array[off + 1] = p.y + n.y * halfThickness;
  46017. array[off + 2] = p.x + n.x * -halfThickness;
  46018. array[off + 3] = p.y + n.y * -halfThickness;
  46019. this._updateMinMax(array, off);
  46020. this._updateMinMax(array, off + 2);
  46021. // If an index is given we check if the two segments formed between [index+0;detectFlip+0] and [index+2;detectFlip+2] intersect themselves.
  46022. // 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
  46023. if (detectFlip !== undefined) {
  46024. // Flip if intersect
  46025. var flipOff = detectFlip * (borderMode ? 8 : 4);
  46026. 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])) {
  46027. swap = true;
  46028. var tps = array[off + 0];
  46029. array[off + 0] = array[off + 2];
  46030. array[off + 2] = tps;
  46031. tps = array[off + 1];
  46032. array[off + 1] = array[off + 3];
  46033. array[off + 3] = tps;
  46034. }
  46035. }
  46036. if (borderMode) {
  46037. var t = halfThickness + borderThickness;
  46038. array[off + 4] = p.x + n.x * (swap ? -t : t);
  46039. array[off + 5] = p.y + n.y * (swap ? -t : t);
  46040. array[off + 6] = p.x + n.x * (swap ? t : -t);
  46041. array[off + 7] = p.y + n.y * (swap ? t : -t);
  46042. this._updateMinMax(array, off + 4);
  46043. this._updateMinMax(array, off + 6);
  46044. }
  46045. if (contour) {
  46046. off += borderMode ? 4 : 0;
  46047. contour.push(new BABYLON.Vector2(array[off + 0], array[off + 1]));
  46048. contour.push(new BABYLON.Vector2(array[off + 2], array[off + 3]));
  46049. }
  46050. };
  46051. Lines2D.prototype._getCapSize = function (type, border) {
  46052. if (border === void 0) { border = false; }
  46053. var sd = Lines2D._roundCapSubDiv;
  46054. // If no array given, we call this to get the size
  46055. var vbsize = 0, ibsize = 0;
  46056. switch (type) {
  46057. case Lines2D.NoCap:
  46058. {
  46059. // If the line is not close and we're computing border, we add the size to generate the edge border
  46060. if (!this.closed && border) {
  46061. vbsize = 4;
  46062. ibsize = 6;
  46063. }
  46064. else {
  46065. vbsize = ibsize = 0;
  46066. }
  46067. break;
  46068. }
  46069. case Lines2D.RoundCap:
  46070. {
  46071. if (border) {
  46072. vbsize = sd;
  46073. ibsize = (sd - 2) * 3;
  46074. }
  46075. else {
  46076. vbsize = (sd / 2) + 1;
  46077. ibsize = (sd / 2) * 3;
  46078. }
  46079. break;
  46080. }
  46081. case Lines2D.ArrowCap:
  46082. {
  46083. if (border) {
  46084. vbsize = 12;
  46085. ibsize = 24;
  46086. }
  46087. else {
  46088. vbsize = 3;
  46089. ibsize = 3;
  46090. }
  46091. break;
  46092. }
  46093. case Lines2D.TriangleCap:
  46094. {
  46095. if (border) {
  46096. vbsize = 6;
  46097. ibsize = 12;
  46098. }
  46099. else {
  46100. vbsize = 3;
  46101. ibsize = 3;
  46102. }
  46103. break;
  46104. }
  46105. case Lines2D.DiamondAnchorCap:
  46106. {
  46107. if (border) {
  46108. vbsize = 10;
  46109. ibsize = 24;
  46110. }
  46111. else {
  46112. vbsize = 5;
  46113. ibsize = 9;
  46114. }
  46115. break;
  46116. }
  46117. case Lines2D.SquareAnchorCap:
  46118. {
  46119. if (border) {
  46120. vbsize = 12;
  46121. ibsize = 30;
  46122. }
  46123. else {
  46124. vbsize = 4;
  46125. ibsize = 6;
  46126. }
  46127. break;
  46128. }
  46129. case Lines2D.RoundAnchorCap:
  46130. {
  46131. if (border) {
  46132. vbsize = sd * 2;
  46133. ibsize = (sd - 1) * 6;
  46134. }
  46135. else {
  46136. vbsize = sd + 1;
  46137. ibsize = (sd + 1) * 3;
  46138. }
  46139. break;
  46140. }
  46141. }
  46142. return { vbsize: vbsize * 2, ibsize: ibsize };
  46143. };
  46144. Lines2D.prototype._storeVertex = function (vb, baseOffset, index, basePos, rotation, vertex, contour) {
  46145. var c = Math.cos(rotation);
  46146. var s = Math.sin(rotation);
  46147. Lines2D._tpsV.x = (c * vertex.x) + (-s * vertex.y) + basePos.x;
  46148. Lines2D._tpsV.y = (s * vertex.x) + (c * vertex.y) + basePos.y;
  46149. var offset = baseOffset + (index * 2);
  46150. vb[offset + 0] = Lines2D._tpsV.x;
  46151. vb[offset + 1] = Lines2D._tpsV.y;
  46152. if (contour) {
  46153. contour.push(Lines2D._tpsV.x);
  46154. contour.push(Lines2D._tpsV.y);
  46155. }
  46156. this._updateMinMax(vb, offset);
  46157. return (baseOffset + index * 2) / 2;
  46158. };
  46159. Lines2D.prototype._storeIndex = function (ib, baseOffset, index, vertexIndex) {
  46160. ib[baseOffset + index] = vertexIndex;
  46161. };
  46162. Lines2D.prototype._buildCap = function (vb, vbi, ib, ibi, pos, thickness, borderThickness, type, capDir, contour) {
  46163. // 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
  46164. var sd = Lines2D._roundCapSubDiv;
  46165. var dir = new BABYLON.Vector2(1, 0);
  46166. var angle = Math.atan2(capDir.y, capDir.x) - Math.atan2(dir.y, dir.x);
  46167. var ht = thickness / 2;
  46168. var t = thickness;
  46169. var borderMode = borderThickness != null;
  46170. var bt = borderThickness;
  46171. switch (type) {
  46172. case Lines2D.NoCap:
  46173. if (borderMode && !this.closed) {
  46174. var vi = 0;
  46175. var ii = 0;
  46176. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), contour);
  46177. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, ht + bt), contour);
  46178. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, -(ht + bt)), contour);
  46179. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), contour);
  46180. this._storeIndex(ib, ibi, ii++, v1);
  46181. this._storeIndex(ib, ibi, ii++, v2);
  46182. this._storeIndex(ib, ibi, ii++, v3);
  46183. this._storeIndex(ib, ibi, ii++, v1);
  46184. this._storeIndex(ib, ibi, ii++, v3);
  46185. this._storeIndex(ib, ibi, ii++, v4);
  46186. }
  46187. break;
  46188. case Lines2D.ArrowCap:
  46189. ht *= 2;
  46190. case Lines2D.TriangleCap:
  46191. {
  46192. if (borderMode) {
  46193. var f = type === Lines2D.TriangleCap ? bt : Math.sqrt(bt * bt * 2);
  46194. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), null);
  46195. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), null);
  46196. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), null);
  46197. var v4 = this._storeVertex(vb, vbi, 3, pos, angle, new BABYLON.Vector2(0, ht + f), contour);
  46198. var v5 = this._storeVertex(vb, vbi, 4, pos, angle, new BABYLON.Vector2(ht + f, 0), contour);
  46199. var v6 = this._storeVertex(vb, vbi, 5, pos, angle, new BABYLON.Vector2(0, -(ht + f)), contour);
  46200. var ii = 0;
  46201. this._storeIndex(ib, ibi, ii++, v1);
  46202. this._storeIndex(ib, ibi, ii++, v4);
  46203. this._storeIndex(ib, ibi, ii++, v5);
  46204. this._storeIndex(ib, ibi, ii++, v1);
  46205. this._storeIndex(ib, ibi, ii++, v5);
  46206. this._storeIndex(ib, ibi, ii++, v2);
  46207. this._storeIndex(ib, ibi, ii++, v6);
  46208. this._storeIndex(ib, ibi, ii++, v3);
  46209. this._storeIndex(ib, ibi, ii++, v2);
  46210. this._storeIndex(ib, ibi, ii++, v6);
  46211. this._storeIndex(ib, ibi, ii++, v2);
  46212. this._storeIndex(ib, ibi, ii++, v5);
  46213. if (type === Lines2D.ArrowCap) {
  46214. var rht = thickness / 2;
  46215. var v10 = this._storeVertex(vb, vbi, 9, pos, angle, new BABYLON.Vector2(0, -(rht + bt)), null);
  46216. var v12 = this._storeVertex(vb, vbi, 11, pos, angle, new BABYLON.Vector2(-bt, -(ht + f)), contour);
  46217. var v11 = this._storeVertex(vb, vbi, 10, pos, angle, new BABYLON.Vector2(-bt, -(rht + bt)), contour);
  46218. var v7 = this._storeVertex(vb, vbi, 6, pos, angle, new BABYLON.Vector2(0, rht + bt), null);
  46219. var v8 = this._storeVertex(vb, vbi, 7, pos, angle, new BABYLON.Vector2(-bt, rht + bt), contour);
  46220. var v9 = this._storeVertex(vb, vbi, 8, pos, angle, new BABYLON.Vector2(-bt, ht + f), contour);
  46221. this._storeIndex(ib, ibi, ii++, v7);
  46222. this._storeIndex(ib, ibi, ii++, v8);
  46223. this._storeIndex(ib, ibi, ii++, v9);
  46224. this._storeIndex(ib, ibi, ii++, v7);
  46225. this._storeIndex(ib, ibi, ii++, v9);
  46226. this._storeIndex(ib, ibi, ii++, v4);
  46227. this._storeIndex(ib, ibi, ii++, v10);
  46228. this._storeIndex(ib, ibi, ii++, v12);
  46229. this._storeIndex(ib, ibi, ii++, v11);
  46230. this._storeIndex(ib, ibi, ii++, v10);
  46231. this._storeIndex(ib, ibi, ii++, v6);
  46232. this._storeIndex(ib, ibi, ii++, v12);
  46233. }
  46234. }
  46235. else {
  46236. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), contour);
  46237. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), contour);
  46238. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), contour);
  46239. this._storeIndex(ib, ibi, 0, v1);
  46240. this._storeIndex(ib, ibi, 1, v2);
  46241. this._storeIndex(ib, ibi, 2, v3);
  46242. }
  46243. break;
  46244. }
  46245. case Lines2D.RoundCap:
  46246. {
  46247. if (borderMode) {
  46248. var curA = -Math.PI / 2;
  46249. var incA = Math.PI / (sd / 2 - 1);
  46250. var ii = 0;
  46251. for (var i = 0; i < (sd / 2); i++) {
  46252. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  46253. 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);
  46254. if (i > 0) {
  46255. this._storeIndex(ib, ibi, ii++, v1 - 2);
  46256. this._storeIndex(ib, ibi, ii++, v2 - 2);
  46257. this._storeIndex(ib, ibi, ii++, v2);
  46258. this._storeIndex(ib, ibi, ii++, v1 - 2);
  46259. this._storeIndex(ib, ibi, ii++, v2);
  46260. this._storeIndex(ib, ibi, ii++, v1);
  46261. }
  46262. curA += incA;
  46263. }
  46264. }
  46265. else {
  46266. var c = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, 0), null);
  46267. var curA = -Math.PI / 2;
  46268. var incA = Math.PI / (sd / 2 - 1);
  46269. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  46270. curA += incA;
  46271. for (var i = 1; i < (sd / 2); i++) {
  46272. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), contour);
  46273. this._storeIndex(ib, ibi, i * 3 + 0, c);
  46274. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  46275. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  46276. curA += incA;
  46277. }
  46278. }
  46279. break;
  46280. }
  46281. case Lines2D.SquareAnchorCap:
  46282. {
  46283. var vi = 0;
  46284. var c = borderMode ? null : contour;
  46285. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, t), c);
  46286. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, t), c);
  46287. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, -t), c);
  46288. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -t), c);
  46289. if (borderMode) {
  46290. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), null);
  46291. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, ht + bt), contour);
  46292. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, t + bt), contour);
  46293. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, t + bt), contour);
  46294. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, -(t + bt)), contour);
  46295. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(t + bt)), contour);
  46296. var v11 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(ht + bt)), contour);
  46297. var v12 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), null);
  46298. var ii = 0;
  46299. this._storeIndex(ib, ibi, ii++, v6);
  46300. this._storeIndex(ib, ibi, ii++, v1);
  46301. this._storeIndex(ib, ibi, ii++, v5);
  46302. this._storeIndex(ib, ibi, ii++, v6);
  46303. this._storeIndex(ib, ibi, ii++, v7);
  46304. this._storeIndex(ib, ibi, ii++, v1);
  46305. this._storeIndex(ib, ibi, ii++, v1);
  46306. this._storeIndex(ib, ibi, ii++, v7);
  46307. this._storeIndex(ib, ibi, ii++, v8);
  46308. this._storeIndex(ib, ibi, ii++, v1);
  46309. this._storeIndex(ib, ibi, ii++, v8);
  46310. this._storeIndex(ib, ibi, ii++, v2);
  46311. this._storeIndex(ib, ibi, ii++, v2);
  46312. this._storeIndex(ib, ibi, ii++, v8);
  46313. this._storeIndex(ib, ibi, ii++, v9);
  46314. this._storeIndex(ib, ibi, ii++, v2);
  46315. this._storeIndex(ib, ibi, ii++, v9);
  46316. this._storeIndex(ib, ibi, ii++, v3);
  46317. this._storeIndex(ib, ibi, ii++, v3);
  46318. this._storeIndex(ib, ibi, ii++, v9);
  46319. this._storeIndex(ib, ibi, ii++, v10);
  46320. this._storeIndex(ib, ibi, ii++, v3);
  46321. this._storeIndex(ib, ibi, ii++, v10);
  46322. this._storeIndex(ib, ibi, ii++, v4);
  46323. this._storeIndex(ib, ibi, ii++, v10);
  46324. this._storeIndex(ib, ibi, ii++, v11);
  46325. this._storeIndex(ib, ibi, ii++, v4);
  46326. this._storeIndex(ib, ibi, ii++, v11);
  46327. this._storeIndex(ib, ibi, ii++, v12);
  46328. this._storeIndex(ib, ibi, ii++, v4);
  46329. }
  46330. else {
  46331. this._storeIndex(ib, ibi, 0, v1);
  46332. this._storeIndex(ib, ibi, 1, v2);
  46333. this._storeIndex(ib, ibi, 2, v3);
  46334. this._storeIndex(ib, ibi, 3, v1);
  46335. this._storeIndex(ib, ibi, 4, v3);
  46336. this._storeIndex(ib, ibi, 5, v4);
  46337. }
  46338. break;
  46339. }
  46340. case Lines2D.RoundAnchorCap:
  46341. {
  46342. var cpos = Math.sqrt(t * t - ht * ht);
  46343. var center = new BABYLON.Vector2(cpos, 0);
  46344. var curA = BABYLON.Tools.ToRadians(-150);
  46345. var incA = BABYLON.Tools.ToRadians(300) / (sd - 1);
  46346. if (borderMode) {
  46347. var ii = 0;
  46348. for (var i = 0; i < sd; i++) {
  46349. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  46350. 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);
  46351. if (i > 0) {
  46352. this._storeIndex(ib, ibi, ii++, v1 - 2);
  46353. this._storeIndex(ib, ibi, ii++, v2 - 2);
  46354. this._storeIndex(ib, ibi, ii++, v2);
  46355. this._storeIndex(ib, ibi, ii++, v1 - 2);
  46356. this._storeIndex(ib, ibi, ii++, v2);
  46357. this._storeIndex(ib, ibi, ii++, v1);
  46358. }
  46359. curA += incA;
  46360. }
  46361. }
  46362. else {
  46363. var c = this._storeVertex(vb, vbi, 0, pos, angle, center, null);
  46364. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  46365. curA += incA;
  46366. for (var i = 1; i < sd; i++) {
  46367. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), contour);
  46368. this._storeIndex(ib, ibi, i * 3 + 0, c);
  46369. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  46370. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  46371. curA += incA;
  46372. }
  46373. this._storeIndex(ib, ibi, sd * 3 + 0, c);
  46374. this._storeIndex(ib, ibi, sd * 3 + 1, c + 1);
  46375. this._storeIndex(ib, ibi, sd * 3 + 2, c + sd);
  46376. }
  46377. break;
  46378. }
  46379. case Lines2D.DiamondAnchorCap:
  46380. {
  46381. var vi = 0;
  46382. var c = borderMode ? null : contour;
  46383. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht), c);
  46384. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t), c);
  46385. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3, 0), c);
  46386. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -t), c);
  46387. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -ht), c);
  46388. if (borderMode) {
  46389. var f = Math.sqrt(bt * bt * 2);
  46390. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, ht), contour);
  46391. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t + f), contour);
  46392. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3 + f, 0), contour);
  46393. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -(t + f)), contour);
  46394. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, -ht), contour);
  46395. var ii = 0;
  46396. this._storeIndex(ib, ibi, ii++, v6);
  46397. this._storeIndex(ib, ibi, ii++, v7);
  46398. this._storeIndex(ib, ibi, ii++, v1);
  46399. this._storeIndex(ib, ibi, ii++, v1);
  46400. this._storeIndex(ib, ibi, ii++, v7);
  46401. this._storeIndex(ib, ibi, ii++, v2);
  46402. this._storeIndex(ib, ibi, ii++, v2);
  46403. this._storeIndex(ib, ibi, ii++, v7);
  46404. this._storeIndex(ib, ibi, ii++, v8);
  46405. this._storeIndex(ib, ibi, ii++, v2);
  46406. this._storeIndex(ib, ibi, ii++, v8);
  46407. this._storeIndex(ib, ibi, ii++, v3);
  46408. this._storeIndex(ib, ibi, ii++, v3);
  46409. this._storeIndex(ib, ibi, ii++, v8);
  46410. this._storeIndex(ib, ibi, ii++, v9);
  46411. this._storeIndex(ib, ibi, ii++, v3);
  46412. this._storeIndex(ib, ibi, ii++, v9);
  46413. this._storeIndex(ib, ibi, ii++, v4);
  46414. this._storeIndex(ib, ibi, ii++, v4);
  46415. this._storeIndex(ib, ibi, ii++, v9);
  46416. this._storeIndex(ib, ibi, ii++, v10);
  46417. this._storeIndex(ib, ibi, ii++, v4);
  46418. this._storeIndex(ib, ibi, ii++, v10);
  46419. this._storeIndex(ib, ibi, ii++, v5);
  46420. }
  46421. else {
  46422. this._storeIndex(ib, ibi, 0, v1);
  46423. this._storeIndex(ib, ibi, 1, v2);
  46424. this._storeIndex(ib, ibi, 2, v3);
  46425. this._storeIndex(ib, ibi, 3, v1);
  46426. this._storeIndex(ib, ibi, 4, v3);
  46427. this._storeIndex(ib, ibi, 5, v5);
  46428. this._storeIndex(ib, ibi, 6, v5);
  46429. this._storeIndex(ib, ibi, 7, v3);
  46430. this._storeIndex(ib, ibi, 8, v4);
  46431. }
  46432. break;
  46433. }
  46434. }
  46435. return null;
  46436. };
  46437. Lines2D.prototype._buildLine = function (vb, contour, ht, bt) {
  46438. var lineA = BABYLON.Vector2.Zero();
  46439. var lineB = BABYLON.Vector2.Zero();
  46440. var tangent = BABYLON.Vector2.Zero();
  46441. var miter = BABYLON.Vector2.Zero();
  46442. var curNormal = null;
  46443. if (this.closed) {
  46444. this.points.push(this.points[0]);
  46445. }
  46446. var total = this.points.length;
  46447. for (var i = 1; i < total; i++) {
  46448. var last = this.points[i - 1];
  46449. var cur = this.points[i];
  46450. var next = (i < (this.points.length - 1)) ? this.points[i + 1] : null;
  46451. this._direction(cur, last, lineA);
  46452. if (!curNormal) {
  46453. curNormal = BABYLON.Vector2.Zero();
  46454. this._perp(lineA, curNormal);
  46455. }
  46456. if (i === 1) {
  46457. this._store(vb, contour, 0, total, this.points[0], curNormal, ht, bt);
  46458. }
  46459. if (!next) {
  46460. this._perp(lineA, curNormal);
  46461. this._store(vb, contour, i, total, this.points[i], curNormal, ht, bt, i - 1);
  46462. }
  46463. else {
  46464. this._direction(next, cur, lineB);
  46465. var miterLen = this._computeMiter(tangent, miter, lineA, lineB);
  46466. this._store(vb, contour, i, total, this.points[i], miter, miterLen * ht, miterLen * bt, i - 1);
  46467. }
  46468. }
  46469. if (this.points.length > 2 && this.closed) {
  46470. var last2 = this.points[total - 2];
  46471. var cur2 = this.points[0];
  46472. var next2 = this.points[1];
  46473. this._direction(cur2, last2, lineA);
  46474. this._direction(next2, cur2, lineB);
  46475. this._perp(lineA, curNormal);
  46476. var miterLen2 = this._computeMiter(tangent, miter, lineA, lineB);
  46477. this._store(vb, null, 0, total, this.points[0], miter, miterLen2 * ht, miterLen2 * bt, 1);
  46478. // Patch contour
  46479. if (contour) {
  46480. var off = (bt == null) ? 0 : 4;
  46481. contour[0].x = vb[off + 0];
  46482. contour[0].y = vb[off + 1];
  46483. contour[1].x = vb[off + 2];
  46484. contour[1].y = vb[off + 3];
  46485. }
  46486. }
  46487. // Remove the point we added at the beginning
  46488. if (this.closed) {
  46489. this.points.splice(total - 1);
  46490. }
  46491. };
  46492. // Methods for Lines building
  46493. ///////////////////////////////////////////////////////////////////////////////////
  46494. Lines2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  46495. var renderCache = modelRenderCache;
  46496. var engine = this.owner.engine;
  46497. if (this._fillVB === null) {
  46498. this._computeLines2D();
  46499. }
  46500. // Need to create WebGL resources for fill part?
  46501. if (this.fill) {
  46502. renderCache.fillVB = engine.createVertexBuffer(this._fillVB);
  46503. renderCache.fillIB = engine.createIndexBuffer(this._fillIB);
  46504. renderCache.fillIndicesCount = this._fillIB.length;
  46505. // 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
  46506. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], true);
  46507. if (ei) {
  46508. renderCache.effectFillInstanced = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  46509. }
  46510. // Get the non instanced version
  46511. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], false);
  46512. renderCache.effectFill = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  46513. }
  46514. // Need to create WebGL resources for border part?
  46515. if (this.border) {
  46516. renderCache.borderVB = engine.createVertexBuffer(this._borderVB);
  46517. renderCache.borderIB = engine.createIndexBuffer(this._borderIB);
  46518. renderCache.borderIndicesCount = this._borderIB.length;
  46519. // 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
  46520. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], true);
  46521. if (ei) {
  46522. renderCache.effectBorderInstanced = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  46523. }
  46524. // Get the non instanced version
  46525. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], false);
  46526. renderCache.effectBorder = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  46527. }
  46528. this._fillVB = null;
  46529. this._fillIB = null;
  46530. this._borderVB = null;
  46531. this._borderIB = null;
  46532. return renderCache;
  46533. };
  46534. Lines2D.prototype._computeLines2D = function () {
  46535. // Init min/max because their being computed here
  46536. this._boundingMin = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  46537. this._boundingMax = new BABYLON.Vector2(Number.MIN_VALUE, Number.MIN_VALUE);
  46538. var contour = new Array();
  46539. var startCapContour = new Array();
  46540. var endCapContour = new Array();
  46541. // Need to create WebGL resources for fill part?
  46542. if (this.fill) {
  46543. var startCapInfo = this._getCapSize(this.startCap);
  46544. var endCapInfo = this._getCapSize(this.endCap);
  46545. var count = this.points.length;
  46546. var vbSize = (count * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  46547. this._fillVB = new Float32Array(vbSize);
  46548. var vb = this._fillVB;
  46549. var ht = this.fillThickness / 2;
  46550. var total = this.points.length;
  46551. this._buildLine(vb, this.border ? null : contour, ht);
  46552. var max = total * 2;
  46553. var triCount = (count - (this.closed ? 0 : 1)) * 2;
  46554. this._fillIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  46555. var ib = this._fillIB;
  46556. for (var i = 0; i < triCount; i += 2) {
  46557. ib[i * 3 + 0] = i + 0;
  46558. ib[i * 3 + 1] = i + 1;
  46559. ib[i * 3 + 2] = (i + 2) % max;
  46560. ib[i * 3 + 3] = i + 1;
  46561. ib[i * 3 + 4] = (i + 3) % max;
  46562. ib[i * 3 + 5] = (i + 2) % max;
  46563. }
  46564. this._buildCap(vb, count * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, null, this.startCap, Lines2D._startDir, this.border ? null : startCapContour);
  46565. 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);
  46566. }
  46567. // Need to create WebGL resources for border part?
  46568. if (this.border) {
  46569. var startCapInfo = this._getCapSize(this.startCap, true);
  46570. var endCapInfo = this._getCapSize(this.endCap, true);
  46571. var count = this.points.length;
  46572. var vbSize = (count * 2 * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  46573. this._borderVB = new Float32Array(vbSize);
  46574. var vb = this._borderVB;
  46575. var ht = this.fillThickness / 2;
  46576. var bt = this.borderThickness;
  46577. var total = this.points.length;
  46578. this._buildLine(vb, contour, ht, bt);
  46579. var max = total * 2 * 2;
  46580. var triCount = (count - (this.closed ? 0 : 1)) * 2 * 2;
  46581. this._borderIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  46582. var ib = this._borderIB;
  46583. for (var i = 0; i < triCount; i += 4) {
  46584. ib[i * 3 + 0] = i + 0;
  46585. ib[i * 3 + 1] = i + 2;
  46586. ib[i * 3 + 2] = (i + 6) % max;
  46587. ib[i * 3 + 3] = i + 0;
  46588. ib[i * 3 + 4] = (i + 6) % max;
  46589. ib[i * 3 + 5] = (i + 4) % max;
  46590. ib[i * 3 + 6] = i + 3;
  46591. ib[i * 3 + 7] = i + 1;
  46592. ib[i * 3 + 8] = (i + 5) % max;
  46593. ib[i * 3 + 9] = i + 3;
  46594. ib[i * 3 + 10] = (i + 5) % max;
  46595. ib[i * 3 + 11] = (i + 7) % max;
  46596. }
  46597. this._buildCap(vb, count * 2 * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, this.borderThickness, this.startCap, Lines2D._startDir, startCapContour);
  46598. 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);
  46599. }
  46600. this._contour = contour;
  46601. if (startCapContour.length > 0) {
  46602. var startCapTri = Earcut.earcut(startCapContour, null, 2);
  46603. this._startCapTriIndices = startCapTri;
  46604. this._startCapContour = startCapContour;
  46605. }
  46606. else {
  46607. this._startCapTriIndices = null;
  46608. this._startCapContour = null;
  46609. }
  46610. if (endCapContour.length > 0) {
  46611. var endCapTri = Earcut.earcut(endCapContour, null, 2);
  46612. this._endCapContour = endCapContour;
  46613. this._endCapTriIndices = endCapTri;
  46614. }
  46615. else {
  46616. this._endCapContour = null;
  46617. this._endCapTriIndices = null;
  46618. }
  46619. var bs = this._boundingMax.subtract(this._boundingMin);
  46620. this._size.width = bs.x;
  46621. this._size.height = bs.y;
  46622. };
  46623. Object.defineProperty(Lines2D.prototype, "size", {
  46624. get: function () {
  46625. if (this._size == null) {
  46626. this._computeLines2D();
  46627. }
  46628. return this._size;
  46629. },
  46630. enumerable: true,
  46631. configurable: true
  46632. });
  46633. Lines2D.prototype.createInstanceDataParts = function () {
  46634. var res = new Array();
  46635. if (this.border) {
  46636. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  46637. }
  46638. if (this.fill) {
  46639. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  46640. }
  46641. return res;
  46642. };
  46643. Lines2D.prototype.refreshInstanceDataPart = function (part) {
  46644. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  46645. return false;
  46646. }
  46647. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  46648. var d = part;
  46649. if (this.border instanceof BABYLON.GradientColorBrush2D) {
  46650. d.boundingMin = this.boundingMin;
  46651. d.boundingMax = this.boundingMax;
  46652. }
  46653. }
  46654. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  46655. var d = part;
  46656. if (this.fill instanceof BABYLON.GradientColorBrush2D) {
  46657. d.boundingMin = this.boundingMin;
  46658. d.boundingMax = this.boundingMax;
  46659. }
  46660. }
  46661. return true;
  46662. };
  46663. Lines2D._prevA = BABYLON.Vector2.Zero();
  46664. Lines2D._prevB = BABYLON.Vector2.Zero();
  46665. Lines2D._curA = BABYLON.Vector2.Zero();
  46666. Lines2D._curB = BABYLON.Vector2.Zero();
  46667. Lines2D._miterTps = BABYLON.Vector2.Zero();
  46668. Lines2D._startDir = BABYLON.Vector2.Zero();
  46669. Lines2D._endDir = BABYLON.Vector2.Zero();
  46670. Lines2D._tpsV = BABYLON.Vector2.Zero();
  46671. Lines2D._noCap = 0;
  46672. Lines2D._roundCap = 1;
  46673. Lines2D._triangleCap = 2;
  46674. Lines2D._squareAnchorCap = 3;
  46675. Lines2D._roundAnchorCap = 4;
  46676. Lines2D._diamondAnchorCap = 5;
  46677. Lines2D._arrowCap = 6;
  46678. Lines2D._roundCapSubDiv = 36;
  46679. __decorate([
  46680. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Lines2D.pointsProperty = pi; })
  46681. ], Lines2D.prototype, "points", null);
  46682. __decorate([
  46683. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Lines2D.fillThicknessProperty = pi; })
  46684. ], Lines2D.prototype, "fillThickness", null);
  46685. __decorate([
  46686. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Lines2D.closedProperty = pi; })
  46687. ], Lines2D.prototype, "closed", null);
  46688. __decorate([
  46689. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 4, function (pi) { return Lines2D.startCapProperty = pi; })
  46690. ], Lines2D.prototype, "startCap", null);
  46691. __decorate([
  46692. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 5, function (pi) { return Lines2D.endCapProperty = pi; })
  46693. ], Lines2D.prototype, "endCap", null);
  46694. Lines2D = __decorate([
  46695. BABYLON.className("Lines2D")
  46696. ], Lines2D);
  46697. return Lines2D;
  46698. })(BABYLON.Shape2D);
  46699. BABYLON.Lines2D = Lines2D;
  46700. })(BABYLON || (BABYLON = {}));
  46701. var BABYLON;
  46702. (function (BABYLON) {
  46703. // This class contains data that lifetime is bounding to the Babylon Engine object
  46704. var Canvas2DEngineBoundData = (function () {
  46705. function Canvas2DEngineBoundData() {
  46706. this._modelCache = new BABYLON.StringDictionary();
  46707. }
  46708. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  46709. return this._modelCache.getOrAddWithFactory(key, factory);
  46710. };
  46711. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  46712. if (!modelRenderCache.isDisposed) {
  46713. return false;
  46714. }
  46715. this._modelCache.remove(modelRenderCache.modelKey);
  46716. return true;
  46717. };
  46718. return Canvas2DEngineBoundData;
  46719. })();
  46720. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  46721. var Canvas2D = (function (_super) {
  46722. __extends(Canvas2D, _super);
  46723. function Canvas2D(scene, settings) {
  46724. var _this = this;
  46725. _super.call(this, settings);
  46726. /**
  46727. * 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.
  46728. * Beware that you have to take under consideration the origin in your calculations! Good luck!
  46729. */
  46730. this.worldSpaceToNodeLocal = function (worldPos) {
  46731. var node = _this._worldSpaceNode;
  46732. if (!node) {
  46733. return;
  46734. }
  46735. var mtx = node.getWorldMatrix().clone();
  46736. mtx.invert();
  46737. var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
  46738. var res = new BABYLON.Vector2(v.x, v.y);
  46739. var size = _this.actualSize;
  46740. res.x += size.width * 0.5; // res is centered, make it relative to bottom/left
  46741. res.y += size.height * 0.5;
  46742. return res;
  46743. };
  46744. /**
  46745. * 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
  46746. */
  46747. this.worldSpaceCacheChanged = function () {
  46748. var plane = _this.worldSpaceCanvasNode;
  46749. var vd = BABYLON.VertexData.ExtractFromMesh(plane); //new VertexData();
  46750. vd.uvs = new Float32Array(8);
  46751. var material = plane.material;
  46752. var tex = _this._renderableData._cacheTexture;
  46753. if (material.diffuseTexture !== tex) {
  46754. material.diffuseTexture = tex;
  46755. tex.hasAlpha = true;
  46756. }
  46757. var nodeuv = _this._renderableData._cacheNodeUVs;
  46758. for (var i = 0; i < 4; i++) {
  46759. vd.uvs[i * 2 + 0] = nodeuv[i].x;
  46760. vd.uvs[i * 2 + 1] = nodeuv[i].y;
  46761. }
  46762. vd.applyToMesh(plane);
  46763. };
  46764. this._notifDebugMode = false;
  46765. this._mapCounter = 0;
  46766. this._drawCallsOpaqueCounter = new BABYLON.PerfCounter();
  46767. this._drawCallsAlphaTestCounter = new BABYLON.PerfCounter();
  46768. this._drawCallsTransparentCounter = new BABYLON.PerfCounter();
  46769. this._groupRenderCounter = new BABYLON.PerfCounter();
  46770. this._updateTransparentDataCounter = new BABYLON.PerfCounter();
  46771. this._cachedGroupRenderCounter = new BABYLON.PerfCounter();
  46772. this._updateCachedStateCounter = new BABYLON.PerfCounter();
  46773. this._updateLayoutCounter = new BABYLON.PerfCounter();
  46774. this._updatePositioningCounter = new BABYLON.PerfCounter();
  46775. this._updateLocalTransformCounter = new BABYLON.PerfCounter();
  46776. this._updateGlobalTransformCounter = new BABYLON.PerfCounter();
  46777. this._boundingInfoRecomputeCounter = new BABYLON.PerfCounter();
  46778. this._profileInfoText = null;
  46779. BABYLON.Prim2DBase._isCanvasInit = false;
  46780. if (!settings) {
  46781. settings = {};
  46782. }
  46783. if (this._cachingStrategy !== Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  46784. this._background = new BABYLON.Rectangle2D({ parent: this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
  46785. this._background.zOrder = 1.0;
  46786. this._background.isPickable = false;
  46787. this._background.origin = BABYLON.Vector2.Zero();
  46788. this._background.levelVisible = false;
  46789. if (settings.backgroundRoundRadius != null) {
  46790. this.backgroundRoundRadius = settings.backgroundRoundRadius;
  46791. }
  46792. if (settings.backgroundBorder != null) {
  46793. if (typeof (settings.backgroundBorder) === "string") {
  46794. this.backgroundBorder = Canvas2D.GetBrushFromString(settings.backgroundBorder);
  46795. }
  46796. else {
  46797. this.backgroundBorder = settings.backgroundBorder;
  46798. }
  46799. }
  46800. if (settings.backgroundBorderThickNess != null) {
  46801. this.backgroundBorderThickness = settings.backgroundBorderThickNess;
  46802. }
  46803. if (settings.backgroundFill != null) {
  46804. if (typeof (settings.backgroundFill) === "string") {
  46805. this.backgroundFill = Canvas2D.GetBrushFromString(settings.backgroundFill);
  46806. }
  46807. else {
  46808. this.backgroundFill = settings.backgroundFill;
  46809. }
  46810. }
  46811. this._background._patchHierarchy(this);
  46812. }
  46813. var engine = scene.getEngine();
  46814. this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  46815. this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  46816. this._capturedPointers = new BABYLON.StringDictionary();
  46817. this._pickStartingPosition = BABYLON.Vector2.Zero();
  46818. this._hierarchyLevelMaxSiblingCount = 50;
  46819. this._hierarchyDepth = 0;
  46820. this._zOrder = 0;
  46821. this._zMax = 1;
  46822. this._scene = scene;
  46823. this._engine = engine;
  46824. this._renderingSize = new BABYLON.Size(0, 0);
  46825. this._trackedGroups = new Array();
  46826. this._maxAdaptiveWorldSpaceCanvasSize = null;
  46827. this._groupCacheMaps = new BABYLON.StringDictionary();
  46828. this._patchHierarchy(this);
  46829. var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
  46830. this._fitRenderingDevice = !settings.size;
  46831. if (!settings.size) {
  46832. settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  46833. }
  46834. // Register scene dispose to also dispose the canvas when it'll happens
  46835. scene.onDisposeObservable.add(function (d, s) {
  46836. _this.dispose();
  46837. });
  46838. if (this._isScreenSpace) {
  46839. this._afterRenderObserver = this._scene.onAfterRenderObservable.add(function (d, s) {
  46840. _this._engine.clear(null, false, true, true);
  46841. _this._render();
  46842. });
  46843. }
  46844. else {
  46845. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function (d, s) {
  46846. _this._render();
  46847. });
  46848. }
  46849. this._supprtInstancedArray = this._engine.getCaps().instancedArrays !== null;
  46850. //this._supprtInstancedArray = false; // TODO REMOVE!!!
  46851. this._setupInteraction(enableInteraction);
  46852. }
  46853. Object.defineProperty(Canvas2D.prototype, "drawCallsOpaqueCounter", {
  46854. get: function () {
  46855. return this._drawCallsOpaqueCounter;
  46856. },
  46857. enumerable: true,
  46858. configurable: true
  46859. });
  46860. Object.defineProperty(Canvas2D.prototype, "drawCallsAlphaTestCounter", {
  46861. get: function () {
  46862. return this._drawCallsAlphaTestCounter;
  46863. },
  46864. enumerable: true,
  46865. configurable: true
  46866. });
  46867. Object.defineProperty(Canvas2D.prototype, "drawCallsTransparentCounter", {
  46868. get: function () {
  46869. return this._drawCallsTransparentCounter;
  46870. },
  46871. enumerable: true,
  46872. configurable: true
  46873. });
  46874. Object.defineProperty(Canvas2D.prototype, "groupRenderCounter", {
  46875. get: function () {
  46876. return this._groupRenderCounter;
  46877. },
  46878. enumerable: true,
  46879. configurable: true
  46880. });
  46881. Object.defineProperty(Canvas2D.prototype, "updateTransparentDataCounter", {
  46882. get: function () {
  46883. return this._updateTransparentDataCounter;
  46884. },
  46885. enumerable: true,
  46886. configurable: true
  46887. });
  46888. Object.defineProperty(Canvas2D.prototype, "cachedGroupRenderCounter", {
  46889. get: function () {
  46890. return this._cachedGroupRenderCounter;
  46891. },
  46892. enumerable: true,
  46893. configurable: true
  46894. });
  46895. Object.defineProperty(Canvas2D.prototype, "updateCachedStateCounter", {
  46896. get: function () {
  46897. return this._updateCachedStateCounter;
  46898. },
  46899. enumerable: true,
  46900. configurable: true
  46901. });
  46902. Object.defineProperty(Canvas2D.prototype, "updateLayoutCounter", {
  46903. get: function () {
  46904. return this._updateLayoutCounter;
  46905. },
  46906. enumerable: true,
  46907. configurable: true
  46908. });
  46909. Object.defineProperty(Canvas2D.prototype, "updatePositioningCounter", {
  46910. get: function () {
  46911. return this._updatePositioningCounter;
  46912. },
  46913. enumerable: true,
  46914. configurable: true
  46915. });
  46916. Object.defineProperty(Canvas2D.prototype, "updateLocalTransformCounter", {
  46917. get: function () {
  46918. return this._updateLocalTransformCounter;
  46919. },
  46920. enumerable: true,
  46921. configurable: true
  46922. });
  46923. Object.defineProperty(Canvas2D.prototype, "updateGlobalTransformCounter", {
  46924. get: function () {
  46925. return this._updateGlobalTransformCounter;
  46926. },
  46927. enumerable: true,
  46928. configurable: true
  46929. });
  46930. Object.defineProperty(Canvas2D.prototype, "boundingInfoRecomputeCounter", {
  46931. get: function () {
  46932. return this._boundingInfoRecomputeCounter;
  46933. },
  46934. enumerable: true,
  46935. configurable: true
  46936. });
  46937. Canvas2D.prototype._canvasPreInit = function (settings) {
  46938. var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
  46939. this._cachingStrategy = cachingStrategy;
  46940. this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
  46941. };
  46942. Canvas2D.prototype._setupInteraction = function (enable) {
  46943. var _this = this;
  46944. // No change detection
  46945. if (enable === this._interactionEnabled) {
  46946. return;
  46947. }
  46948. // Set the new state
  46949. this._interactionEnabled = enable;
  46950. // ScreenSpace mode
  46951. if (this._isScreenSpace) {
  46952. // Disable interaction
  46953. if (!enable) {
  46954. if (this._scenePrePointerObserver) {
  46955. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  46956. this._scenePrePointerObserver = null;
  46957. }
  46958. return;
  46959. }
  46960. // Enable Interaction
  46961. // Register the observable
  46962. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  46963. var hs = 1 / _this.engine.getHardwareScalingLevel();
  46964. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  46965. _this._handlePointerEventForInteraction(e, localPos, s);
  46966. });
  46967. }
  46968. else {
  46969. var scene = this.scene;
  46970. if (enable) {
  46971. scene.constantlyUpdateMeshUnderPointer = true;
  46972. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  46973. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  46974. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  46975. _this._handlePointerEventForInteraction(e, localPos, s);
  46976. }
  46977. });
  46978. }
  46979. else {
  46980. if (this._scenePointerObserver) {
  46981. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  46982. this._scenePointerObserver = null;
  46983. }
  46984. }
  46985. }
  46986. };
  46987. /**
  46988. * Internal method, you should use the Prim2DBase version instead
  46989. */
  46990. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  46991. if (this.isPointerCaptured(pointerId)) {
  46992. return false;
  46993. }
  46994. // Try to capture the pointer on the HTML side
  46995. try {
  46996. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  46997. }
  46998. catch (e) {
  46999. }
  47000. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  47001. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  47002. this._capturedPointers.add(pointerId.toString(), primitive);
  47003. return true;
  47004. };
  47005. /**
  47006. * Internal method, you should use the Prim2DBase version instead
  47007. */
  47008. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  47009. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  47010. return false;
  47011. }
  47012. // Try to release the pointer on the HTML side
  47013. try {
  47014. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  47015. }
  47016. catch (e) {
  47017. }
  47018. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  47019. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  47020. this._capturedPointers.remove(pointerId.toString());
  47021. return true;
  47022. };
  47023. /**
  47024. * Determine if the given pointer is captured or not
  47025. * @param pointerId the Id of the pointer
  47026. * @return true if it's captured, false otherwise
  47027. */
  47028. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  47029. return this._capturedPointers.contains(pointerId.toString());
  47030. };
  47031. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  47032. // Avoid unnecessary lookup
  47033. if (this._capturedPointers.count === 0) {
  47034. return null;
  47035. }
  47036. return this._capturedPointers.get(pointerId.toString());
  47037. };
  47038. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  47039. // Dispose check
  47040. if (this.isDisposed) {
  47041. return;
  47042. }
  47043. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  47044. this._updatePointerInfo(eventData, localPosition);
  47045. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  47046. // 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.
  47047. // 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.
  47048. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, capturedPrim !== null);
  47049. // 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
  47050. this._updateOverStatus();
  47051. // Check if we have nothing to raise
  47052. if (!this._actualOverPrimitive && !capturedPrim) {
  47053. return;
  47054. }
  47055. // Update the relatedTarget info with the over primitive or the captured one (if any)
  47056. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  47057. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  47058. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  47059. // Analyze the pointer event type and fire proper events on the primitive
  47060. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  47061. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData.event);
  47062. }
  47063. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47064. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData.event);
  47065. }
  47066. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  47067. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData.event);
  47068. }
  47069. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  47070. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData.event);
  47071. }
  47072. };
  47073. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  47074. var pii = this._primPointerInfo;
  47075. if (!pii.canvasPointerPos) {
  47076. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  47077. }
  47078. var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
  47079. var engine = this._scene.getEngine();
  47080. if (this._isScreenSpace) {
  47081. var cameraViewport = camera.viewport;
  47082. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  47083. // Moving coordinates to local viewport world
  47084. var x = localPosition.x - viewport.x;
  47085. var y = localPosition.y - viewport.y;
  47086. pii.canvasPointerPos.x = x - this.actualPosition.x;
  47087. pii.canvasPointerPos.y = engine.getRenderHeight() - y - this.actualPosition.y;
  47088. }
  47089. else {
  47090. pii.canvasPointerPos.x = localPosition.x;
  47091. pii.canvasPointerPos.y = localPosition.y;
  47092. }
  47093. pii.mouseWheelDelta = 0;
  47094. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  47095. var event = eventData.event;
  47096. if (event.wheelDelta) {
  47097. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  47098. }
  47099. else if (event.detail) {
  47100. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  47101. }
  47102. }
  47103. else {
  47104. var pe = eventData.event;
  47105. pii.ctrlKey = pe.ctrlKey;
  47106. pii.altKey = pe.altKey;
  47107. pii.shiftKey = pe.shiftKey;
  47108. pii.metaKey = pe.metaKey;
  47109. pii.button = pe.button;
  47110. pii.buttons = pe.buttons;
  47111. pii.pointerId = pe.pointerId;
  47112. pii.width = pe.width;
  47113. pii.height = pe.height;
  47114. pii.presssure = pe.pressure;
  47115. pii.tilt.x = pe.tiltX;
  47116. pii.tilt.y = pe.tiltY;
  47117. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  47118. }
  47119. };
  47120. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture) {
  47121. if (this.scene.getRenderId() === this._intersectionRenderId) {
  47122. return;
  47123. }
  47124. // 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
  47125. if (!this._globalTransform) {
  47126. this.updateCachedStates(true);
  47127. }
  47128. var ii = Canvas2D._interInfo;
  47129. ii.pickPosition.x = mouseLocalPos.x;
  47130. ii.pickPosition.y = mouseLocalPos.y;
  47131. ii.findFirstOnly = false;
  47132. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  47133. if (!isCapture && !this.levelBoundingInfo.doesIntersect(ii.pickPosition)) {
  47134. this._previousIntersectionList = this._actualIntersectionList;
  47135. this._actualIntersectionList = null;
  47136. this._previousOverPrimitive = this._actualOverPrimitive;
  47137. this._actualOverPrimitive = null;
  47138. return;
  47139. }
  47140. this.intersect(ii);
  47141. this._previousIntersectionList = this._actualIntersectionList;
  47142. this._actualIntersectionList = ii.intersectedPrimitives;
  47143. this._previousOverPrimitive = this._actualOverPrimitive;
  47144. this._actualOverPrimitive = ii.topMostIntersectedPrimitive;
  47145. this._intersectionRenderId = this.scene.getRenderId();
  47146. };
  47147. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  47148. Canvas2D.prototype._updateOverStatus = function () {
  47149. if ((this.scene.getRenderId() === this._hoverStatusRenderId) || !this._previousIntersectionList || !this._actualIntersectionList) {
  47150. return;
  47151. }
  47152. // Detect a change of over
  47153. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  47154. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  47155. if (prevPrim !== actualPrim) {
  47156. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  47157. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  47158. // Notify the previous "over" prim that the pointer is no longer over it
  47159. if ((capturedPrim && capturedPrim === prevPrim) || (!capturedPrim && prevPrim)) {
  47160. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  47161. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  47162. }
  47163. // Notify the new "over" prim that the pointer is over it
  47164. if ((capturedPrim && capturedPrim === actualPrim) || (!capturedPrim && actualPrim)) {
  47165. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  47166. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  47167. }
  47168. }
  47169. this._hoverStatusRenderId = this.scene.getRenderId();
  47170. };
  47171. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  47172. if (this._primPointerInfo.isCaptured) {
  47173. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  47174. }
  47175. else {
  47176. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  47177. var pii = _a[_i];
  47178. if (pii.prim === prim) {
  47179. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  47180. return;
  47181. }
  47182. }
  47183. }
  47184. };
  47185. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  47186. if (!this._notifDebugMode) {
  47187. return;
  47188. }
  47189. var debug = "";
  47190. for (var i = 0; i < prim.hierarchyDepth; i++) {
  47191. debug += " ";
  47192. }
  47193. var pii = this._primPointerInfo;
  47194. 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();
  47195. console.log(debug);
  47196. };
  47197. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  47198. var ppi = this._primPointerInfo;
  47199. // In case of PointerOver/Out we will first notify the parent with PointerEnter/Leave
  47200. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) !== 0) {
  47201. this._notifParents(prim, mask);
  47202. }
  47203. var bubbleCancelled = false;
  47204. var cur = prim;
  47205. while (cur) {
  47206. // Only trigger the observers if the primitive is intersected (except for out)
  47207. if (!bubbleCancelled) {
  47208. this._updatePrimPointerPos(cur);
  47209. // Exec the observers
  47210. this._debugExecObserver(cur, mask);
  47211. cur._pointerEventObservable.notifyObservers(ppi, mask);
  47212. this._triggerActionManager(cur, ppi, mask, eventData);
  47213. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  47214. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  47215. if (ppi.cancelBubble) {
  47216. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) === 0) {
  47217. return;
  47218. }
  47219. // We're dealing with PointerOver/Out, let's keep looping to fire PointerEnter/Leave, but not Over/Out anymore
  47220. bubbleCancelled = true;
  47221. }
  47222. }
  47223. // If bubble is cancel we didn't update the Primitive Pointer Pos yet, let's do it
  47224. if (bubbleCancelled) {
  47225. this._updatePrimPointerPos(cur);
  47226. }
  47227. // Trigger a PointerEnter corresponding to the PointerOver
  47228. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  47229. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerEnter);
  47230. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  47231. }
  47232. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  47233. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerLeave);
  47234. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  47235. }
  47236. // Loop to the parent
  47237. cur = cur.parent;
  47238. }
  47239. };
  47240. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  47241. var _this = this;
  47242. // 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
  47243. if (!this._globalTransform) {
  47244. this.updateCachedStates(true);
  47245. }
  47246. // Process Trigger related to PointerDown
  47247. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  47248. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  47249. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  47250. this._pickStartingTime = new Date().getTime();
  47251. this._pickedDownPrim = null;
  47252. if (prim.actionManager) {
  47253. this._pickedDownPrim = prim;
  47254. if (prim.actionManager.hasPickTriggers) {
  47255. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  47256. switch (eventData.button) {
  47257. case 0:
  47258. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  47259. break;
  47260. case 1:
  47261. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  47262. break;
  47263. case 2:
  47264. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  47265. break;
  47266. }
  47267. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  47268. }
  47269. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  47270. window.setTimeout(function () {
  47271. var ppi = _this._primPointerInfo;
  47272. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  47273. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null);
  47274. var ii = new BABYLON.IntersectInfo2D();
  47275. ii.pickPosition = ppi.canvasPointerPos.clone();
  47276. ii.findFirstOnly = false;
  47277. _this.intersect(ii);
  47278. if (ii.isPrimIntersected(prim) !== null) {
  47279. if (prim.actionManager) {
  47280. 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)) {
  47281. _this._pickStartingTime = 0;
  47282. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  47283. }
  47284. }
  47285. }
  47286. }, BABYLON.ActionManager.LongPressDelay);
  47287. }
  47288. }
  47289. }
  47290. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  47291. this._pickStartingTime = 0;
  47292. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  47293. if (prim.actionManager) {
  47294. // OnPickUpTrigger
  47295. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  47296. // OnPickTrigger
  47297. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  47298. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  47299. }
  47300. }
  47301. // OnPickOutTrigger
  47302. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  47303. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  47304. }
  47305. }
  47306. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  47307. if (prim.actionManager) {
  47308. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  47309. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  47310. }
  47311. }
  47312. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  47313. if (prim.actionManager) {
  47314. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  47315. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  47316. }
  47317. }
  47318. };
  47319. Canvas2D.prototype._notifParents = function (prim, mask) {
  47320. var pii = this._primPointerInfo;
  47321. var curPrim = this;
  47322. while (curPrim) {
  47323. this._updatePrimPointerPos(curPrim);
  47324. // Fire the proper notification
  47325. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  47326. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerEnter);
  47327. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerEnter);
  47328. }
  47329. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  47330. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerLeave);
  47331. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerLeave);
  47332. }
  47333. curPrim = curPrim.parent;
  47334. }
  47335. };
  47336. /**
  47337. * Don't forget to call the dispose method when you're done with the Canvas instance.
  47338. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  47339. */
  47340. Canvas2D.prototype.dispose = function () {
  47341. if (!_super.prototype.dispose.call(this)) {
  47342. return false;
  47343. }
  47344. if (this._profilingCanvas) {
  47345. this._profilingCanvas.dispose();
  47346. this._profilingCanvas = null;
  47347. }
  47348. if (this.interactionEnabled) {
  47349. this._setupInteraction(false);
  47350. }
  47351. if (this._beforeRenderObserver) {
  47352. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  47353. this._beforeRenderObserver = null;
  47354. }
  47355. if (this._afterRenderObserver) {
  47356. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  47357. this._afterRenderObserver = null;
  47358. }
  47359. if (this._groupCacheMaps) {
  47360. this._groupCacheMaps.forEach(function (k, m) { return m.forEach(function (e) { return e.dispose(); }); });
  47361. this._groupCacheMaps = null;
  47362. }
  47363. };
  47364. Object.defineProperty(Canvas2D.prototype, "scene", {
  47365. /**
  47366. * Accessor to the Scene that owns the Canvas
  47367. * @returns The instance of the Scene object
  47368. */
  47369. get: function () {
  47370. return this._scene;
  47371. },
  47372. enumerable: true,
  47373. configurable: true
  47374. });
  47375. Object.defineProperty(Canvas2D.prototype, "engine", {
  47376. /**
  47377. * Accessor to the Engine that drives the Scene used by this Canvas
  47378. * @returns The instance of the Engine object
  47379. */
  47380. get: function () {
  47381. return this._engine;
  47382. },
  47383. enumerable: true,
  47384. configurable: true
  47385. });
  47386. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  47387. /**
  47388. * Accessor of the Caching Strategy used by this Canvas.
  47389. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  47390. * @returns the value corresponding to the used strategy.
  47391. */
  47392. get: function () {
  47393. return this._cachingStrategy;
  47394. },
  47395. enumerable: true,
  47396. configurable: true
  47397. });
  47398. Object.defineProperty(Canvas2D.prototype, "isScreenSpace", {
  47399. /**
  47400. * Return true if the Canvas is a Screen Space one, false if it's a World Space one.
  47401. * @returns {}
  47402. */
  47403. get: function () {
  47404. return this._isScreenSpace;
  47405. },
  47406. enumerable: true,
  47407. configurable: true
  47408. });
  47409. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  47410. /**
  47411. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  47412. */
  47413. get: function () {
  47414. return this._worldSpaceNode;
  47415. },
  47416. set: function (val) {
  47417. this._worldSpaceNode = val;
  47418. },
  47419. enumerable: true,
  47420. configurable: true
  47421. });
  47422. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  47423. /**
  47424. * Check if the WebGL Instanced Array extension is supported or not
  47425. */
  47426. get: function () {
  47427. return this._supprtInstancedArray;
  47428. },
  47429. enumerable: true,
  47430. configurable: true
  47431. });
  47432. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  47433. /**
  47434. * Property that defines the fill object used to draw the background of the Canvas.
  47435. * Note that Canvas with a Caching Strategy of
  47436. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  47437. */
  47438. get: function () {
  47439. if (!this._background || !this._background.isVisible) {
  47440. return null;
  47441. }
  47442. return this._background.fill;
  47443. },
  47444. set: function (value) {
  47445. this.checkBackgroundAvailability();
  47446. if (value === this._background.fill) {
  47447. return;
  47448. }
  47449. this._background.fill = value;
  47450. this._background.levelVisible = true;
  47451. },
  47452. enumerable: true,
  47453. configurable: true
  47454. });
  47455. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  47456. /**
  47457. * Property that defines the border object used to draw the background of the Canvas.
  47458. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  47459. */
  47460. get: function () {
  47461. if (!this._background || !this._background.isVisible) {
  47462. return null;
  47463. }
  47464. return this._background.border;
  47465. },
  47466. set: function (value) {
  47467. this.checkBackgroundAvailability();
  47468. if (value === this._background.border) {
  47469. return;
  47470. }
  47471. this._background.border = value;
  47472. this._background.levelVisible = true;
  47473. },
  47474. enumerable: true,
  47475. configurable: true
  47476. });
  47477. Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
  47478. /**
  47479. * Property that defines the thickness of the border object used to draw the background of the Canvas.
  47480. * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
  47481. */
  47482. get: function () {
  47483. if (!this._background || !this._background.isVisible) {
  47484. return null;
  47485. }
  47486. return this._background.borderThickness;
  47487. },
  47488. set: function (value) {
  47489. this.checkBackgroundAvailability();
  47490. if (value === this._background.borderThickness) {
  47491. return;
  47492. }
  47493. this._background.borderThickness = value;
  47494. },
  47495. enumerable: true,
  47496. configurable: true
  47497. });
  47498. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  47499. /**
  47500. * You can set the roundRadius of the background
  47501. * @returns The current roundRadius
  47502. */
  47503. get: function () {
  47504. if (!this._background || !this._background.isVisible) {
  47505. return null;
  47506. }
  47507. return this._background.roundRadius;
  47508. },
  47509. set: function (value) {
  47510. this.checkBackgroundAvailability();
  47511. if (value === this._background.roundRadius) {
  47512. return;
  47513. }
  47514. this._background.roundRadius = value;
  47515. this._background.levelVisible = true;
  47516. },
  47517. enumerable: true,
  47518. configurable: true
  47519. });
  47520. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  47521. /**
  47522. * Enable/Disable interaction for this Canvas
  47523. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  47524. */
  47525. get: function () {
  47526. return this._interactionEnabled;
  47527. },
  47528. set: function (enable) {
  47529. this._setupInteraction(enable);
  47530. },
  47531. enumerable: true,
  47532. configurable: true
  47533. });
  47534. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  47535. /**
  47536. * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
  47537. * @returns {}
  47538. */
  47539. get: function () {
  47540. return this.__engineData;
  47541. },
  47542. enumerable: true,
  47543. configurable: true
  47544. });
  47545. Canvas2D.prototype.createCanvasProfileInfoCanvas = function () {
  47546. if (this._profilingCanvas) {
  47547. return this._profilingCanvas;
  47548. }
  47549. var canvas = new ScreenSpaceCanvas2D(this.scene, {
  47550. id: "ProfileInfoCanvas", cachingStrategy: Canvas2D.CACHESTRATEGY_DONTCACHE, children: [
  47551. new BABYLON.Rectangle2D({
  47552. id: "ProfileBorder", border: "#FFFFFFFF", borderThickness: 2, roundRadius: 5, fill: "#C04040C0", marginAlignment: "h: left, v: top", margin: "10", padding: "10", children: [
  47553. new BABYLON.Text2D("Stats", { id: "ProfileInfoText", marginAlignment: "h: left, v: top", fontName: "10pt Lucida Console" })
  47554. ]
  47555. })
  47556. ]
  47557. });
  47558. this._profileInfoText = canvas.findById("ProfileInfoText");
  47559. this._profilingCanvas = canvas;
  47560. return canvas;
  47561. };
  47562. Canvas2D.prototype.checkBackgroundAvailability = function () {
  47563. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  47564. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  47565. }
  47566. };
  47567. Canvas2D.prototype._initPerfMetrics = function () {
  47568. this._drawCallsOpaqueCounter.fetchNewFrame();
  47569. this._drawCallsAlphaTestCounter.fetchNewFrame();
  47570. this._drawCallsTransparentCounter.fetchNewFrame();
  47571. this._groupRenderCounter.fetchNewFrame();
  47572. this._updateTransparentDataCounter.fetchNewFrame();
  47573. this._cachedGroupRenderCounter.fetchNewFrame();
  47574. this._updateCachedStateCounter.fetchNewFrame();
  47575. this._updateLayoutCounter.fetchNewFrame();
  47576. this._updatePositioningCounter.fetchNewFrame();
  47577. this._updateLocalTransformCounter.fetchNewFrame();
  47578. this._updateGlobalTransformCounter.fetchNewFrame();
  47579. this._boundingInfoRecomputeCounter.fetchNewFrame();
  47580. };
  47581. Canvas2D.prototype._fetchPerfMetrics = function () {
  47582. this._drawCallsOpaqueCounter.addCount(0, true);
  47583. this._drawCallsAlphaTestCounter.addCount(0, true);
  47584. this._drawCallsTransparentCounter.addCount(0, true);
  47585. this._groupRenderCounter.addCount(0, true);
  47586. this._updateTransparentDataCounter.addCount(0, true);
  47587. this._cachedGroupRenderCounter.addCount(0, true);
  47588. this._updateCachedStateCounter.addCount(0, true);
  47589. this._updateLayoutCounter.addCount(0, true);
  47590. this._updatePositioningCounter.addCount(0, true);
  47591. this._updateLocalTransformCounter.addCount(0, true);
  47592. this._updateGlobalTransformCounter.addCount(0, true);
  47593. this._boundingInfoRecomputeCounter.addCount(0, true);
  47594. };
  47595. Canvas2D.prototype._updateProfileCanvas = function () {
  47596. if (this._profileInfoText == null) {
  47597. return;
  47598. }
  47599. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  47600. var p = "Draw Calls:\n" +
  47601. (" - Opaque: " + format(this.drawCallsOpaqueCounter.current) + ", (avg:" + format(this.drawCallsOpaqueCounter.lastSecAverage) + ", t:" + format(this.drawCallsOpaqueCounter.total) + ")\n") +
  47602. (" - AlphaTest: " + format(this.drawCallsAlphaTestCounter.current) + ", (avg:" + format(this.drawCallsAlphaTestCounter.lastSecAverage) + ", t:" + format(this.drawCallsAlphaTestCounter.total) + ")\n") +
  47603. (" - Transparent: " + format(this.drawCallsTransparentCounter.current) + ", (avg:" + format(this.drawCallsTransparentCounter.lastSecAverage) + ", t:" + format(this.drawCallsTransparentCounter.total) + ")\n") +
  47604. ("Group Render: " + this.groupRenderCounter.current + ", (avg:" + format(this.groupRenderCounter.lastSecAverage) + ", t:" + format(this.groupRenderCounter.total) + ")\n") +
  47605. ("Update Transparent Data: " + this.updateTransparentDataCounter.current + ", (avg:" + format(this.updateTransparentDataCounter.lastSecAverage) + ", t:" + format(this.updateTransparentDataCounter.total) + ")\n") +
  47606. ("Cached Group Render: " + this.cachedGroupRenderCounter.current + ", (avg:" + format(this.cachedGroupRenderCounter.lastSecAverage) + ", t:" + format(this.cachedGroupRenderCounter.total) + ")\n") +
  47607. ("Update Cached States: " + this.updateCachedStateCounter.current + ", (avg:" + format(this.updateCachedStateCounter.lastSecAverage) + ", t:" + format(this.updateCachedStateCounter.total) + ")\n") +
  47608. (" - Update Layout: " + this.updateLayoutCounter.current + ", (avg:" + format(this.updateLayoutCounter.lastSecAverage) + ", t:" + format(this.updateLayoutCounter.total) + ")\n") +
  47609. (" - Update Positioning: " + this.updatePositioningCounter.current + ", (avg:" + format(this.updatePositioningCounter.lastSecAverage) + ", t:" + format(this.updatePositioningCounter.total) + ")\n") +
  47610. (" - Update Local Trans: " + this.updateLocalTransformCounter.current + ", (avg:" + format(this.updateLocalTransformCounter.lastSecAverage) + ", t:" + format(this.updateLocalTransformCounter.total) + ")\n") +
  47611. (" - Update Global Trans: " + this.updateGlobalTransformCounter.current + ", (avg:" + format(this.updateGlobalTransformCounter.lastSecAverage) + ", t:" + format(this.updateGlobalTransformCounter.total) + ")\n") +
  47612. (" - BoundingInfo Recompute: " + this.boundingInfoRecomputeCounter.current + ", (avg:" + format(this.boundingInfoRecomputeCounter.lastSecAverage) + ", t:" + format(this.boundingInfoRecomputeCounter.total) + ")\n");
  47613. this._profileInfoText.text = p;
  47614. };
  47615. Canvas2D.prototype._addDrawCallCount = function (count, renderMode) {
  47616. switch (renderMode) {
  47617. case BABYLON.Render2DContext.RenderModeOpaque:
  47618. this._drawCallsOpaqueCounter.addCount(count, false);
  47619. return;
  47620. case BABYLON.Render2DContext.RenderModeAlphaTest:
  47621. this._drawCallsAlphaTestCounter.addCount(count, false);
  47622. return;
  47623. case BABYLON.Render2DContext.RenderModeTransparent:
  47624. this._drawCallsTransparentCounter.addCount(count, false);
  47625. return;
  47626. }
  47627. };
  47628. Canvas2D.prototype._addGroupRenderCount = function (count) {
  47629. this._groupRenderCounter.addCount(count, false);
  47630. };
  47631. Canvas2D.prototype._addUpdateTransparentDataCount = function (count) {
  47632. this._updateTransparentDataCounter.addCount(count, false);
  47633. };
  47634. Canvas2D.prototype.addCachedGroupRenderCounter = function (count) {
  47635. this._cachedGroupRenderCounter.addCount(count, false);
  47636. };
  47637. Canvas2D.prototype.addUpdateCachedStateCounter = function (count) {
  47638. this._updateCachedStateCounter.addCount(count, false);
  47639. };
  47640. Canvas2D.prototype.addUpdateLayoutCounter = function (count) {
  47641. this._updateLayoutCounter.addCount(count, false);
  47642. };
  47643. Canvas2D.prototype.addUpdatePositioningCounter = function (count) {
  47644. this._updatePositioningCounter.addCount(count, false);
  47645. };
  47646. Canvas2D.prototype.addupdateLocalTransformCounter = function (count) {
  47647. this._updateLocalTransformCounter.addCount(count, false);
  47648. };
  47649. Canvas2D.prototype.addUpdateGlobalTransformCounter = function (count) {
  47650. this._updateGlobalTransformCounter.addCount(count, false);
  47651. };
  47652. Canvas2D.prototype._updateTrackedNodes = function () {
  47653. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  47654. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  47655. var rh = this.engine.getRenderHeight();
  47656. var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
  47657. for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
  47658. var group = _a[_i];
  47659. if (group.isDisposed || !group.isVisible) {
  47660. continue;
  47661. }
  47662. var node = group.trackedNode;
  47663. var worldMtx = node.getWorldMatrix();
  47664. var proj = BABYLON.Vector3.Project(Canvas2D._v, worldMtx, Canvas2D._m, v);
  47665. group.x = Math.round(proj.x);
  47666. group.y = Math.round(rh - proj.y);
  47667. }
  47668. };
  47669. /**
  47670. * Call this method change you want to have layout related data computed and up to date (layout area, primitive area, local/global transformation matrices)
  47671. */
  47672. Canvas2D.prototype.updateCanvasLayout = function (forceRecompute) {
  47673. this._updateCanvasState(forceRecompute);
  47674. };
  47675. Canvas2D.prototype._updateAdaptiveSizeWorldCanvas = function () {
  47676. if (this._globalTransformStep < 2) {
  47677. return;
  47678. }
  47679. var n = this.worldSpaceCanvasNode;
  47680. var bi = n.getBoundingInfo().boundingBox;
  47681. var v = bi.vectorsWorld;
  47682. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  47683. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  47684. var vp = cam.viewport.toGlobal(this.engine.getRenderWidth(), this.engine.getRenderHeight());
  47685. var projPoints = new Array(4);
  47686. for (var i = 0; i < 4; i++) {
  47687. projPoints[i] = BABYLON.Vector3.Project(v[i], Canvas2D._mI, Canvas2D._m, vp);
  47688. }
  47689. var left = projPoints[3].subtract(projPoints[0]).length();
  47690. var top = projPoints[3].subtract(projPoints[1]).length();
  47691. var right = projPoints[1].subtract(projPoints[2]).length();
  47692. var bottom = projPoints[2].subtract(projPoints[0]).length();
  47693. var w = Math.round(Math.max(top, bottom));
  47694. var h = Math.round(Math.max(right, left));
  47695. var isW = w > h;
  47696. // Basically if it's under 256 we use 256, otherwise we take the biggest power of 2
  47697. var edge = Math.max(w, h);
  47698. if (edge < 256) {
  47699. edge = 256;
  47700. }
  47701. else {
  47702. edge = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  47703. }
  47704. // Clip values if needed
  47705. edge = Math.min(edge, this._maxAdaptiveWorldSpaceCanvasSize);
  47706. var newScale = edge / ((isW) ? this.size.width : this.size.height);
  47707. if (newScale !== this.scale) {
  47708. var scale = newScale;
  47709. // console.log(`New adaptive scale for Canvas ${this.id}, w: ${w}, h: ${h}, scale: ${scale}, edge: ${edge}, isW: ${isW}`);
  47710. this._setRenderingScale(scale);
  47711. }
  47712. };
  47713. Canvas2D.prototype._updateCanvasState = function (forceRecompute) {
  47714. // Check if the update has already been made for this render Frame
  47715. if (!forceRecompute && this.scene.getRenderId() === this._updateRenderId) {
  47716. return;
  47717. }
  47718. // Detect a change of rendering size
  47719. var renderingSizeChanged = false;
  47720. var newWidth = this.engine.getRenderWidth();
  47721. if (newWidth !== this._renderingSize.width) {
  47722. renderingSizeChanged = true;
  47723. }
  47724. this._renderingSize.width = newWidth;
  47725. var newHeight = this.engine.getRenderHeight();
  47726. if (newHeight !== this._renderingSize.height) {
  47727. renderingSizeChanged = true;
  47728. }
  47729. this._renderingSize.height = newHeight;
  47730. // If the canvas fit the rendering size and it changed, update
  47731. if (renderingSizeChanged && this._fitRenderingDevice) {
  47732. this.size = this._renderingSize;
  47733. if (this._background) {
  47734. this._background.size = this.size;
  47735. }
  47736. // Dirty the Layout at the Canvas level to recompute as the size changed
  47737. this._setLayoutDirty();
  47738. }
  47739. var context = new BABYLON.PrepareRender2DContext();
  47740. ++this._globalTransformProcessStep;
  47741. this.updateCachedStates(false);
  47742. this._prepareGroupRender(context);
  47743. this._updateRenderId = this.scene.getRenderId();
  47744. };
  47745. /**
  47746. * Method that renders the Canvas, you should not invoke
  47747. */
  47748. Canvas2D.prototype._render = function () {
  47749. this._initPerfMetrics();
  47750. this._updateTrackedNodes();
  47751. this._updateCanvasState(false);
  47752. if (!this._isScreenSpace) {
  47753. this._updateAdaptiveSizeWorldCanvas();
  47754. }
  47755. this._updateCanvasState(false);
  47756. if (this._primPointerInfo.canvasPointerPos) {
  47757. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false);
  47758. this._updateOverStatus(); // TODO this._primPointerInfo may not be up to date!
  47759. }
  47760. this.engine.setState(false);
  47761. this._groupRender();
  47762. if (!this._isScreenSpace) {
  47763. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagWorldCacheChanged)) {
  47764. this.worldSpaceCacheChanged();
  47765. this._clearFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  47766. }
  47767. }
  47768. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  47769. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  47770. this._cachedCanvasGroup._renderCachedCanvas();
  47771. }
  47772. this._fetchPerfMetrics();
  47773. this._updateProfileCanvas();
  47774. };
  47775. /**
  47776. * Internal method that allocate a cache for the given group.
  47777. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  47778. * @param group The group to allocate the cache of.
  47779. * @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.
  47780. */
  47781. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize, useMipMap, anisotropicLevel) {
  47782. if (useMipMap === void 0) { useMipMap = false; }
  47783. if (anisotropicLevel === void 0) { anisotropicLevel = 1; }
  47784. var key = (useMipMap ? "MipMap" : "NoMipMap") + "_" + anisotropicLevel;
  47785. // Determine size
  47786. var size = group.actualSize;
  47787. size = new BABYLON.Size(Math.ceil(size.width), Math.ceil(size.height));
  47788. if (minSize) {
  47789. size.width = Math.max(minSize.width, size.width);
  47790. size.height = Math.max(minSize.height, size.height);
  47791. }
  47792. var mapArray = this._groupCacheMaps.getOrAddWithFactory(key, function () { return new Array(); });
  47793. // Try to find a spot in one of the cached texture
  47794. var res = null;
  47795. var map;
  47796. for (var _i = 0; _i < mapArray.length; _i++) {
  47797. var _map = mapArray[_i];
  47798. map = _map;
  47799. var node = map.allocateRect(size);
  47800. if (node) {
  47801. res = { node: node, texture: map };
  47802. break;
  47803. }
  47804. }
  47805. // Couldn't find a map that could fit the rect, create a new map for it
  47806. if (!res) {
  47807. var mapSize = new BABYLON.Size(Canvas2D._groupTextureCacheSize, Canvas2D._groupTextureCacheSize);
  47808. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  47809. if (size.width > mapSize.width || size.height > mapSize.height) {
  47810. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  47811. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  47812. }
  47813. var id = "groupsMapChache" + this._mapCounter + "forCanvas" + this.id;
  47814. map = new BABYLON.MapTexture(id, this._scene, mapSize, useMipMap ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE, useMipMap);
  47815. map.anisotropicFilteringLevel = 4;
  47816. mapArray.splice(0, 0, map);
  47817. var node = map.allocateRect(size);
  47818. res = { node: node, texture: map };
  47819. }
  47820. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  47821. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  47822. if (group !== this || this._isScreenSpace) {
  47823. var node = res.node;
  47824. // 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
  47825. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS) {
  47826. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  47827. var sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: node.contentSize, spriteLocation: node.pos });
  47828. sprite.zOrder = 1;
  47829. sprite.origin = BABYLON.Vector2.Zero();
  47830. }
  47831. else {
  47832. 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 });
  47833. sprite.origin = group.origin.clone();
  47834. res.sprite = sprite;
  47835. }
  47836. }
  47837. return res;
  47838. };
  47839. /**
  47840. * Internal method used to register a Scene Node to track position for the given group
  47841. * Do not invoke this method, for internal purpose only.
  47842. * @param group the group to track its associated Scene Node
  47843. */
  47844. Canvas2D.prototype._registerTrackedNode = function (group) {
  47845. if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  47846. return;
  47847. }
  47848. this._trackedGroups.push(group);
  47849. group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  47850. };
  47851. /**
  47852. * Internal method used to unregister a tracked Scene Node
  47853. * Do not invoke this method, it's for internal purpose only.
  47854. * @param group the group to unregister its tracked Scene Node from.
  47855. */
  47856. Canvas2D.prototype._unregisterTrackedNode = function (group) {
  47857. if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  47858. return;
  47859. }
  47860. var i = this._trackedGroups.indexOf(group);
  47861. if (i !== -1) {
  47862. this._trackedGroups.splice(i, 1);
  47863. }
  47864. group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  47865. };
  47866. /**
  47867. * Get a Solid Color Brush instance matching the given color.
  47868. * @param color The color to retrieve
  47869. * @return A shared instance of the SolidColorBrush2D class that use the given color
  47870. */
  47871. Canvas2D.GetSolidColorBrush = function (color) {
  47872. return Canvas2D._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  47873. };
  47874. /**
  47875. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  47876. * @param color The color to retrieve
  47877. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  47878. */
  47879. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  47880. return Canvas2D._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  47881. };
  47882. /**
  47883. * Get a Gradient Color Brush
  47884. * @param color1 starting color
  47885. * @param color2 engine color
  47886. * @param translation translation vector to apply. default is [0;0]
  47887. * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
  47888. * @param scale scaling factor to apply. default is 1.
  47889. */
  47890. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  47891. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  47892. if (rotation === void 0) { rotation = 0; }
  47893. if (scale === void 0) { scale = 1; }
  47894. return Canvas2D._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  47895. };
  47896. /**
  47897. * Create a solid or gradient brush from a string value.
  47898. * @param brushString should be either
  47899. * - "solid: #RRGGBBAA" or "#RRGGBBAA"
  47900. * - "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.
  47901. */
  47902. Canvas2D.GetBrushFromString = function (brushString) {
  47903. // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
  47904. brushString = brushString.trim();
  47905. var split = brushString.split(",");
  47906. // Solid, formatted as: "[solid:]#FF808080"
  47907. if (split.length === 1) {
  47908. var value = null;
  47909. if (brushString.indexOf("solid:") === 0) {
  47910. value = brushString.substr(6).trim();
  47911. }
  47912. else if (brushString.indexOf("#") === 0) {
  47913. value = brushString;
  47914. }
  47915. else {
  47916. return null;
  47917. }
  47918. return Canvas2D.GetSolidColorBrushFromHex(value);
  47919. }
  47920. else {
  47921. if (split[0].indexOf("gradient:") === 0) {
  47922. split[0] = split[0].substr(9).trim();
  47923. }
  47924. try {
  47925. var start = BABYLON.Color4.FromHexString(split[0].trim());
  47926. var end = BABYLON.Color4.FromHexString(split[1].trim());
  47927. var t = BABYLON.Vector2.Zero();
  47928. if (split.length > 2) {
  47929. var v = split[2].trim();
  47930. if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
  47931. return null;
  47932. }
  47933. var sep = v.indexOf(":");
  47934. var x = parseFloat(v.substr(1, sep));
  47935. var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
  47936. t = new BABYLON.Vector2(x, y);
  47937. }
  47938. var r = 0;
  47939. if (split.length > 3) {
  47940. r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
  47941. }
  47942. var s = 1;
  47943. if (split.length > 4) {
  47944. s = parseFloat(split[4].trim());
  47945. }
  47946. return Canvas2D.GetGradientColorBrush(start, end, t, r, s);
  47947. }
  47948. catch (e) {
  47949. return null;
  47950. }
  47951. }
  47952. };
  47953. /**
  47954. * 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.
  47955. * This strategy doesn't allow primitives added directly as children of the Canvas.
  47956. * 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.
  47957. */
  47958. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  47959. /**
  47960. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  47961. * 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.
  47962. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  47963. * 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.
  47964. */
  47965. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  47966. /**
  47967. * 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).
  47968. */
  47969. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  47970. /**
  47971. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  47972. * 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).
  47973. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  47974. */
  47975. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  47976. Canvas2D._zMinDelta = 1 / (Math.pow(2, 24) - 1);
  47977. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  47978. Canvas2D._v = BABYLON.Vector3.Zero(); // Must stay zero
  47979. Canvas2D._m = BABYLON.Matrix.Identity();
  47980. Canvas2D._mI = BABYLON.Matrix.Identity(); // Must stay identity
  47981. /**
  47982. * Define the default size used for both the width and height of a MapTexture to allocate.
  47983. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  47984. */
  47985. Canvas2D._groupTextureCacheSize = 1024;
  47986. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  47987. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  47988. Canvas2D = __decorate([
  47989. BABYLON.className("Canvas2D")
  47990. ], Canvas2D);
  47991. return Canvas2D;
  47992. })(BABYLON.Group2D);
  47993. BABYLON.Canvas2D = Canvas2D;
  47994. var WorldSpaceCanvas2D = (function (_super) {
  47995. __extends(WorldSpaceCanvas2D, _super);
  47996. /**
  47997. * 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.
  47998. * 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.
  47999. * @param scene the Scene that owns the Canvas
  48000. * @param size the dimension of the Canvas in World Space
  48001. * @param settings a combination of settings, possible ones are
  48002. * - children: an array of direct children primitives
  48003. * - id: a text identifier, for information purpose only, default is null.
  48004. * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
  48005. * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  48006. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  48007. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  48008. * - 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).
  48009. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  48010. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  48011. * - 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.
  48012. * - 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.
  48013. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  48014. * - 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.
  48015. * - 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.
  48016. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  48017. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  48018. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  48019. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  48020. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  48021. */
  48022. function WorldSpaceCanvas2D(scene, size, settings) {
  48023. BABYLON.Prim2DBase._isCanvasInit = true;
  48024. var s = settings;
  48025. s.isScreenSpace = false;
  48026. s.size = size.clone();
  48027. settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
  48028. if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  48029. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  48030. }
  48031. _super.call(this, scene, settings);
  48032. BABYLON.Prim2DBase._isCanvasInit = false;
  48033. this._renderableData._useMipMap = true;
  48034. this._renderableData._anisotropicLevel = 8;
  48035. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  48036. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  48037. //}
  48038. var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
  48039. var id = settings ? settings.id || null : null;
  48040. // Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap
  48041. var capMaxTextSize = this.engine.getCaps().maxRenderTextureSize;
  48042. var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 4K if allowed otherwise the max allowed
  48043. if (settings.maxAdaptiveCanvasSize == null) {
  48044. this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;
  48045. }
  48046. else {
  48047. // We still clip the given value with the max allowed, the user may not be aware of these limitations
  48048. this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);
  48049. }
  48050. if (createWorldSpaceNode) {
  48051. var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, this);
  48052. var vertexData = BABYLON.VertexData.CreatePlane({
  48053. width: size.width,
  48054. height: size.height,
  48055. sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  48056. });
  48057. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  48058. this.applyCachedTexture(vertexData, mtl);
  48059. vertexData.applyToMesh(plane, true);
  48060. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  48061. mtl.disableLighting = true;
  48062. mtl.useAlphaFromDiffuseTexture = true;
  48063. plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
  48064. plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
  48065. plane.material = mtl;
  48066. this._worldSpaceNode = plane;
  48067. }
  48068. else {
  48069. this._worldSpaceNode = settings.customWorldSpaceNode;
  48070. this.applyCachedTexture(null, null);
  48071. }
  48072. }
  48073. WorldSpaceCanvas2D = __decorate([
  48074. BABYLON.className("WorldSpaceCanvas2D")
  48075. ], WorldSpaceCanvas2D);
  48076. return WorldSpaceCanvas2D;
  48077. })(Canvas2D);
  48078. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  48079. var ScreenSpaceCanvas2D = (function (_super) {
  48080. __extends(ScreenSpaceCanvas2D, _super);
  48081. /**
  48082. * 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.
  48083. * 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.
  48084. * All caching strategies will be available.
  48085. * 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]
  48086. * @param scene the Scene that owns the Canvas
  48087. * @param settings a combination of settings, possible ones are
  48088. * - children: an array of direct children primitives
  48089. * - id: a text identifier, for information purpose only
  48090. * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
  48091. * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
  48092. * - 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]
  48093. * - width: the width of the Canvas. you can alternatively use the size setting.
  48094. * - height: the height of the Canvas. you can alternatively use the size setting.
  48095. * - 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
  48096. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  48097. * - 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.
  48098. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  48099. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  48100. * - 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.
  48101. * - 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.
  48102. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  48103. * - 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.
  48104. * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  48105. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  48106. * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  48107. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  48108. * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
  48109. */
  48110. function ScreenSpaceCanvas2D(scene, settings) {
  48111. BABYLON.Prim2DBase._isCanvasInit = true;
  48112. _super.call(this, scene, settings);
  48113. }
  48114. ScreenSpaceCanvas2D = __decorate([
  48115. BABYLON.className("ScreenSpaceCanvas2D")
  48116. ], ScreenSpaceCanvas2D);
  48117. return ScreenSpaceCanvas2D;
  48118. })(Canvas2D);
  48119. BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
  48120. })(BABYLON || (BABYLON = {}));
  48121. var BABYLON;
  48122. (function (BABYLON) {
  48123. /**
  48124. * This is the class that is used to display a World Space Canvas into a 3D scene
  48125. */
  48126. var WorldSpaceCanvas2DNode = (function (_super) {
  48127. __extends(WorldSpaceCanvas2DNode, _super);
  48128. function WorldSpaceCanvas2DNode(name, scene, canvas) {
  48129. _super.call(this, name, scene);
  48130. this._canvas = canvas;
  48131. }
  48132. WorldSpaceCanvas2DNode.prototype.dispose = function () {
  48133. _super.prototype.dispose.call(this);
  48134. if (this._canvas) {
  48135. this._canvas.dispose();
  48136. this._canvas = null;
  48137. }
  48138. };
  48139. return WorldSpaceCanvas2DNode;
  48140. })(BABYLON.Mesh);
  48141. BABYLON.WorldSpaceCanvas2DNode = WorldSpaceCanvas2DNode;
  48142. })(BABYLON || (BABYLON = {}));
  48143. var BABYLON;
  48144. (function (BABYLON) {
  48145. var LayoutEngineBase = (function () {
  48146. function LayoutEngineBase() {
  48147. this.layoutDirtyOnPropertyChangedMask = 0;
  48148. }
  48149. LayoutEngineBase.prototype.updateLayout = function (prim) {
  48150. };
  48151. Object.defineProperty(LayoutEngineBase.prototype, "isChildPositionAllowed", {
  48152. get: function () {
  48153. return false;
  48154. },
  48155. enumerable: true,
  48156. configurable: true
  48157. });
  48158. LayoutEngineBase.prototype.isLocked = function () {
  48159. return this._isLocked;
  48160. };
  48161. LayoutEngineBase.prototype.lock = function () {
  48162. if (this._isLocked) {
  48163. return false;
  48164. }
  48165. this._isLocked = true;
  48166. return true;
  48167. };
  48168. LayoutEngineBase = __decorate([
  48169. BABYLON.className("LayoutEngineBase")
  48170. ], LayoutEngineBase);
  48171. return LayoutEngineBase;
  48172. })();
  48173. BABYLON.LayoutEngineBase = LayoutEngineBase;
  48174. var CanvasLayoutEngine = (function (_super) {
  48175. __extends(CanvasLayoutEngine, _super);
  48176. function CanvasLayoutEngine() {
  48177. _super.apply(this, arguments);
  48178. }
  48179. // A very simple (no) layout computing...
  48180. // The Canvas and its direct children gets the Canvas' size as Layout Area
  48181. // Indirect children have their Layout Area to the actualSize (margin area) of their parent
  48182. CanvasLayoutEngine.prototype.updateLayout = function (prim) {
  48183. // If this prim is layoutDiry we update its layoutArea and also the one of its direct children
  48184. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  48185. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  48186. var child = _a[_i];
  48187. this._doUpdate(child);
  48188. }
  48189. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  48190. }
  48191. };
  48192. CanvasLayoutEngine.prototype._doUpdate = function (prim) {
  48193. // Canvas ?
  48194. if (prim instanceof BABYLON.Canvas2D) {
  48195. prim.layoutArea = prim.actualSize;
  48196. }
  48197. else if (prim.parent instanceof BABYLON.Canvas2D) {
  48198. prim.layoutArea = prim.owner.actualSize;
  48199. }
  48200. else {
  48201. prim.layoutArea = prim.parent.contentArea;
  48202. }
  48203. };
  48204. Object.defineProperty(CanvasLayoutEngine.prototype, "isChildPositionAllowed", {
  48205. get: function () {
  48206. return true;
  48207. },
  48208. enumerable: true,
  48209. configurable: true
  48210. });
  48211. CanvasLayoutEngine.Singleton = new CanvasLayoutEngine();
  48212. CanvasLayoutEngine = __decorate([
  48213. BABYLON.className("CanvasLayoutEngine")
  48214. ], CanvasLayoutEngine);
  48215. return CanvasLayoutEngine;
  48216. })(LayoutEngineBase);
  48217. BABYLON.CanvasLayoutEngine = CanvasLayoutEngine;
  48218. var StackPanelLayoutEngine = (function (_super) {
  48219. __extends(StackPanelLayoutEngine, _super);
  48220. function StackPanelLayoutEngine() {
  48221. _super.call(this);
  48222. this._isHorizontal = true;
  48223. this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId;
  48224. }
  48225. Object.defineProperty(StackPanelLayoutEngine, "Horizontal", {
  48226. get: function () {
  48227. if (!StackPanelLayoutEngine._horizontal) {
  48228. StackPanelLayoutEngine._horizontal = new StackPanelLayoutEngine();
  48229. StackPanelLayoutEngine._horizontal.isHorizontal = true;
  48230. StackPanelLayoutEngine._horizontal.lock();
  48231. }
  48232. return StackPanelLayoutEngine._horizontal;
  48233. },
  48234. enumerable: true,
  48235. configurable: true
  48236. });
  48237. Object.defineProperty(StackPanelLayoutEngine, "Vertical", {
  48238. get: function () {
  48239. if (!StackPanelLayoutEngine._vertical) {
  48240. StackPanelLayoutEngine._vertical = new StackPanelLayoutEngine();
  48241. StackPanelLayoutEngine._vertical.isHorizontal = false;
  48242. StackPanelLayoutEngine._vertical.lock();
  48243. }
  48244. return StackPanelLayoutEngine._vertical;
  48245. },
  48246. enumerable: true,
  48247. configurable: true
  48248. });
  48249. Object.defineProperty(StackPanelLayoutEngine.prototype, "isHorizontal", {
  48250. get: function () {
  48251. return this._isHorizontal;
  48252. },
  48253. set: function (val) {
  48254. if (this.isLocked()) {
  48255. return;
  48256. }
  48257. this._isHorizontal = val;
  48258. },
  48259. enumerable: true,
  48260. configurable: true
  48261. });
  48262. StackPanelLayoutEngine.prototype.updateLayout = function (prim) {
  48263. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  48264. var x = 0;
  48265. var y = 0;
  48266. var h = this.isHorizontal;
  48267. var max = 0;
  48268. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  48269. var child = _a[_i];
  48270. var layoutArea = child.layoutArea;
  48271. child.margin.computeArea(child.actualSize, layoutArea);
  48272. max = Math.max(max, h ? layoutArea.height : layoutArea.width);
  48273. }
  48274. for (var _b = 0, _c = prim.children; _b < _c.length; _b++) {
  48275. var child = _c[_b];
  48276. child.layoutAreaPos = new BABYLON.Vector2(x, y);
  48277. var layoutArea = child.layoutArea;
  48278. if (h) {
  48279. x += layoutArea.width;
  48280. child.layoutArea = new BABYLON.Size(layoutArea.width, max);
  48281. }
  48282. else {
  48283. y += layoutArea.height;
  48284. child.layoutArea = new BABYLON.Size(max, layoutArea.height);
  48285. }
  48286. }
  48287. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  48288. }
  48289. };
  48290. Object.defineProperty(StackPanelLayoutEngine.prototype, "isChildPositionAllowed", {
  48291. get: function () {
  48292. return false;
  48293. },
  48294. enumerable: true,
  48295. configurable: true
  48296. });
  48297. StackPanelLayoutEngine._horizontal = null;
  48298. StackPanelLayoutEngine._vertical = null;
  48299. StackPanelLayoutEngine = __decorate([
  48300. BABYLON.className("StackPanelLayoutEngine")
  48301. ], StackPanelLayoutEngine);
  48302. return StackPanelLayoutEngine;
  48303. })(LayoutEngineBase);
  48304. BABYLON.StackPanelLayoutEngine = StackPanelLayoutEngine;
  48305. })(BABYLON || (BABYLON = {}));
  48306. var BABYLON;
  48307. (function (BABYLON) {
  48308. var ShaderMaterial = (function (_super) {
  48309. __extends(ShaderMaterial, _super);
  48310. function ShaderMaterial(name, scene, shaderPath, options) {
  48311. _super.call(this, name, scene);
  48312. this._textures = {};
  48313. this._textureArrays = {};
  48314. this._floats = {};
  48315. this._floatsArrays = {};
  48316. this._colors3 = {};
  48317. this._colors4 = {};
  48318. this._vectors2 = {};
  48319. this._vectors3 = {};
  48320. this._vectors4 = {};
  48321. this._matrices = {};
  48322. this._matrices3x3 = {};
  48323. this._matrices2x2 = {};
  48324. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  48325. this._shaderPath = shaderPath;
  48326. options.needAlphaBlending = options.needAlphaBlending || false;
  48327. options.needAlphaTesting = options.needAlphaTesting || false;
  48328. options.attributes = options.attributes || ["position", "normal", "uv"];
  48329. options.uniforms = options.uniforms || ["worldViewProjection"];
  48330. options.samplers = options.samplers || [];
  48331. options.defines = options.defines || [];
  48332. this._options = options;
  48333. }
  48334. ShaderMaterial.prototype.needAlphaBlending = function () {
  48335. return this._options.needAlphaBlending;
  48336. };
  48337. ShaderMaterial.prototype.needAlphaTesting = function () {
  48338. return this._options.needAlphaTesting;
  48339. };
  48340. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  48341. if (this._options.uniforms.indexOf(uniformName) === -1) {
  48342. this._options.uniforms.push(uniformName);
  48343. }
  48344. };
  48345. ShaderMaterial.prototype.setTexture = function (name, texture) {
  48346. if (this._options.samplers.indexOf(name) === -1) {
  48347. this._options.samplers.push(name);
  48348. }
  48349. this._textures[name] = texture;
  48350. return this;
  48351. };
  48352. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  48353. if (this._options.samplers.indexOf(name) === -1) {
  48354. this._options.samplers.push(name);
  48355. }
  48356. this._checkUniform(name);
  48357. this._textureArrays[name] = textures;
  48358. return this;
  48359. };
  48360. ShaderMaterial.prototype.setFloat = function (name, value) {
  48361. this._checkUniform(name);
  48362. this._floats[name] = value;
  48363. return this;
  48364. };
  48365. ShaderMaterial.prototype.setFloats = function (name, value) {
  48366. this._checkUniform(name);
  48367. this._floatsArrays[name] = value;
  48368. return this;
  48369. };
  48370. ShaderMaterial.prototype.setColor3 = function (name, value) {
  48371. this._checkUniform(name);
  48372. this._colors3[name] = value;
  48373. return this;
  48374. };
  48375. ShaderMaterial.prototype.setColor4 = function (name, value) {
  48376. this._checkUniform(name);
  48377. this._colors4[name] = value;
  48378. return this;
  48379. };
  48380. ShaderMaterial.prototype.setVector2 = function (name, value) {
  48381. this._checkUniform(name);
  48382. this._vectors2[name] = value;
  48383. return this;
  48384. };
  48385. ShaderMaterial.prototype.setVector3 = function (name, value) {
  48386. this._checkUniform(name);
  48387. this._vectors3[name] = value;
  48388. return this;
  48389. };
  48390. ShaderMaterial.prototype.setVector4 = function (name, value) {
  48391. this._checkUniform(name);
  48392. this._vectors4[name] = value;
  48393. return this;
  48394. };
  48395. ShaderMaterial.prototype.setMatrix = function (name, value) {
  48396. this._checkUniform(name);
  48397. this._matrices[name] = value;
  48398. return this;
  48399. };
  48400. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  48401. this._checkUniform(name);
  48402. this._matrices3x3[name] = value;
  48403. return this;
  48404. };
  48405. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  48406. this._checkUniform(name);
  48407. this._matrices2x2[name] = value;
  48408. return this;
  48409. };
  48410. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  48411. var scene = this.getScene();
  48412. var engine = scene.getEngine();
  48413. if (!this.checkReadyOnEveryCall) {
  48414. if (this._renderId === scene.getRenderId()) {
  48415. return true;
  48416. }
  48417. }
  48418. // Instances
  48419. var defines = [];
  48420. var fallbacks = new BABYLON.EffectFallbacks();
  48421. if (useInstances) {
  48422. defines.push("#define INSTANCES");
  48423. }
  48424. for (var index = 0; index < this._options.defines.length; index++) {
  48425. defines.push(this._options.defines[index]);
  48426. }
  48427. // Bones
  48428. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  48429. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48430. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48431. fallbacks.addCPUSkinningFallback(0, mesh);
  48432. }
  48433. // Alpha test
  48434. if (engine.getAlphaTesting()) {
  48435. defines.push("#define ALPHATEST");
  48436. }
  48437. var previousEffect = this._effect;
  48438. var join = defines.join("\n");
  48439. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  48440. if (!this._effect.isReady()) {
  48441. return false;
  48442. }
  48443. if (previousEffect !== this._effect) {
  48444. scene.resetCachedMaterial();
  48445. }
  48446. this._renderId = scene.getRenderId();
  48447. return true;
  48448. };
  48449. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  48450. var scene = this.getScene();
  48451. if (this._options.uniforms.indexOf("world") !== -1) {
  48452. this._effect.setMatrix("world", world);
  48453. }
  48454. if (this._options.uniforms.indexOf("worldView") !== -1) {
  48455. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  48456. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  48457. }
  48458. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  48459. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  48460. }
  48461. };
  48462. ShaderMaterial.prototype.bind = function (world, mesh) {
  48463. // Std values
  48464. this.bindOnlyWorldMatrix(world);
  48465. if (this.getScene().getCachedMaterial() !== this) {
  48466. if (this._options.uniforms.indexOf("view") !== -1) {
  48467. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  48468. }
  48469. if (this._options.uniforms.indexOf("projection") !== -1) {
  48470. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  48471. }
  48472. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  48473. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  48474. }
  48475. // Bones
  48476. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  48477. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  48478. }
  48479. var name;
  48480. // Texture
  48481. for (name in this._textures) {
  48482. this._effect.setTexture(name, this._textures[name]);
  48483. }
  48484. // Texture arrays
  48485. for (name in this._textureArrays) {
  48486. this._effect.setTextureArray(name, this._textureArrays[name]);
  48487. }
  48488. // Float
  48489. for (name in this._floats) {
  48490. this._effect.setFloat(name, this._floats[name]);
  48491. }
  48492. // Float s
  48493. for (name in this._floatsArrays) {
  48494. this._effect.setArray(name, this._floatsArrays[name]);
  48495. }
  48496. // Color3
  48497. for (name in this._colors3) {
  48498. this._effect.setColor3(name, this._colors3[name]);
  48499. }
  48500. // Color4
  48501. for (name in this._colors4) {
  48502. var color = this._colors4[name];
  48503. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  48504. }
  48505. // Vector2
  48506. for (name in this._vectors2) {
  48507. this._effect.setVector2(name, this._vectors2[name]);
  48508. }
  48509. // Vector3
  48510. for (name in this._vectors3) {
  48511. this._effect.setVector3(name, this._vectors3[name]);
  48512. }
  48513. // Vector4
  48514. for (name in this._vectors4) {
  48515. this._effect.setVector4(name, this._vectors4[name]);
  48516. }
  48517. // Matrix
  48518. for (name in this._matrices) {
  48519. this._effect.setMatrix(name, this._matrices[name]);
  48520. }
  48521. // Matrix 3x3
  48522. for (name in this._matrices3x3) {
  48523. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  48524. }
  48525. // Matrix 2x2
  48526. for (name in this._matrices2x2) {
  48527. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  48528. }
  48529. }
  48530. _super.prototype.bind.call(this, world, mesh);
  48531. };
  48532. ShaderMaterial.prototype.clone = function (name) {
  48533. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  48534. return newShaderMaterial;
  48535. };
  48536. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  48537. if (forceDisposeTextures) {
  48538. var name;
  48539. for (name in this._textures) {
  48540. this._textures[name].dispose();
  48541. }
  48542. for (name in this._textureArrays) {
  48543. var array = this._textureArrays[name];
  48544. for (var index = 0; index < array.length; index++) {
  48545. array[index].dispose();
  48546. }
  48547. }
  48548. }
  48549. this._textures = {};
  48550. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  48551. };
  48552. ShaderMaterial.prototype.serialize = function () {
  48553. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48554. serializationObject.customType = "BABYLON.ShaderMaterial";
  48555. serializationObject.options = this._options;
  48556. serializationObject.shaderPath = this._shaderPath;
  48557. var name;
  48558. // Texture
  48559. serializationObject.textures = {};
  48560. for (name in this._textures) {
  48561. serializationObject.textures[name] = this._textures[name].serialize();
  48562. }
  48563. // Texture arrays
  48564. serializationObject.textureArrays = {};
  48565. for (name in this._textureArrays) {
  48566. serializationObject.textureArrays[name] = [];
  48567. var array = this._textureArrays[name];
  48568. for (var index = 0; index < array.length; index++) {
  48569. serializationObject.textureArrays[name].push(array[index].serialize());
  48570. }
  48571. }
  48572. // Float
  48573. serializationObject.floats = {};
  48574. for (name in this._floats) {
  48575. serializationObject.floats[name] = this._floats[name];
  48576. }
  48577. // Float s
  48578. serializationObject.floatArrays = {};
  48579. for (name in this._floatsArrays) {
  48580. serializationObject.floatArrays[name] = this._floatsArrays[name];
  48581. }
  48582. // Color3
  48583. serializationObject.colors3 = {};
  48584. for (name in this._colors3) {
  48585. serializationObject.colors3[name] = this._colors3[name].asArray();
  48586. }
  48587. // Color4
  48588. serializationObject.colors4 = {};
  48589. for (name in this._colors4) {
  48590. serializationObject.colors4[name] = this._colors4[name].asArray();
  48591. }
  48592. // Vector2
  48593. serializationObject.vectors2 = {};
  48594. for (name in this._vectors2) {
  48595. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  48596. }
  48597. // Vector3
  48598. serializationObject.vectors3 = {};
  48599. for (name in this._vectors3) {
  48600. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  48601. }
  48602. // Vector4
  48603. serializationObject.vectors4 = {};
  48604. for (name in this._vectors4) {
  48605. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  48606. }
  48607. // Matrix
  48608. serializationObject.matrices = {};
  48609. for (name in this._matrices) {
  48610. serializationObject.matrices[name] = this._matrices[name].asArray();
  48611. }
  48612. // Matrix 3x3
  48613. serializationObject.matrices3x3 = {};
  48614. for (name in this._matrices3x3) {
  48615. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  48616. }
  48617. // Matrix 2x2
  48618. serializationObject.matrices2x2 = {};
  48619. for (name in this._matrices2x2) {
  48620. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  48621. }
  48622. return serializationObject;
  48623. };
  48624. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  48625. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  48626. var name;
  48627. // Texture
  48628. for (name in source.textures) {
  48629. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  48630. }
  48631. // Texture arrays
  48632. for (name in source.textureArrays) {
  48633. var array = source.textureArrays[name];
  48634. var textureArray = new Array();
  48635. for (var index = 0; index < array.length; index++) {
  48636. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  48637. }
  48638. material.setTextureArray(name, textureArray);
  48639. }
  48640. // Float
  48641. for (name in source.floats) {
  48642. material.setFloat(name, source.floats[name]);
  48643. }
  48644. // Float s
  48645. for (name in source.floatsArrays) {
  48646. material.setFloats(name, source.floatsArrays[name]);
  48647. }
  48648. // Color3
  48649. for (name in source.colors3) {
  48650. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  48651. }
  48652. // Color4
  48653. for (name in source.colors4) {
  48654. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  48655. }
  48656. // Vector2
  48657. for (name in source.vectors2) {
  48658. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  48659. }
  48660. // Vector3
  48661. for (name in source.vectors3) {
  48662. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  48663. }
  48664. // Vector4
  48665. for (name in source.vectors4) {
  48666. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  48667. }
  48668. // Matrix
  48669. for (name in source.matrices) {
  48670. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  48671. }
  48672. // Matrix 3x3
  48673. for (name in source.matrices3x3) {
  48674. material.setMatrix3x3(name, source.matrices3x3[name]);
  48675. }
  48676. // Matrix 2x2
  48677. for (name in source.matrices2x2) {
  48678. material.setMatrix2x2(name, source.matrices2x2[name]);
  48679. }
  48680. return material;
  48681. };
  48682. return ShaderMaterial;
  48683. })(BABYLON.Material);
  48684. BABYLON.ShaderMaterial = ShaderMaterial;
  48685. })(BABYLON || (BABYLON = {}));
  48686. var BABYLON;
  48687. (function (BABYLON) {
  48688. var Internals;
  48689. (function (Internals) {
  48690. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  48691. // All values and structures referenced from:
  48692. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  48693. var DDS_MAGIC = 0x20534444;
  48694. 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;
  48695. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  48696. 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;
  48697. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  48698. function FourCCToInt32(value) {
  48699. return value.charCodeAt(0) +
  48700. (value.charCodeAt(1) << 8) +
  48701. (value.charCodeAt(2) << 16) +
  48702. (value.charCodeAt(3) << 24);
  48703. }
  48704. function Int32ToFourCC(value) {
  48705. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  48706. }
  48707. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  48708. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  48709. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  48710. var headerLengthInt = 31; // The header length in 32 bit ints
  48711. // Offsets into the header array
  48712. var off_magic = 0;
  48713. var off_size = 1;
  48714. var off_flags = 2;
  48715. var off_height = 3;
  48716. var off_width = 4;
  48717. var off_mipmapCount = 7;
  48718. var off_pfFlags = 20;
  48719. var off_pfFourCC = 21;
  48720. var off_RGBbpp = 22;
  48721. var off_RMask = 23;
  48722. var off_GMask = 24;
  48723. var off_BMask = 25;
  48724. var off_AMask = 26;
  48725. var off_caps1 = 27;
  48726. var off_caps2 = 28;
  48727. ;
  48728. var DDSTools = (function () {
  48729. function DDSTools() {
  48730. }
  48731. DDSTools.GetDDSInfo = function (arrayBuffer) {
  48732. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  48733. var mipmapCount = 1;
  48734. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  48735. mipmapCount = Math.max(1, header[off_mipmapCount]);
  48736. }
  48737. return {
  48738. width: header[off_width],
  48739. height: header[off_height],
  48740. mipmapCount: mipmapCount,
  48741. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  48742. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  48743. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  48744. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  48745. };
  48746. };
  48747. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  48748. var byteArray = new Uint8Array(dataLength);
  48749. var srcData = new Uint8Array(arrayBuffer);
  48750. var index = 0;
  48751. for (var y = height - 1; y >= 0; y--) {
  48752. for (var x = 0; x < width; x++) {
  48753. var srcPos = dataOffset + (x + y * width) * 4;
  48754. byteArray[index + 2] = srcData[srcPos];
  48755. byteArray[index + 1] = srcData[srcPos + 1];
  48756. byteArray[index] = srcData[srcPos + 2];
  48757. byteArray[index + 3] = srcData[srcPos + 3];
  48758. index += 4;
  48759. }
  48760. }
  48761. return byteArray;
  48762. };
  48763. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  48764. var byteArray = new Uint8Array(dataLength);
  48765. var srcData = new Uint8Array(arrayBuffer);
  48766. var index = 0;
  48767. for (var y = height - 1; y >= 0; y--) {
  48768. for (var x = 0; x < width; x++) {
  48769. var srcPos = dataOffset + (x + y * width) * 3;
  48770. byteArray[index + 2] = srcData[srcPos];
  48771. byteArray[index + 1] = srcData[srcPos + 1];
  48772. byteArray[index] = srcData[srcPos + 2];
  48773. index += 3;
  48774. }
  48775. }
  48776. return byteArray;
  48777. };
  48778. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  48779. var byteArray = new Uint8Array(dataLength);
  48780. var srcData = new Uint8Array(arrayBuffer);
  48781. var index = 0;
  48782. for (var y = height - 1; y >= 0; y--) {
  48783. for (var x = 0; x < width; x++) {
  48784. var srcPos = dataOffset + (x + y * width);
  48785. byteArray[index] = srcData[srcPos];
  48786. index++;
  48787. }
  48788. }
  48789. return byteArray;
  48790. };
  48791. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  48792. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  48793. if (header[off_magic] != DDS_MAGIC) {
  48794. BABYLON.Tools.Error("Invalid magic number in DDS header");
  48795. return;
  48796. }
  48797. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  48798. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  48799. return;
  48800. }
  48801. if (info.isFourCC) {
  48802. fourCC = header[off_pfFourCC];
  48803. switch (fourCC) {
  48804. case FOURCC_DXT1:
  48805. blockBytes = 8;
  48806. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  48807. break;
  48808. case FOURCC_DXT3:
  48809. blockBytes = 16;
  48810. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  48811. break;
  48812. case FOURCC_DXT5:
  48813. blockBytes = 16;
  48814. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  48815. break;
  48816. default:
  48817. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  48818. return;
  48819. }
  48820. }
  48821. mipmapCount = 1;
  48822. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  48823. mipmapCount = Math.max(1, header[off_mipmapCount]);
  48824. }
  48825. var bpp = header[off_RGBbpp];
  48826. for (var face = 0; face < faces; face++) {
  48827. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  48828. width = header[off_width];
  48829. height = header[off_height];
  48830. dataOffset = header[off_size] + 4;
  48831. for (i = 0; i < mipmapCount; ++i) {
  48832. if (info.isRGB) {
  48833. if (bpp === 24) {
  48834. dataLength = width * height * 3;
  48835. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  48836. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  48837. }
  48838. else {
  48839. dataLength = width * height * 4;
  48840. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  48841. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  48842. }
  48843. }
  48844. else if (info.isLuminance) {
  48845. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  48846. var unpaddedRowSize = width;
  48847. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  48848. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  48849. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  48850. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  48851. }
  48852. else {
  48853. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  48854. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  48855. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  48856. }
  48857. dataOffset += dataLength;
  48858. width *= 0.5;
  48859. height *= 0.5;
  48860. width = Math.max(1.0, width);
  48861. height = Math.max(1.0, height);
  48862. }
  48863. }
  48864. };
  48865. return DDSTools;
  48866. })();
  48867. Internals.DDSTools = DDSTools;
  48868. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48869. })(BABYLON || (BABYLON = {}));
  48870. var BABYLON;
  48871. (function (BABYLON) {
  48872. var CannonJSPlugin = (function () {
  48873. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  48874. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  48875. if (iterations === void 0) { iterations = 10; }
  48876. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  48877. this.name = "CannonJSPlugin";
  48878. this._physicsMaterials = [];
  48879. this._fixedTimeStep = 1 / 60;
  48880. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  48881. this._currentCollisionGroup = 2;
  48882. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  48883. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  48884. this._tmpPosition = BABYLON.Vector3.Zero();
  48885. this._tmpQuaternion = new BABYLON.Quaternion();
  48886. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  48887. this._tmpDeltaRotation = new BABYLON.Quaternion();
  48888. this._tmpUnityRotation = new BABYLON.Quaternion();
  48889. if (!this.isSupported()) {
  48890. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  48891. return;
  48892. }
  48893. this.world = new CANNON.World();
  48894. this.world.broadphase = new CANNON.NaiveBroadphase();
  48895. this.world.solver.iterations = iterations;
  48896. }
  48897. CannonJSPlugin.prototype.setGravity = function (gravity) {
  48898. this.world.gravity.copy(gravity);
  48899. };
  48900. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  48901. this._fixedTimeStep = timeStep;
  48902. };
  48903. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  48904. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  48905. };
  48906. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  48907. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  48908. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  48909. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  48910. };
  48911. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  48912. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  48913. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  48914. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  48915. };
  48916. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  48917. //parent-child relationship. Does this impostor has a parent impostor?
  48918. if (impostor.parent) {
  48919. if (impostor.physicsBody) {
  48920. this.removePhysicsBody(impostor);
  48921. //TODO is that needed?
  48922. impostor.forceUpdate();
  48923. }
  48924. return;
  48925. }
  48926. //should a new body be created for this impostor?
  48927. if (impostor.isBodyInitRequired()) {
  48928. var shape = this._createShape(impostor);
  48929. //unregister events, if body is being changed
  48930. var oldBody = impostor.physicsBody;
  48931. if (oldBody) {
  48932. this.removePhysicsBody(impostor);
  48933. }
  48934. //create the body and material
  48935. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  48936. var bodyCreationObject = {
  48937. mass: impostor.getParam("mass"),
  48938. material: material
  48939. };
  48940. // A simple extend, in case native options were used.
  48941. var nativeOptions = impostor.getParam("nativeOptions");
  48942. for (var key in nativeOptions) {
  48943. if (nativeOptions.hasOwnProperty(key)) {
  48944. bodyCreationObject[key] = nativeOptions[key];
  48945. }
  48946. }
  48947. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  48948. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  48949. this.world.addEventListener("preStep", impostor.beforeStep);
  48950. this.world.addEventListener("postStep", impostor.afterStep);
  48951. impostor.physicsBody.addShape(shape);
  48952. this.world.add(impostor.physicsBody);
  48953. //try to keep the body moving in the right direction by taking old properties.
  48954. //Should be tested!
  48955. if (oldBody) {
  48956. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  48957. impostor.physicsBody[param].copy(oldBody[param]);
  48958. });
  48959. }
  48960. this._processChildMeshes(impostor);
  48961. }
  48962. //now update the body's transformation
  48963. this._updatePhysicsBodyTransformation(impostor);
  48964. };
  48965. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  48966. var _this = this;
  48967. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  48968. if (meshChildren.length) {
  48969. var processMesh = function (localPosition, mesh) {
  48970. var childImpostor = mesh.getPhysicsImpostor();
  48971. if (childImpostor) {
  48972. var parent = childImpostor.parent;
  48973. if (parent !== mainImpostor) {
  48974. var localPosition = mesh.position;
  48975. if (childImpostor.physicsBody) {
  48976. _this.removePhysicsBody(childImpostor);
  48977. childImpostor.physicsBody = null;
  48978. }
  48979. childImpostor.parent = mainImpostor;
  48980. childImpostor.resetUpdateFlags();
  48981. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  48982. //Add the mass of the children.
  48983. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  48984. }
  48985. }
  48986. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  48987. };
  48988. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  48989. }
  48990. };
  48991. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  48992. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  48993. this.world.removeEventListener("preStep", impostor.beforeStep);
  48994. this.world.removeEventListener("postStep", impostor.afterStep);
  48995. this.world.remove(impostor.physicsBody);
  48996. };
  48997. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  48998. var mainBody = impostorJoint.mainImpostor.physicsBody;
  48999. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  49000. if (!mainBody || !connectedBody) {
  49001. return;
  49002. }
  49003. var constraint;
  49004. var jointData = impostorJoint.joint.jointData;
  49005. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  49006. var constraintData = {
  49007. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  49008. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  49009. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  49010. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  49011. maxForce: jointData.nativeParams.maxForce,
  49012. collideConnected: !!jointData.collision
  49013. };
  49014. //Not needed, Cannon has a collideConnected flag
  49015. /*if (!jointData.collision) {
  49016. //add 1st body to a collision group of its own, if it is not in 1
  49017. if (mainBody.collisionFilterGroup === 1) {
  49018. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  49019. this._currentCollisionGroup <<= 1;
  49020. }
  49021. if (connectedBody.collisionFilterGroup === 1) {
  49022. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  49023. this._currentCollisionGroup <<= 1;
  49024. }
  49025. //add their mask to the collisionFilterMask of each other:
  49026. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  49027. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  49028. }*/
  49029. switch (impostorJoint.joint.type) {
  49030. case BABYLON.PhysicsJoint.HingeJoint:
  49031. case BABYLON.PhysicsJoint.Hinge2Joint:
  49032. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  49033. break;
  49034. case BABYLON.PhysicsJoint.DistanceJoint:
  49035. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  49036. break;
  49037. case BABYLON.PhysicsJoint.SpringJoint:
  49038. var springData = jointData;
  49039. constraint = new CANNON.Spring(mainBody, connectedBody, {
  49040. restLength: springData.length,
  49041. stiffness: springData.stiffness,
  49042. damping: springData.damping,
  49043. localAnchorA: constraintData.pivotA,
  49044. localAnchorB: constraintData.pivotB
  49045. });
  49046. break;
  49047. case BABYLON.PhysicsJoint.LockJoint:
  49048. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  49049. break;
  49050. case BABYLON.PhysicsJoint.PointToPointJoint:
  49051. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  49052. default:
  49053. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  49054. break;
  49055. }
  49056. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  49057. constraint.collideConnected = !!jointData.collision;
  49058. impostorJoint.joint.physicsJoint = constraint;
  49059. //don't add spring as constraint, as it is not one.
  49060. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  49061. this.world.addConstraint(constraint);
  49062. }
  49063. else {
  49064. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  49065. constraint.applyForce();
  49066. });
  49067. }
  49068. };
  49069. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  49070. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  49071. };
  49072. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  49073. var index;
  49074. var mat;
  49075. for (index = 0; index < this._physicsMaterials.length; index++) {
  49076. mat = this._physicsMaterials[index];
  49077. if (mat.friction === friction && mat.restitution === restitution) {
  49078. return mat;
  49079. }
  49080. }
  49081. var currentMat = new CANNON.Material(name);
  49082. currentMat.friction = friction;
  49083. currentMat.restitution = restitution;
  49084. this._physicsMaterials.push(currentMat);
  49085. return currentMat;
  49086. };
  49087. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  49088. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  49089. };
  49090. CannonJSPlugin.prototype._createShape = function (impostor) {
  49091. var object = impostor.object;
  49092. var returnValue;
  49093. var extendSize = impostor.getObjectExtendSize();
  49094. switch (impostor.type) {
  49095. case BABYLON.PhysicsEngine.SphereImpostor:
  49096. var radiusX = extendSize.x;
  49097. var radiusY = extendSize.y;
  49098. var radiusZ = extendSize.z;
  49099. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  49100. break;
  49101. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  49102. case BABYLON.PhysicsImpostor.CylinderImpostor:
  49103. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  49104. break;
  49105. case BABYLON.PhysicsImpostor.BoxImpostor:
  49106. var box = extendSize.scale(0.5);
  49107. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  49108. break;
  49109. case BABYLON.PhysicsImpostor.PlaneImpostor:
  49110. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  49111. returnValue = new CANNON.Plane();
  49112. break;
  49113. case BABYLON.PhysicsImpostor.MeshImpostor:
  49114. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  49115. var rawFaces = object.getIndices ? object.getIndices() : [];
  49116. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  49117. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  49118. break;
  49119. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  49120. returnValue = this._createHeightmap(object);
  49121. break;
  49122. case BABYLON.PhysicsImpostor.ParticleImpostor:
  49123. returnValue = new CANNON.Particle();
  49124. break;
  49125. }
  49126. return returnValue;
  49127. };
  49128. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  49129. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49130. var matrix = [];
  49131. //For now pointDepth will not be used and will be automatically calculated.
  49132. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  49133. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  49134. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  49135. var elementSize = dim * 2 / arraySize;
  49136. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  49137. for (var i = 0; i < pos.length; i = i + 3) {
  49138. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  49139. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  49140. var y = pos[i + 1] + minY;
  49141. if (!matrix[x]) {
  49142. matrix[x] = [];
  49143. }
  49144. if (!matrix[x][z]) {
  49145. matrix[x][z] = y;
  49146. }
  49147. matrix[x][z] = Math.max(y, matrix[x][z]);
  49148. }
  49149. for (var x = 0; x <= arraySize; ++x) {
  49150. if (!matrix[x]) {
  49151. var loc = 1;
  49152. while (!matrix[(x + loc) % arraySize]) {
  49153. loc++;
  49154. }
  49155. matrix[x] = matrix[(x + loc) % arraySize].slice();
  49156. }
  49157. for (var z = 0; z <= arraySize; ++z) {
  49158. if (!matrix[x][z]) {
  49159. var loc = 1;
  49160. var newValue;
  49161. while (newValue === undefined) {
  49162. newValue = matrix[x][(z + loc++) % arraySize];
  49163. }
  49164. matrix[x][z] = newValue;
  49165. }
  49166. }
  49167. }
  49168. var shape = new CANNON.Heightfield(matrix, {
  49169. elementSize: elementSize
  49170. });
  49171. //For future reference, needed for body transformation
  49172. shape.minY = minY;
  49173. return shape;
  49174. };
  49175. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  49176. var object = impostor.object;
  49177. //make sure it is updated...
  49178. object.computeWorldMatrix && object.computeWorldMatrix(true);
  49179. // The delta between the mesh position and the mesh bounding box center
  49180. var center = impostor.getObjectCenter();
  49181. var extendSize = impostor.getObjectExtendSize();
  49182. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  49183. this._tmpPosition.copyFrom(center);
  49184. var quaternion = object.rotationQuaternion;
  49185. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  49186. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  49187. //-90 DEG in X, precalculated
  49188. quaternion = quaternion.multiply(this._minus90X);
  49189. //Invert! (Precalculated, 90 deg in X)
  49190. //No need to clone. this will never change.
  49191. impostor.setDeltaRotation(this._plus90X);
  49192. }
  49193. //If it is a heightfield, if should be centered.
  49194. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  49195. var mesh = object;
  49196. //calculate the correct body position:
  49197. var rotationQuaternion = mesh.rotationQuaternion;
  49198. mesh.rotationQuaternion = this._tmpUnityRotation;
  49199. mesh.computeWorldMatrix(true);
  49200. //get original center with no rotation
  49201. var c = center.clone();
  49202. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  49203. //rotation is back
  49204. mesh.rotationQuaternion = rotationQuaternion;
  49205. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  49206. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  49207. mesh.setPivotMatrix(p);
  49208. mesh.computeWorldMatrix(true);
  49209. //calculate the translation
  49210. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  49211. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  49212. //add it inverted to the delta
  49213. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  49214. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  49215. mesh.setPivotMatrix(oldPivot);
  49216. mesh.computeWorldMatrix(true);
  49217. }
  49218. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  49219. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  49220. this._tmpPosition.copyFrom(object.position);
  49221. }
  49222. impostor.setDeltaPosition(this._tmpDeltaPosition);
  49223. //Now update the impostor object
  49224. impostor.physicsBody.position.copy(this._tmpPosition);
  49225. impostor.physicsBody.quaternion.copy(quaternion);
  49226. };
  49227. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  49228. impostor.object.position.copyFrom(impostor.physicsBody.position);
  49229. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  49230. };
  49231. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  49232. impostor.physicsBody.position.copy(newPosition);
  49233. impostor.physicsBody.quaternion.copy(newRotation);
  49234. };
  49235. CannonJSPlugin.prototype.isSupported = function () {
  49236. return window.CANNON !== undefined;
  49237. };
  49238. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  49239. impostor.physicsBody.velocity.copy(velocity);
  49240. };
  49241. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  49242. impostor.physicsBody.angularVelocity.copy(velocity);
  49243. };
  49244. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  49245. var v = impostor.physicsBody.velocity;
  49246. if (!v)
  49247. return null;
  49248. return new BABYLON.Vector3(v.x, v.y, v.z);
  49249. };
  49250. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  49251. var v = impostor.physicsBody.angularVelocity;
  49252. if (!v)
  49253. return null;
  49254. return new BABYLON.Vector3(v.x, v.y, v.z);
  49255. };
  49256. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  49257. impostor.physicsBody.mass = mass;
  49258. impostor.physicsBody.updateMassProperties();
  49259. };
  49260. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  49261. impostor.physicsBody.sleep();
  49262. };
  49263. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  49264. impostor.physicsBody.wakeUp();
  49265. };
  49266. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  49267. joint.physicsJoint.distance = maxDistance;
  49268. };
  49269. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  49270. if (!motorIndex) {
  49271. joint.physicsJoint.enableMotor();
  49272. }
  49273. };
  49274. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  49275. if (!motorIndex) {
  49276. joint.physicsJoint.disableMotor();
  49277. }
  49278. };
  49279. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  49280. if (!motorIndex) {
  49281. joint.physicsJoint.enableMotor();
  49282. joint.physicsJoint.setMotorSpeed(speed);
  49283. if (maxForce) {
  49284. this.setLimit(joint, maxForce);
  49285. }
  49286. }
  49287. };
  49288. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  49289. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  49290. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  49291. };
  49292. CannonJSPlugin.prototype.dispose = function () {
  49293. //nothing to do, actually.
  49294. };
  49295. return CannonJSPlugin;
  49296. })();
  49297. BABYLON.CannonJSPlugin = CannonJSPlugin;
  49298. })(BABYLON || (BABYLON = {}));
  49299. var BABYLON;
  49300. (function (BABYLON) {
  49301. var OimoJSPlugin = (function () {
  49302. function OimoJSPlugin(iterations) {
  49303. this.name = "OimoJSPlugin";
  49304. this._tmpImpostorsArray = [];
  49305. this._tmpPositionVector = BABYLON.Vector3.Zero();
  49306. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  49307. this.world.clear();
  49308. //making sure no stats are calculated
  49309. this.world.isNoStat = true;
  49310. }
  49311. OimoJSPlugin.prototype.setGravity = function (gravity) {
  49312. this.world.gravity.copy(gravity);
  49313. };
  49314. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  49315. this.world.timeStep = timeStep;
  49316. };
  49317. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  49318. var _this = this;
  49319. impostors.forEach(function (impostor) {
  49320. impostor.beforeStep();
  49321. });
  49322. this.world.step();
  49323. impostors.forEach(function (impostor) {
  49324. impostor.afterStep();
  49325. //update the ordered impostors array
  49326. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  49327. });
  49328. //check for collisions
  49329. var contact = this.world.contacts;
  49330. while (contact !== null) {
  49331. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  49332. contact = contact.next;
  49333. continue;
  49334. }
  49335. //is this body colliding with any other? get the impostor
  49336. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  49337. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  49338. if (!mainImpostor || !collidingImpostor) {
  49339. contact = contact.next;
  49340. continue;
  49341. }
  49342. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  49343. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  49344. contact = contact.next;
  49345. }
  49346. };
  49347. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  49348. var mass = impostor.physicsBody.massInfo.mass;
  49349. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  49350. };
  49351. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  49352. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  49353. this.applyImpulse(impostor, force, contactPoint);
  49354. };
  49355. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  49356. var _this = this;
  49357. //parent-child relationship. Does this impostor has a parent impostor?
  49358. if (impostor.parent) {
  49359. if (impostor.physicsBody) {
  49360. this.removePhysicsBody(impostor);
  49361. //TODO is that needed?
  49362. impostor.forceUpdate();
  49363. }
  49364. return;
  49365. }
  49366. if (impostor.isBodyInitRequired()) {
  49367. var bodyConfig = {
  49368. name: impostor.uniqueId,
  49369. //Oimo must have mass, also for static objects.
  49370. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  49371. size: [],
  49372. type: [],
  49373. pos: [],
  49374. rot: [],
  49375. move: impostor.getParam("mass") !== 0,
  49376. //Supporting older versions of Oimo
  49377. world: this.world
  49378. };
  49379. var impostors = [impostor];
  49380. function addToArray(parent) {
  49381. if (!parent.getChildMeshes)
  49382. return;
  49383. parent.getChildMeshes().forEach(function (m) {
  49384. if (m.physicsImpostor) {
  49385. impostors.push(m.physicsImpostor);
  49386. m.physicsImpostor._init();
  49387. }
  49388. });
  49389. }
  49390. addToArray(impostor.object);
  49391. function checkWithEpsilon(value) {
  49392. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  49393. }
  49394. impostors.forEach(function (i) {
  49395. //get the correct bounding box
  49396. var oldQuaternion = i.object.rotationQuaternion;
  49397. var rot = new OIMO.Euler().setFromQuaternion({
  49398. x: impostor.object.rotationQuaternion.x,
  49399. y: impostor.object.rotationQuaternion.y,
  49400. z: impostor.object.rotationQuaternion.z,
  49401. s: impostor.object.rotationQuaternion.w
  49402. });
  49403. var extendSize = i.getObjectExtendSize();
  49404. if (i === impostor) {
  49405. var center = impostor.getObjectCenter();
  49406. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  49407. //Can also use Array.prototype.push.apply
  49408. bodyConfig.pos.push(center.x);
  49409. bodyConfig.pos.push(center.y);
  49410. bodyConfig.pos.push(center.z);
  49411. //tmp solution
  49412. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  49413. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  49414. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  49415. }
  49416. else {
  49417. bodyConfig.pos.push(i.object.position.x);
  49418. bodyConfig.pos.push(i.object.position.y);
  49419. bodyConfig.pos.push(i.object.position.z);
  49420. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  49421. bodyConfig.rot.push(0);
  49422. bodyConfig.rot.push(0);
  49423. bodyConfig.rot.push(0);
  49424. }
  49425. // register mesh
  49426. switch (i.type) {
  49427. case BABYLON.PhysicsImpostor.ParticleImpostor:
  49428. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  49429. case BABYLON.PhysicsImpostor.SphereImpostor:
  49430. var radiusX = extendSize.x;
  49431. var radiusY = extendSize.y;
  49432. var radiusZ = extendSize.z;
  49433. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  49434. bodyConfig.type.push('sphere');
  49435. //due to the way oimo works with compounds, add 3 times
  49436. bodyConfig.size.push(size);
  49437. bodyConfig.size.push(size);
  49438. bodyConfig.size.push(size);
  49439. break;
  49440. case BABYLON.PhysicsImpostor.CylinderImpostor:
  49441. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  49442. var sizeY = checkWithEpsilon(extendSize.y);
  49443. bodyConfig.type.push('cylinder');
  49444. bodyConfig.size.push(sizeX);
  49445. bodyConfig.size.push(sizeY);
  49446. //due to the way oimo works with compounds, add one more value.
  49447. bodyConfig.size.push(sizeY);
  49448. break;
  49449. case BABYLON.PhysicsImpostor.PlaneImpostor:
  49450. case BABYLON.PhysicsImpostor.BoxImpostor:
  49451. default:
  49452. var sizeX = checkWithEpsilon(extendSize.x);
  49453. var sizeY = checkWithEpsilon(extendSize.y);
  49454. var sizeZ = checkWithEpsilon(extendSize.z);
  49455. bodyConfig.type.push('box');
  49456. bodyConfig.size.push(sizeX);
  49457. bodyConfig.size.push(sizeY);
  49458. bodyConfig.size.push(sizeZ);
  49459. break;
  49460. }
  49461. //actually not needed, but hey...
  49462. i.object.rotationQuaternion = oldQuaternion;
  49463. });
  49464. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  49465. }
  49466. else {
  49467. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  49468. }
  49469. impostor.setDeltaPosition(this._tmpPositionVector);
  49470. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  49471. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  49472. };
  49473. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  49474. //impostor.physicsBody.dispose();
  49475. //Same as : (older oimo versions)
  49476. this.world.removeRigidBody(impostor.physicsBody);
  49477. };
  49478. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  49479. var mainBody = impostorJoint.mainImpostor.physicsBody;
  49480. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  49481. if (!mainBody || !connectedBody) {
  49482. return;
  49483. }
  49484. var jointData = impostorJoint.joint.jointData;
  49485. var options = jointData.nativeParams || {};
  49486. var type;
  49487. var nativeJointData = {
  49488. body1: mainBody,
  49489. body2: connectedBody,
  49490. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  49491. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  49492. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  49493. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  49494. min: options.min,
  49495. max: options.max,
  49496. collision: options.collision || jointData.collision,
  49497. spring: options.spring,
  49498. //supporting older version of Oimo
  49499. world: this.world
  49500. };
  49501. switch (impostorJoint.joint.type) {
  49502. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  49503. type = "jointBall";
  49504. break;
  49505. case BABYLON.PhysicsJoint.SpringJoint:
  49506. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  49507. var springData = jointData;
  49508. nativeJointData.min = springData.length || nativeJointData.min;
  49509. //Max should also be set, just make sure it is at least min
  49510. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  49511. case BABYLON.PhysicsJoint.DistanceJoint:
  49512. type = "jointDistance";
  49513. nativeJointData.max = jointData.maxDistance;
  49514. break;
  49515. case BABYLON.PhysicsJoint.PrismaticJoint:
  49516. type = "jointPrisme";
  49517. break;
  49518. case BABYLON.PhysicsJoint.SliderJoint:
  49519. type = "jointSlide";
  49520. break;
  49521. case BABYLON.PhysicsJoint.WheelJoint:
  49522. type = "jointWheel";
  49523. break;
  49524. case BABYLON.PhysicsJoint.HingeJoint:
  49525. default:
  49526. type = "jointHinge";
  49527. break;
  49528. }
  49529. nativeJointData.type = type;
  49530. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  49531. };
  49532. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  49533. //Bug in Oimo prevents us from disposing a joint in the playground
  49534. //joint.joint.physicsJoint.dispose();
  49535. //So we will bruteforce it!
  49536. try {
  49537. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  49538. }
  49539. catch (e) {
  49540. BABYLON.Tools.Warn(e);
  49541. }
  49542. };
  49543. OimoJSPlugin.prototype.isSupported = function () {
  49544. return OIMO !== undefined;
  49545. };
  49546. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  49547. if (!impostor.physicsBody.sleeping) {
  49548. //TODO check that
  49549. if (impostor.physicsBody.shapes.next) {
  49550. var parentShape = this._getLastShape(impostor.physicsBody);
  49551. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  49552. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  49553. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  49554. }
  49555. else {
  49556. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  49557. }
  49558. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  49559. impostor.object.rotationQuaternion.normalize();
  49560. }
  49561. };
  49562. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  49563. var body = impostor.physicsBody;
  49564. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  49565. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  49566. body.syncShapes();
  49567. body.awake();
  49568. };
  49569. OimoJSPlugin.prototype._getLastShape = function (body) {
  49570. var lastShape = body.shapes;
  49571. while (lastShape.next) {
  49572. lastShape = lastShape.next;
  49573. }
  49574. return lastShape;
  49575. };
  49576. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  49577. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  49578. };
  49579. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  49580. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  49581. };
  49582. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  49583. var v = impostor.physicsBody.linearVelocity;
  49584. if (!v)
  49585. return null;
  49586. return new BABYLON.Vector3(v.x, v.y, v.z);
  49587. };
  49588. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  49589. var v = impostor.physicsBody.angularVelocity;
  49590. if (!v)
  49591. return null;
  49592. return new BABYLON.Vector3(v.x, v.y, v.z);
  49593. };
  49594. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  49595. var staticBody = mass === 0;
  49596. //this will actually set the body's density and not its mass.
  49597. //But this is how oimo treats the mass variable.
  49598. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  49599. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  49600. };
  49601. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  49602. impostor.physicsBody.sleep();
  49603. };
  49604. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  49605. impostor.physicsBody.awake();
  49606. };
  49607. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  49608. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  49609. if (minDistance !== void 0) {
  49610. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  49611. }
  49612. };
  49613. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  49614. //TODO separate rotational and transational motors.
  49615. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  49616. if (motor) {
  49617. motor.setMotor(speed, maxForce);
  49618. }
  49619. };
  49620. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  49621. //TODO separate rotational and transational motors.
  49622. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  49623. if (motor) {
  49624. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  49625. }
  49626. };
  49627. OimoJSPlugin.prototype.dispose = function () {
  49628. this.world.clear();
  49629. };
  49630. return OimoJSPlugin;
  49631. })();
  49632. BABYLON.OimoJSPlugin = OimoJSPlugin;
  49633. })(BABYLON || (BABYLON = {}));
  49634. var BABYLON;
  49635. (function (BABYLON) {
  49636. var DisplayPassPostProcess = (function (_super) {
  49637. __extends(DisplayPassPostProcess, _super);
  49638. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  49639. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  49640. }
  49641. return DisplayPassPostProcess;
  49642. })(BABYLON.PostProcess);
  49643. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  49644. })(BABYLON || (BABYLON = {}));
  49645. var BABYLON;
  49646. (function (BABYLON) {
  49647. var SimplificationSettings = (function () {
  49648. function SimplificationSettings(quality, distance, optimizeMesh) {
  49649. this.quality = quality;
  49650. this.distance = distance;
  49651. this.optimizeMesh = optimizeMesh;
  49652. }
  49653. return SimplificationSettings;
  49654. })();
  49655. BABYLON.SimplificationSettings = SimplificationSettings;
  49656. var SimplificationQueue = (function () {
  49657. function SimplificationQueue() {
  49658. this.running = false;
  49659. this._simplificationArray = [];
  49660. }
  49661. SimplificationQueue.prototype.addTask = function (task) {
  49662. this._simplificationArray.push(task);
  49663. };
  49664. SimplificationQueue.prototype.executeNext = function () {
  49665. var task = this._simplificationArray.pop();
  49666. if (task) {
  49667. this.running = true;
  49668. this.runSimplification(task);
  49669. }
  49670. else {
  49671. this.running = false;
  49672. }
  49673. };
  49674. SimplificationQueue.prototype.runSimplification = function (task) {
  49675. var _this = this;
  49676. if (task.parallelProcessing) {
  49677. //parallel simplifier
  49678. task.settings.forEach(function (setting) {
  49679. var simplifier = _this.getSimplifier(task);
  49680. simplifier.simplify(setting, function (newMesh) {
  49681. task.mesh.addLODLevel(setting.distance, newMesh);
  49682. newMesh.isVisible = true;
  49683. //check if it is the last
  49684. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  49685. //all done, run the success callback.
  49686. task.successCallback();
  49687. }
  49688. _this.executeNext();
  49689. });
  49690. });
  49691. }
  49692. else {
  49693. //single simplifier.
  49694. var simplifier = this.getSimplifier(task);
  49695. var runDecimation = function (setting, callback) {
  49696. simplifier.simplify(setting, function (newMesh) {
  49697. task.mesh.addLODLevel(setting.distance, newMesh);
  49698. newMesh.isVisible = true;
  49699. //run the next quality level
  49700. callback();
  49701. });
  49702. };
  49703. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  49704. runDecimation(task.settings[loop.index], function () {
  49705. loop.executeNext();
  49706. });
  49707. }, function () {
  49708. //execution ended, run the success callback.
  49709. if (task.successCallback) {
  49710. task.successCallback();
  49711. }
  49712. _this.executeNext();
  49713. });
  49714. }
  49715. };
  49716. SimplificationQueue.prototype.getSimplifier = function (task) {
  49717. switch (task.simplificationType) {
  49718. case SimplificationType.QUADRATIC:
  49719. default:
  49720. return new QuadraticErrorSimplification(task.mesh);
  49721. }
  49722. };
  49723. return SimplificationQueue;
  49724. })();
  49725. BABYLON.SimplificationQueue = SimplificationQueue;
  49726. /**
  49727. * The implemented types of simplification.
  49728. * At the moment only Quadratic Error Decimation is implemented.
  49729. */
  49730. (function (SimplificationType) {
  49731. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  49732. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  49733. var SimplificationType = BABYLON.SimplificationType;
  49734. var DecimationTriangle = (function () {
  49735. function DecimationTriangle(vertices) {
  49736. this.vertices = vertices;
  49737. this.error = new Array(4);
  49738. this.deleted = false;
  49739. this.isDirty = false;
  49740. this.deletePending = false;
  49741. this.borderFactor = 0;
  49742. }
  49743. return DecimationTriangle;
  49744. })();
  49745. BABYLON.DecimationTriangle = DecimationTriangle;
  49746. var DecimationVertex = (function () {
  49747. function DecimationVertex(position, id) {
  49748. this.position = position;
  49749. this.id = id;
  49750. this.isBorder = true;
  49751. this.q = new QuadraticMatrix();
  49752. this.triangleCount = 0;
  49753. this.triangleStart = 0;
  49754. this.originalOffsets = [];
  49755. }
  49756. DecimationVertex.prototype.updatePosition = function (newPosition) {
  49757. this.position.copyFrom(newPosition);
  49758. };
  49759. return DecimationVertex;
  49760. })();
  49761. BABYLON.DecimationVertex = DecimationVertex;
  49762. var QuadraticMatrix = (function () {
  49763. function QuadraticMatrix(data) {
  49764. this.data = new Array(10);
  49765. for (var i = 0; i < 10; ++i) {
  49766. if (data && data[i]) {
  49767. this.data[i] = data[i];
  49768. }
  49769. else {
  49770. this.data[i] = 0;
  49771. }
  49772. }
  49773. }
  49774. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  49775. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  49776. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  49777. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  49778. return det;
  49779. };
  49780. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  49781. for (var i = 0; i < 10; ++i) {
  49782. this.data[i] += matrix.data[i];
  49783. }
  49784. };
  49785. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  49786. for (var i = 0; i < 10; ++i) {
  49787. this.data[i] += data[i];
  49788. }
  49789. };
  49790. QuadraticMatrix.prototype.add = function (matrix) {
  49791. var m = new QuadraticMatrix();
  49792. for (var i = 0; i < 10; ++i) {
  49793. m.data[i] = this.data[i] + matrix.data[i];
  49794. }
  49795. return m;
  49796. };
  49797. QuadraticMatrix.FromData = function (a, b, c, d) {
  49798. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  49799. };
  49800. //returning an array to avoid garbage collection
  49801. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  49802. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  49803. };
  49804. return QuadraticMatrix;
  49805. })();
  49806. BABYLON.QuadraticMatrix = QuadraticMatrix;
  49807. var Reference = (function () {
  49808. function Reference(vertexId, triangleId) {
  49809. this.vertexId = vertexId;
  49810. this.triangleId = triangleId;
  49811. }
  49812. return Reference;
  49813. })();
  49814. BABYLON.Reference = Reference;
  49815. /**
  49816. * An implementation of the Quadratic Error simplification algorithm.
  49817. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  49818. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  49819. * @author RaananW
  49820. */
  49821. var QuadraticErrorSimplification = (function () {
  49822. function QuadraticErrorSimplification(_mesh) {
  49823. this._mesh = _mesh;
  49824. this.initialized = false;
  49825. this.syncIterations = 5000;
  49826. this.aggressiveness = 7;
  49827. this.decimationIterations = 100;
  49828. this.boundingBoxEpsilon = BABYLON.Epsilon;
  49829. }
  49830. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  49831. var _this = this;
  49832. this.initDecimatedMesh();
  49833. //iterating through the submeshes array, one after the other.
  49834. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  49835. _this.initWithMesh(loop.index, function () {
  49836. _this.runDecimation(settings, loop.index, function () {
  49837. loop.executeNext();
  49838. });
  49839. }, settings.optimizeMesh);
  49840. }, function () {
  49841. setTimeout(function () {
  49842. successCallback(_this._reconstructedMesh);
  49843. }, 0);
  49844. });
  49845. };
  49846. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  49847. var _this = this;
  49848. var gCount = 0;
  49849. triangle.vertices.forEach(function (vertex) {
  49850. var count = 0;
  49851. var vPos = vertex.position;
  49852. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  49853. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  49854. ++count;
  49855. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  49856. ++count;
  49857. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  49858. ++count;
  49859. if (count > 1) {
  49860. ++gCount;
  49861. }
  49862. ;
  49863. });
  49864. if (gCount > 1) {
  49865. console.log(triangle, gCount);
  49866. }
  49867. return gCount > 1;
  49868. };
  49869. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  49870. var _this = this;
  49871. var targetCount = ~~(this.triangles.length * settings.quality);
  49872. var deletedTriangles = 0;
  49873. var triangleCount = this.triangles.length;
  49874. var iterationFunction = function (iteration, callback) {
  49875. setTimeout(function () {
  49876. if (iteration % 5 === 0) {
  49877. _this.updateMesh(iteration === 0);
  49878. }
  49879. for (var i = 0; i < _this.triangles.length; ++i) {
  49880. _this.triangles[i].isDirty = false;
  49881. }
  49882. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  49883. var trianglesIterator = function (i) {
  49884. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  49885. var t = _this.triangles[tIdx];
  49886. if (!t)
  49887. return;
  49888. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  49889. return;
  49890. }
  49891. for (var j = 0; j < 3; ++j) {
  49892. if (t.error[j] < threshold) {
  49893. var deleted0 = [];
  49894. var deleted1 = [];
  49895. var v0 = t.vertices[j];
  49896. var v1 = t.vertices[(j + 1) % 3];
  49897. if (v0.isBorder || v1.isBorder)
  49898. continue;
  49899. var p = BABYLON.Vector3.Zero();
  49900. var n = BABYLON.Vector3.Zero();
  49901. var uv = BABYLON.Vector2.Zero();
  49902. var color = new BABYLON.Color4(0, 0, 0, 1);
  49903. _this.calculateError(v0, v1, p, n, uv, color);
  49904. var delTr = [];
  49905. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  49906. continue;
  49907. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  49908. continue;
  49909. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  49910. continue;
  49911. var uniqueArray = [];
  49912. delTr.forEach(function (deletedT) {
  49913. if (uniqueArray.indexOf(deletedT) === -1) {
  49914. deletedT.deletePending = true;
  49915. uniqueArray.push(deletedT);
  49916. }
  49917. });
  49918. if (uniqueArray.length % 2 !== 0) {
  49919. continue;
  49920. }
  49921. v0.q = v1.q.add(v0.q);
  49922. v0.updatePosition(p);
  49923. var tStart = _this.references.length;
  49924. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  49925. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  49926. var tCount = _this.references.length - tStart;
  49927. if (tCount <= v0.triangleCount) {
  49928. if (tCount) {
  49929. for (var c = 0; c < tCount; c++) {
  49930. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  49931. }
  49932. }
  49933. }
  49934. else {
  49935. v0.triangleStart = tStart;
  49936. }
  49937. v0.triangleCount = tCount;
  49938. break;
  49939. }
  49940. }
  49941. };
  49942. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  49943. }, 0);
  49944. };
  49945. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  49946. if (triangleCount - deletedTriangles <= targetCount)
  49947. loop.breakLoop();
  49948. else {
  49949. iterationFunction(loop.index, function () {
  49950. loop.executeNext();
  49951. });
  49952. }
  49953. }, function () {
  49954. setTimeout(function () {
  49955. //reconstruct this part of the mesh
  49956. _this.reconstructMesh(submeshIndex);
  49957. successCallback();
  49958. }, 0);
  49959. });
  49960. };
  49961. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  49962. var _this = this;
  49963. this.vertices = [];
  49964. this.triangles = [];
  49965. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49966. var indices = this._mesh.getIndices();
  49967. var submesh = this._mesh.subMeshes[submeshIndex];
  49968. var findInVertices = function (positionToSearch) {
  49969. if (optimizeMesh) {
  49970. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  49971. if (_this.vertices[ii].position.equals(positionToSearch)) {
  49972. return _this.vertices[ii];
  49973. }
  49974. }
  49975. }
  49976. return null;
  49977. };
  49978. var vertexReferences = [];
  49979. var vertexInit = function (i) {
  49980. var offset = i + submesh.verticesStart;
  49981. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  49982. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  49983. vertex.originalOffsets.push(offset);
  49984. if (vertex.id === _this.vertices.length) {
  49985. _this.vertices.push(vertex);
  49986. }
  49987. vertexReferences.push(vertex.id);
  49988. };
  49989. //var totalVertices = mesh.getTotalVertices();
  49990. var totalVertices = submesh.verticesCount;
  49991. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  49992. var indicesInit = function (i) {
  49993. var offset = (submesh.indexStart / 3) + i;
  49994. var pos = (offset * 3);
  49995. var i0 = indices[pos + 0];
  49996. var i1 = indices[pos + 1];
  49997. var i2 = indices[pos + 2];
  49998. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  49999. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  50000. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  50001. var triangle = new DecimationTriangle([v0, v1, v2]);
  50002. triangle.originalOffset = pos;
  50003. _this.triangles.push(triangle);
  50004. };
  50005. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  50006. _this.init(callback);
  50007. });
  50008. });
  50009. };
  50010. QuadraticErrorSimplification.prototype.init = function (callback) {
  50011. var _this = this;
  50012. var triangleInit1 = function (i) {
  50013. var t = _this.triangles[i];
  50014. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  50015. for (var j = 0; j < 3; j++) {
  50016. 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))));
  50017. }
  50018. };
  50019. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  50020. var triangleInit2 = function (i) {
  50021. var t = _this.triangles[i];
  50022. for (var j = 0; j < 3; ++j) {
  50023. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  50024. }
  50025. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  50026. };
  50027. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  50028. _this.initialized = true;
  50029. callback();
  50030. });
  50031. });
  50032. };
  50033. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  50034. var newTriangles = [];
  50035. var i;
  50036. for (i = 0; i < this.vertices.length; ++i) {
  50037. this.vertices[i].triangleCount = 0;
  50038. }
  50039. var t;
  50040. var j;
  50041. for (i = 0; i < this.triangles.length; ++i) {
  50042. if (!this.triangles[i].deleted) {
  50043. t = this.triangles[i];
  50044. for (j = 0; j < 3; ++j) {
  50045. t.vertices[j].triangleCount = 1;
  50046. }
  50047. newTriangles.push(t);
  50048. }
  50049. }
  50050. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  50051. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  50052. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  50053. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  50054. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50055. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50056. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  50057. var vertexCount = 0;
  50058. for (i = 0; i < this.vertices.length; ++i) {
  50059. var vertex = this.vertices[i];
  50060. vertex.id = vertexCount;
  50061. if (vertex.triangleCount) {
  50062. vertex.originalOffsets.forEach(function (originalOffset) {
  50063. newPositionData.push(vertex.position.x);
  50064. newPositionData.push(vertex.position.y);
  50065. newPositionData.push(vertex.position.z);
  50066. newNormalData.push(normalData[originalOffset * 3]);
  50067. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  50068. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  50069. if (uvs && uvs.length) {
  50070. newUVsData.push(uvs[(originalOffset * 2)]);
  50071. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  50072. }
  50073. else if (colorsData && colorsData.length) {
  50074. newColorsData.push(colorsData[(originalOffset * 4)]);
  50075. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  50076. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  50077. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  50078. }
  50079. ++vertexCount;
  50080. });
  50081. }
  50082. }
  50083. var startingIndex = this._reconstructedMesh.getTotalIndices();
  50084. var startingVertex = this._reconstructedMesh.getTotalVertices();
  50085. var submeshesArray = this._reconstructedMesh.subMeshes;
  50086. this._reconstructedMesh.subMeshes = [];
  50087. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  50088. var originalIndices = this._mesh.getIndices();
  50089. for (i = 0; i < newTriangles.length; ++i) {
  50090. t = newTriangles[i]; //now get the new referencing point for each vertex
  50091. [0, 1, 2].forEach(function (idx) {
  50092. var id = originalIndices[t.originalOffset + idx];
  50093. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  50094. if (offset < 0)
  50095. offset = 0;
  50096. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  50097. });
  50098. }
  50099. //overwriting the old vertex buffers and indices.
  50100. this._reconstructedMesh.setIndices(newIndicesArray);
  50101. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  50102. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  50103. if (newUVsData.length > 0)
  50104. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  50105. if (newColorsData.length > 0)
  50106. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  50107. //create submesh
  50108. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  50109. if (submeshIndex > 0) {
  50110. this._reconstructedMesh.subMeshes = [];
  50111. submeshesArray.forEach(function (submesh) {
  50112. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  50113. });
  50114. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  50115. }
  50116. };
  50117. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  50118. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  50119. this._reconstructedMesh.material = this._mesh.material;
  50120. this._reconstructedMesh.parent = this._mesh.parent;
  50121. this._reconstructedMesh.isVisible = false;
  50122. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  50123. };
  50124. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  50125. for (var i = 0; i < vertex1.triangleCount; ++i) {
  50126. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  50127. if (t.deleted)
  50128. continue;
  50129. var s = this.references[vertex1.triangleStart + i].vertexId;
  50130. var v1 = t.vertices[(s + 1) % 3];
  50131. var v2 = t.vertices[(s + 2) % 3];
  50132. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  50133. deletedArray[i] = true;
  50134. delTr.push(t);
  50135. continue;
  50136. }
  50137. var d1 = v1.position.subtract(point);
  50138. d1 = d1.normalize();
  50139. var d2 = v2.position.subtract(point);
  50140. d2 = d2.normalize();
  50141. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  50142. return true;
  50143. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  50144. deletedArray[i] = false;
  50145. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  50146. return true;
  50147. }
  50148. return false;
  50149. };
  50150. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  50151. var newDeleted = deletedTriangles;
  50152. for (var i = 0; i < vertex.triangleCount; ++i) {
  50153. var ref = this.references[vertex.triangleStart + i];
  50154. var t = this.triangles[ref.triangleId];
  50155. if (t.deleted)
  50156. continue;
  50157. if (deletedArray[i] && t.deletePending) {
  50158. t.deleted = true;
  50159. newDeleted++;
  50160. continue;
  50161. }
  50162. t.vertices[ref.vertexId] = origVertex;
  50163. t.isDirty = true;
  50164. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  50165. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  50166. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  50167. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  50168. this.references.push(ref);
  50169. }
  50170. return newDeleted;
  50171. };
  50172. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  50173. for (var i = 0; i < this.vertices.length; ++i) {
  50174. var vCount = [];
  50175. var vId = [];
  50176. var v = this.vertices[i];
  50177. var j;
  50178. for (j = 0; j < v.triangleCount; ++j) {
  50179. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  50180. for (var ii = 0; ii < 3; ii++) {
  50181. var ofs = 0;
  50182. var vv = triangle.vertices[ii];
  50183. while (ofs < vCount.length) {
  50184. if (vId[ofs] === vv.id)
  50185. break;
  50186. ++ofs;
  50187. }
  50188. if (ofs === vCount.length) {
  50189. vCount.push(1);
  50190. vId.push(vv.id);
  50191. }
  50192. else {
  50193. vCount[ofs]++;
  50194. }
  50195. }
  50196. }
  50197. for (j = 0; j < vCount.length; ++j) {
  50198. if (vCount[j] === 1) {
  50199. this.vertices[vId[j]].isBorder = true;
  50200. }
  50201. else {
  50202. this.vertices[vId[j]].isBorder = false;
  50203. }
  50204. }
  50205. }
  50206. };
  50207. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  50208. if (identifyBorders === void 0) { identifyBorders = false; }
  50209. var i;
  50210. if (!identifyBorders) {
  50211. var newTrianglesVector = [];
  50212. for (i = 0; i < this.triangles.length; ++i) {
  50213. if (!this.triangles[i].deleted) {
  50214. newTrianglesVector.push(this.triangles[i]);
  50215. }
  50216. }
  50217. this.triangles = newTrianglesVector;
  50218. }
  50219. for (i = 0; i < this.vertices.length; ++i) {
  50220. this.vertices[i].triangleCount = 0;
  50221. this.vertices[i].triangleStart = 0;
  50222. }
  50223. var t;
  50224. var j;
  50225. var v;
  50226. for (i = 0; i < this.triangles.length; ++i) {
  50227. t = this.triangles[i];
  50228. for (j = 0; j < 3; ++j) {
  50229. v = t.vertices[j];
  50230. v.triangleCount++;
  50231. }
  50232. }
  50233. var tStart = 0;
  50234. for (i = 0; i < this.vertices.length; ++i) {
  50235. this.vertices[i].triangleStart = tStart;
  50236. tStart += this.vertices[i].triangleCount;
  50237. this.vertices[i].triangleCount = 0;
  50238. }
  50239. var newReferences = new Array(this.triangles.length * 3);
  50240. for (i = 0; i < this.triangles.length; ++i) {
  50241. t = this.triangles[i];
  50242. for (j = 0; j < 3; ++j) {
  50243. v = t.vertices[j];
  50244. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  50245. v.triangleCount++;
  50246. }
  50247. }
  50248. this.references = newReferences;
  50249. if (identifyBorders) {
  50250. this.identifyBorder();
  50251. }
  50252. };
  50253. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  50254. var x = point.x;
  50255. var y = point.y;
  50256. var z = point.z;
  50257. 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
  50258. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  50259. };
  50260. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  50261. var q = vertex1.q.add(vertex2.q);
  50262. var border = vertex1.isBorder && vertex2.isBorder;
  50263. var error = 0;
  50264. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  50265. if (qDet !== 0 && !border) {
  50266. if (!pointResult) {
  50267. pointResult = BABYLON.Vector3.Zero();
  50268. }
  50269. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  50270. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  50271. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  50272. error = this.vertexError(q, pointResult);
  50273. }
  50274. else {
  50275. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  50276. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  50277. var error1 = this.vertexError(q, vertex1.position);
  50278. var error2 = this.vertexError(q, vertex2.position);
  50279. var error3 = this.vertexError(q, p3);
  50280. error = Math.min(error1, error2, error3);
  50281. if (error === error1) {
  50282. if (pointResult) {
  50283. pointResult.copyFrom(vertex1.position);
  50284. }
  50285. }
  50286. else if (error === error2) {
  50287. if (pointResult) {
  50288. pointResult.copyFrom(vertex2.position);
  50289. }
  50290. }
  50291. else {
  50292. if (pointResult) {
  50293. pointResult.copyFrom(p3);
  50294. }
  50295. }
  50296. }
  50297. return error;
  50298. };
  50299. return QuadraticErrorSimplification;
  50300. })();
  50301. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  50302. })(BABYLON || (BABYLON = {}));
  50303. var BABYLON;
  50304. (function (BABYLON) {
  50305. var serializedGeometries = [];
  50306. var serializeGeometry = function (geometry, serializationGeometries) {
  50307. if (serializedGeometries[geometry.id]) {
  50308. return;
  50309. }
  50310. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  50311. serializationGeometries.boxes.push(geometry.serialize());
  50312. }
  50313. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  50314. serializationGeometries.spheres.push(geometry.serialize());
  50315. }
  50316. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  50317. serializationGeometries.cylinders.push(geometry.serialize());
  50318. }
  50319. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  50320. serializationGeometries.toruses.push(geometry.serialize());
  50321. }
  50322. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  50323. serializationGeometries.grounds.push(geometry.serialize());
  50324. }
  50325. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  50326. serializationGeometries.planes.push(geometry.serialize());
  50327. }
  50328. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  50329. serializationGeometries.torusKnots.push(geometry.serialize());
  50330. }
  50331. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  50332. throw new Error("Unknown primitive type");
  50333. }
  50334. else {
  50335. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  50336. }
  50337. serializedGeometries[geometry.id] = true;
  50338. };
  50339. var serializeMesh = function (mesh, serializationScene) {
  50340. var serializationObject = {};
  50341. serializationObject.name = mesh.name;
  50342. serializationObject.id = mesh.id;
  50343. if (BABYLON.Tags.HasTags(mesh)) {
  50344. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  50345. }
  50346. serializationObject.position = mesh.position.asArray();
  50347. if (mesh.rotationQuaternion) {
  50348. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  50349. }
  50350. else if (mesh.rotation) {
  50351. serializationObject.rotation = mesh.rotation.asArray();
  50352. }
  50353. serializationObject.scaling = mesh.scaling.asArray();
  50354. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  50355. serializationObject.isEnabled = mesh.isEnabled();
  50356. serializationObject.isVisible = mesh.isVisible;
  50357. serializationObject.infiniteDistance = mesh.infiniteDistance;
  50358. serializationObject.pickable = mesh.isPickable;
  50359. serializationObject.receiveShadows = mesh.receiveShadows;
  50360. serializationObject.billboardMode = mesh.billboardMode;
  50361. serializationObject.visibility = mesh.visibility;
  50362. serializationObject.checkCollisions = mesh.checkCollisions;
  50363. // Parent
  50364. if (mesh.parent) {
  50365. serializationObject.parentId = mesh.parent.id;
  50366. }
  50367. // Geometry
  50368. var geometry = mesh._geometry;
  50369. if (geometry) {
  50370. var geometryId = geometry.id;
  50371. serializationObject.geometryId = geometryId;
  50372. if (!mesh.getScene().getGeometryByID(geometryId)) {
  50373. // 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
  50374. serializeGeometry(geometry, serializationScene.geometries);
  50375. }
  50376. // SubMeshes
  50377. serializationObject.subMeshes = [];
  50378. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  50379. var subMesh = mesh.subMeshes[subIndex];
  50380. serializationObject.subMeshes.push({
  50381. materialIndex: subMesh.materialIndex,
  50382. verticesStart: subMesh.verticesStart,
  50383. verticesCount: subMesh.verticesCount,
  50384. indexStart: subMesh.indexStart,
  50385. indexCount: subMesh.indexCount
  50386. });
  50387. }
  50388. }
  50389. // Material
  50390. if (mesh.material) {
  50391. serializationObject.materialId = mesh.material.id;
  50392. }
  50393. else {
  50394. mesh.material = null;
  50395. }
  50396. // Skeleton
  50397. if (mesh.skeleton) {
  50398. serializationObject.skeletonId = mesh.skeleton.id;
  50399. }
  50400. // Physics
  50401. //TODO implement correct serialization for physics impostors.
  50402. if (mesh.getPhysicsImpostor()) {
  50403. serializationObject.physicsMass = mesh.getPhysicsMass();
  50404. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  50405. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  50406. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  50407. }
  50408. // Instances
  50409. serializationObject.instances = [];
  50410. for (var index = 0; index < mesh.instances.length; index++) {
  50411. var instance = mesh.instances[index];
  50412. var serializationInstance = {
  50413. name: instance.name,
  50414. position: instance.position.asArray(),
  50415. scaling: instance.scaling.asArray()
  50416. };
  50417. if (instance.rotationQuaternion) {
  50418. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  50419. }
  50420. else if (instance.rotation) {
  50421. serializationInstance.rotation = instance.rotation.asArray();
  50422. }
  50423. serializationObject.instances.push(serializationInstance);
  50424. // Animations
  50425. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  50426. serializationInstance.ranges = instance.serializeAnimationRanges();
  50427. }
  50428. // Animations
  50429. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  50430. serializationObject.ranges = mesh.serializeAnimationRanges();
  50431. // Layer mask
  50432. serializationObject.layerMask = mesh.layerMask;
  50433. // Action Manager
  50434. if (mesh.actionManager) {
  50435. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  50436. }
  50437. return serializationObject;
  50438. };
  50439. var finalizeSingleMesh = function (mesh, serializationObject) {
  50440. //only works if the mesh is already loaded
  50441. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  50442. //serialize material
  50443. if (mesh.material) {
  50444. if (mesh.material instanceof BABYLON.StandardMaterial) {
  50445. serializationObject.materials = serializationObject.materials || [];
  50446. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  50447. serializationObject.materials.push(mesh.material.serialize());
  50448. }
  50449. }
  50450. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  50451. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  50452. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  50453. serializationObject.multiMaterials.push(mesh.material.serialize());
  50454. }
  50455. }
  50456. }
  50457. //serialize geometry
  50458. var geometry = mesh._geometry;
  50459. if (geometry) {
  50460. if (!serializationObject.geometries) {
  50461. serializationObject.geometries = {};
  50462. serializationObject.geometries.boxes = [];
  50463. serializationObject.geometries.spheres = [];
  50464. serializationObject.geometries.cylinders = [];
  50465. serializationObject.geometries.toruses = [];
  50466. serializationObject.geometries.grounds = [];
  50467. serializationObject.geometries.planes = [];
  50468. serializationObject.geometries.torusKnots = [];
  50469. serializationObject.geometries.vertexData = [];
  50470. }
  50471. serializeGeometry(geometry, serializationObject.geometries);
  50472. }
  50473. // Skeletons
  50474. if (mesh.skeleton) {
  50475. serializationObject.skeletons = serializationObject.skeletons || [];
  50476. serializationObject.skeletons.push(mesh.skeleton.serialize());
  50477. }
  50478. //serialize the actual mesh
  50479. serializationObject.meshes = serializationObject.meshes || [];
  50480. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  50481. }
  50482. };
  50483. var SceneSerializer = (function () {
  50484. function SceneSerializer() {
  50485. }
  50486. SceneSerializer.ClearCache = function () {
  50487. serializedGeometries = [];
  50488. };
  50489. SceneSerializer.Serialize = function (scene) {
  50490. var serializationObject = {};
  50491. // Scene
  50492. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  50493. serializationObject.autoClear = scene.autoClear;
  50494. serializationObject.clearColor = scene.clearColor.asArray();
  50495. serializationObject.ambientColor = scene.ambientColor.asArray();
  50496. serializationObject.gravity = scene.gravity.asArray();
  50497. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  50498. serializationObject.workerCollisions = scene.workerCollisions;
  50499. // Fog
  50500. if (scene.fogMode && scene.fogMode !== 0) {
  50501. serializationObject.fogMode = scene.fogMode;
  50502. serializationObject.fogColor = scene.fogColor.asArray();
  50503. serializationObject.fogStart = scene.fogStart;
  50504. serializationObject.fogEnd = scene.fogEnd;
  50505. serializationObject.fogDensity = scene.fogDensity;
  50506. }
  50507. //Physics
  50508. if (scene.isPhysicsEnabled()) {
  50509. serializationObject.physicsEnabled = true;
  50510. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  50511. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  50512. }
  50513. // Lights
  50514. serializationObject.lights = [];
  50515. var index;
  50516. var light;
  50517. for (index = 0; index < scene.lights.length; index++) {
  50518. light = scene.lights[index];
  50519. serializationObject.lights.push(light.serialize());
  50520. }
  50521. // Cameras
  50522. serializationObject.cameras = [];
  50523. for (index = 0; index < scene.cameras.length; index++) {
  50524. var camera = scene.cameras[index];
  50525. serializationObject.cameras.push(camera.serialize());
  50526. }
  50527. if (scene.activeCamera) {
  50528. serializationObject.activeCameraID = scene.activeCamera.id;
  50529. }
  50530. // Animations
  50531. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  50532. // Materials
  50533. serializationObject.materials = [];
  50534. serializationObject.multiMaterials = [];
  50535. var material;
  50536. for (index = 0; index < scene.materials.length; index++) {
  50537. material = scene.materials[index];
  50538. serializationObject.materials.push(material.serialize());
  50539. }
  50540. // MultiMaterials
  50541. serializationObject.multiMaterials = [];
  50542. for (index = 0; index < scene.multiMaterials.length; index++) {
  50543. var multiMaterial = scene.multiMaterials[index];
  50544. serializationObject.multiMaterials.push(multiMaterial.serialize());
  50545. }
  50546. // Skeletons
  50547. serializationObject.skeletons = [];
  50548. for (index = 0; index < scene.skeletons.length; index++) {
  50549. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  50550. }
  50551. // Geometries
  50552. serializationObject.geometries = {};
  50553. serializationObject.geometries.boxes = [];
  50554. serializationObject.geometries.spheres = [];
  50555. serializationObject.geometries.cylinders = [];
  50556. serializationObject.geometries.toruses = [];
  50557. serializationObject.geometries.grounds = [];
  50558. serializationObject.geometries.planes = [];
  50559. serializationObject.geometries.torusKnots = [];
  50560. serializationObject.geometries.vertexData = [];
  50561. serializedGeometries = [];
  50562. var geometries = scene.getGeometries();
  50563. for (index = 0; index < geometries.length; index++) {
  50564. var geometry = geometries[index];
  50565. if (geometry.isReady()) {
  50566. serializeGeometry(geometry, serializationObject.geometries);
  50567. }
  50568. }
  50569. // Meshes
  50570. serializationObject.meshes = [];
  50571. for (index = 0; index < scene.meshes.length; index++) {
  50572. var abstractMesh = scene.meshes[index];
  50573. if (abstractMesh instanceof BABYLON.Mesh) {
  50574. var mesh = abstractMesh;
  50575. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  50576. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  50577. }
  50578. }
  50579. }
  50580. // Particles Systems
  50581. serializationObject.particleSystems = [];
  50582. for (index = 0; index < scene.particleSystems.length; index++) {
  50583. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  50584. }
  50585. // Lens flares
  50586. serializationObject.lensFlareSystems = [];
  50587. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  50588. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  50589. }
  50590. // Shadows
  50591. serializationObject.shadowGenerators = [];
  50592. for (index = 0; index < scene.lights.length; index++) {
  50593. light = scene.lights[index];
  50594. var shadowGenerator = light.getShadowGenerator();
  50595. // Only support serialization for official generator so far.
  50596. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  50597. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  50598. }
  50599. }
  50600. // Action Manager
  50601. if (scene.actionManager) {
  50602. serializationObject.actions = scene.actionManager.serialize("scene");
  50603. }
  50604. // Audio
  50605. serializationObject.sounds = [];
  50606. for (index = 0; index < scene.soundTracks.length; index++) {
  50607. var soundtrack = scene.soundTracks[index];
  50608. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  50609. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  50610. }
  50611. }
  50612. return serializationObject;
  50613. };
  50614. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  50615. if (withParents === void 0) { withParents = false; }
  50616. if (withChildren === void 0) { withChildren = false; }
  50617. var serializationObject = {};
  50618. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  50619. if (withParents || withChildren) {
  50620. //deliberate for loop! not for each, appended should be processed as well.
  50621. for (var i = 0; i < toSerialize.length; ++i) {
  50622. if (withChildren) {
  50623. toSerialize[i].getDescendants().forEach(function (node) {
  50624. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  50625. toSerialize.push(node);
  50626. }
  50627. });
  50628. }
  50629. //make sure the array doesn't contain the object already
  50630. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  50631. toSerialize.push(toSerialize[i].parent);
  50632. }
  50633. }
  50634. }
  50635. toSerialize.forEach(function (mesh) {
  50636. finalizeSingleMesh(mesh, serializationObject);
  50637. });
  50638. return serializationObject;
  50639. };
  50640. return SceneSerializer;
  50641. })();
  50642. BABYLON.SceneSerializer = SceneSerializer;
  50643. })(BABYLON || (BABYLON = {}));
  50644. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  50645. // Huge respect for a such great lib.
  50646. // Earcut license:
  50647. // Copyright (c) 2016, Mapbox
  50648. //
  50649. // Permission to use, copy, modify, and/or distribute this software for any purpose
  50650. // with or without fee is hereby granted, provided that the above copyright notice
  50651. // and this permission notice appear in all copies.
  50652. //
  50653. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  50654. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  50655. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  50656. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  50657. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  50658. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  50659. // THIS SOFTWARE.
  50660. var Earcut;
  50661. (function (Earcut) {
  50662. /**
  50663. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  50664. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  50665. * @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).
  50666. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  50667. */
  50668. function earcut(data, holeIndices, dim) {
  50669. dim = dim || 2;
  50670. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  50671. if (!outerNode)
  50672. return triangles;
  50673. var minX, minY, maxX, maxY, x, y, size;
  50674. if (hasHoles)
  50675. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  50676. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  50677. if (data.length > 80 * dim) {
  50678. minX = maxX = data[0];
  50679. minY = maxY = data[1];
  50680. for (var i = dim; i < outerLen; i += dim) {
  50681. x = data[i];
  50682. y = data[i + 1];
  50683. if (x < minX)
  50684. minX = x;
  50685. if (y < minY)
  50686. minY = y;
  50687. if (x > maxX)
  50688. maxX = x;
  50689. if (y > maxY)
  50690. maxY = y;
  50691. }
  50692. // minX, minY and size are later used to transform coords into integers for z-order calculation
  50693. size = Math.max(maxX - minX, maxY - minY);
  50694. }
  50695. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  50696. return triangles;
  50697. }
  50698. Earcut.earcut = earcut;
  50699. // create a circular doubly linked list from polygon points in the specified winding order
  50700. function linkedList(data, start, end, dim, clockwise) {
  50701. var i, last;
  50702. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  50703. for (i = start; i < end; i += dim)
  50704. last = insertNode(i, data[i], data[i + 1], last);
  50705. }
  50706. else {
  50707. for (i = end - dim; i >= start; i -= dim)
  50708. last = insertNode(i, data[i], data[i + 1], last);
  50709. }
  50710. if (last && equals(last, last.next)) {
  50711. removeNode(last);
  50712. last = last.next;
  50713. }
  50714. return last;
  50715. }
  50716. // eliminate colinear or duplicate points
  50717. function filterPoints(start, end) {
  50718. if (!start)
  50719. return start;
  50720. if (!end)
  50721. end = start;
  50722. var p = start, again;
  50723. do {
  50724. again = false;
  50725. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  50726. removeNode(p);
  50727. p = end = p.prev;
  50728. if (p === p.next)
  50729. return null;
  50730. again = true;
  50731. }
  50732. else {
  50733. p = p.next;
  50734. }
  50735. } while (again || p !== end);
  50736. return end;
  50737. }
  50738. // main ear slicing loop which triangulates a polygon (given as a linked list)
  50739. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  50740. if (!ear)
  50741. return;
  50742. // interlink polygon nodes in z-order
  50743. if (!pass && size)
  50744. indexCurve(ear, minX, minY, size);
  50745. var stop = ear, prev, next;
  50746. // iterate through ears, slicing them one by one
  50747. while (ear.prev !== ear.next) {
  50748. prev = ear.prev;
  50749. next = ear.next;
  50750. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  50751. // cut off the triangle
  50752. triangles.push(prev.i / dim);
  50753. triangles.push(ear.i / dim);
  50754. triangles.push(next.i / dim);
  50755. removeNode(ear);
  50756. // skipping the next vertice leads to less sliver triangles
  50757. ear = next.next;
  50758. stop = next.next;
  50759. continue;
  50760. }
  50761. ear = next;
  50762. // if we looped through the whole remaining polygon and can't find any more ears
  50763. if (ear === stop) {
  50764. // try filtering points and slicing again
  50765. if (!pass) {
  50766. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  50767. }
  50768. else if (pass === 1) {
  50769. ear = cureLocalIntersections(ear, triangles, dim);
  50770. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  50771. }
  50772. else if (pass === 2) {
  50773. splitEarcut(ear, triangles, dim, minX, minY, size);
  50774. }
  50775. break;
  50776. }
  50777. }
  50778. }
  50779. // check whether a polygon node forms a valid ear with adjacent nodes
  50780. function isEar(ear) {
  50781. var a = ear.prev, b = ear, c = ear.next;
  50782. if (area(a, b, c) >= 0)
  50783. return false; // reflex, can't be an ear
  50784. // now make sure we don't have other points inside the potential ear
  50785. var p = ear.next.next;
  50786. while (p !== ear.prev) {
  50787. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  50788. area(p.prev, p, p.next) >= 0)
  50789. return false;
  50790. p = p.next;
  50791. }
  50792. return true;
  50793. }
  50794. function isEarHashed(ear, minX, minY, size) {
  50795. var a = ear.prev, b = ear, c = ear.next;
  50796. if (area(a, b, c) >= 0)
  50797. return false; // reflex, can't be an ear
  50798. // triangle bbox; min & max are calculated like this for speed
  50799. 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);
  50800. // z-order range for the current triangle bbox;
  50801. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  50802. // first look for points inside the triangle in increasing z-order
  50803. var p = ear.nextZ;
  50804. while (p && p.z <= maxZ) {
  50805. if (p !== ear.prev &&
  50806. p !== ear.next &&
  50807. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  50808. area(p.prev, p, p.next) >= 0)
  50809. return false;
  50810. p = p.nextZ;
  50811. }
  50812. // then look for points in decreasing z-order
  50813. p = ear.prevZ;
  50814. while (p && p.z >= minZ) {
  50815. if (p !== ear.prev &&
  50816. p !== ear.next &&
  50817. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  50818. area(p.prev, p, p.next) >= 0)
  50819. return false;
  50820. p = p.prevZ;
  50821. }
  50822. return true;
  50823. }
  50824. // go through all polygon nodes and cure small local self-intersections
  50825. function cureLocalIntersections(start, triangles, dim) {
  50826. var p = start;
  50827. do {
  50828. var a = p.prev, b = p.next.next;
  50829. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  50830. triangles.push(a.i / dim);
  50831. triangles.push(p.i / dim);
  50832. triangles.push(b.i / dim);
  50833. // remove two nodes involved
  50834. removeNode(p);
  50835. removeNode(p.next);
  50836. p = start = b;
  50837. }
  50838. p = p.next;
  50839. } while (p !== start);
  50840. return p;
  50841. }
  50842. // try splitting polygon into two and triangulate them independently
  50843. function splitEarcut(start, triangles, dim, minX, minY, size) {
  50844. // look for a valid diagonal that divides the polygon into two
  50845. var a = start;
  50846. do {
  50847. var b = a.next.next;
  50848. while (b !== a.prev) {
  50849. if (a.i !== b.i && isValidDiagonal(a, b)) {
  50850. // split the polygon in two by the diagonal
  50851. var c = splitPolygon(a, b);
  50852. // filter colinear points around the cuts
  50853. a = filterPoints(a, a.next);
  50854. c = filterPoints(c, c.next);
  50855. // run earcut on each half
  50856. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  50857. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  50858. return;
  50859. }
  50860. b = b.next;
  50861. }
  50862. a = a.next;
  50863. } while (a !== start);
  50864. }
  50865. // link every hole into the outer loop, producing a single-ring polygon without holes
  50866. function eliminateHoles(data, holeIndices, outerNode, dim) {
  50867. var queue = [], i, len, start, end, list;
  50868. for (i = 0, len = holeIndices.length; i < len; i++) {
  50869. start = holeIndices[i] * dim;
  50870. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  50871. list = linkedList(data, start, end, dim, false);
  50872. if (list === list.next)
  50873. list.steiner = true;
  50874. queue.push(getLeftmost(list));
  50875. }
  50876. queue.sort(compareX);
  50877. // process holes from left to right
  50878. for (i = 0; i < queue.length; i++) {
  50879. eliminateHole(queue[i], outerNode);
  50880. outerNode = filterPoints(outerNode, outerNode.next);
  50881. }
  50882. return outerNode;
  50883. }
  50884. function compareX(a, b) {
  50885. return a.x - b.x;
  50886. }
  50887. // find a bridge between vertices that connects hole with an outer ring and and link it
  50888. function eliminateHole(hole, outerNode) {
  50889. outerNode = findHoleBridge(hole, outerNode);
  50890. if (outerNode) {
  50891. var b = splitPolygon(outerNode, hole);
  50892. filterPoints(b, b.next);
  50893. }
  50894. }
  50895. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  50896. function findHoleBridge(hole, outerNode) {
  50897. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  50898. // find a segment intersected by a ray from the hole's leftmost point to the left;
  50899. // segment's endpoint with lesser x will be potential connection point
  50900. do {
  50901. if (hy <= p.y && hy >= p.next.y) {
  50902. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  50903. if (x <= hx && x > qx) {
  50904. qx = x;
  50905. if (x === hx) {
  50906. if (hy === p.y)
  50907. return p;
  50908. if (hy === p.next.y)
  50909. return p.next;
  50910. }
  50911. m = p.x < p.next.x ? p : p.next;
  50912. }
  50913. }
  50914. p = p.next;
  50915. } while (p !== outerNode);
  50916. if (!m)
  50917. return null;
  50918. if (hx === qx)
  50919. return m.prev; // hole touches outer segment; pick lower endpoint
  50920. // look for points inside the triangle of hole point, segment intersection and endpoint;
  50921. // if there are no points found, we have a valid connection;
  50922. // otherwise choose the point of the minimum angle with the ray as connection point
  50923. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  50924. p = m.next;
  50925. while (p !== stop) {
  50926. if (hx >= p.x &&
  50927. p.x >= mx &&
  50928. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  50929. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  50930. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  50931. m = p;
  50932. tanMin = tan;
  50933. }
  50934. }
  50935. p = p.next;
  50936. }
  50937. return m;
  50938. }
  50939. // interlink polygon nodes in z-order
  50940. function indexCurve(start, minX, minY, size) {
  50941. var p = start;
  50942. do {
  50943. if (p.z === null)
  50944. p.z = zOrder(p.x, p.y, minX, minY, size);
  50945. p.prevZ = p.prev;
  50946. p.nextZ = p.next;
  50947. p = p.next;
  50948. } while (p !== start);
  50949. p.prevZ.nextZ = null;
  50950. p.prevZ = null;
  50951. sortLinked(p);
  50952. }
  50953. // Simon Tatham's linked list merge sort algorithm
  50954. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  50955. function sortLinked(list) {
  50956. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  50957. do {
  50958. p = list;
  50959. list = null;
  50960. tail = null;
  50961. numMerges = 0;
  50962. while (p) {
  50963. numMerges++;
  50964. q = p;
  50965. pSize = 0;
  50966. for (i = 0; i < inSize; i++) {
  50967. pSize++;
  50968. q = q.nextZ;
  50969. if (!q)
  50970. break;
  50971. }
  50972. qSize = inSize;
  50973. while (pSize > 0 || (qSize > 0 && q)) {
  50974. if (pSize === 0) {
  50975. e = q;
  50976. q = q.nextZ;
  50977. qSize--;
  50978. }
  50979. else if (qSize === 0 || !q) {
  50980. e = p;
  50981. p = p.nextZ;
  50982. pSize--;
  50983. }
  50984. else if (p.z <= q.z) {
  50985. e = p;
  50986. p = p.nextZ;
  50987. pSize--;
  50988. }
  50989. else {
  50990. e = q;
  50991. q = q.nextZ;
  50992. qSize--;
  50993. }
  50994. if (tail)
  50995. tail.nextZ = e;
  50996. else
  50997. list = e;
  50998. e.prevZ = tail;
  50999. tail = e;
  51000. }
  51001. p = q;
  51002. }
  51003. tail.nextZ = null;
  51004. inSize *= 2;
  51005. } while (numMerges > 1);
  51006. return list;
  51007. }
  51008. // z-order of a point given coords and size of the data bounding box
  51009. function zOrder(x, y, minX, minY, size) {
  51010. // coords are transformed into non-negative 15-bit integer range
  51011. x = 32767 * (x - minX) / size;
  51012. y = 32767 * (y - minY) / size;
  51013. x = (x | (x << 8)) & 0x00FF00FF;
  51014. x = (x | (x << 4)) & 0x0F0F0F0F;
  51015. x = (x | (x << 2)) & 0x33333333;
  51016. x = (x | (x << 1)) & 0x55555555;
  51017. y = (y | (y << 8)) & 0x00FF00FF;
  51018. y = (y | (y << 4)) & 0x0F0F0F0F;
  51019. y = (y | (y << 2)) & 0x33333333;
  51020. y = (y | (y << 1)) & 0x55555555;
  51021. return x | (y << 1);
  51022. }
  51023. // find the leftmost node of a polygon ring
  51024. function getLeftmost(start) {
  51025. var p = start, leftmost = start;
  51026. do {
  51027. if (p.x < leftmost.x)
  51028. leftmost = p;
  51029. p = p.next;
  51030. } while (p !== start);
  51031. return leftmost;
  51032. }
  51033. // check if a point lies within a convex triangle
  51034. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  51035. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  51036. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  51037. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  51038. }
  51039. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  51040. function isValidDiagonal(a, b) {
  51041. return a.next.i !== b.i &&
  51042. a.prev.i !== b.i &&
  51043. !intersectsPolygon(a, b) &&
  51044. locallyInside(a, b) &&
  51045. locallyInside(b, a) &&
  51046. middleInside(a, b);
  51047. }
  51048. // signed area of a triangle
  51049. function area(p, q, r) {
  51050. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  51051. }
  51052. // check if two points are equal
  51053. function equals(p1, p2) {
  51054. return p1.x === p2.x && p1.y === p2.y;
  51055. }
  51056. // check if two segments intersect
  51057. function intersects(p1, q1, p2, q2) {
  51058. if ((equals(p1, q1) && equals(p2, q2)) ||
  51059. (equals(p1, q2) && equals(p2, q1)))
  51060. return true;
  51061. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  51062. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  51063. }
  51064. // check if a polygon diagonal intersects any polygon segments
  51065. function intersectsPolygon(a, b) {
  51066. var p = a;
  51067. do {
  51068. if (p.i !== a.i &&
  51069. p.next.i !== a.i &&
  51070. p.i !== b.i &&
  51071. p.next.i !== b.i &&
  51072. intersects(p, p.next, a, b))
  51073. return true;
  51074. p = p.next;
  51075. } while (p !== a);
  51076. return false;
  51077. }
  51078. // check if a polygon diagonal is locally inside the polygon
  51079. function locallyInside(a, b) {
  51080. return area(a.prev, a, a.next) < 0
  51081. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  51082. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  51083. }
  51084. // check if the middle point of a polygon diagonal is inside the polygon
  51085. function middleInside(a, b) {
  51086. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  51087. do {
  51088. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  51089. inside = !inside;
  51090. p = p.next;
  51091. } while (p !== a);
  51092. return inside;
  51093. }
  51094. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  51095. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  51096. function splitPolygon(a, b) {
  51097. 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;
  51098. a.next = b;
  51099. b.prev = a;
  51100. a2.next = an;
  51101. an.prev = a2;
  51102. b2.next = a2;
  51103. a2.prev = b2;
  51104. bp.next = b2;
  51105. b2.prev = bp;
  51106. return b2;
  51107. }
  51108. // create a node and optionally link it with previous one (in a circular doubly linked list)
  51109. function insertNode(i, x, y, last) {
  51110. var p = new Node(i, x, y);
  51111. if (!last) {
  51112. p.prev = p;
  51113. p.next = p;
  51114. }
  51115. else {
  51116. p.next = last.next;
  51117. p.prev = last;
  51118. last.next.prev = p;
  51119. last.next = p;
  51120. }
  51121. return p;
  51122. }
  51123. function removeNode(p) {
  51124. p.next.prev = p.prev;
  51125. p.prev.next = p.next;
  51126. if (p.prevZ)
  51127. p.prevZ.nextZ = p.nextZ;
  51128. if (p.nextZ)
  51129. p.nextZ.prevZ = p.prevZ;
  51130. }
  51131. function Node(i, x, y) {
  51132. // vertice index in coordinates array
  51133. this.i = i;
  51134. // vertex coordinates
  51135. this.x = x;
  51136. this.y = y;
  51137. // previous and next vertice nodes in a polygon ring
  51138. this.prev = null;
  51139. this.next = null;
  51140. // z-order curve value
  51141. this.z = null;
  51142. // previous and next nodes in z-order
  51143. this.prevZ = null;
  51144. this.nextZ = null;
  51145. // indicates whether this is a steiner point
  51146. this.steiner = false;
  51147. }
  51148. /**
  51149. * return a percentage difference between the polygon area and its triangulation area;
  51150. * used to verify correctness of triangulation
  51151. */
  51152. function deviation(data, holeIndices, dim, triangles) {
  51153. var hasHoles = holeIndices && holeIndices.length;
  51154. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  51155. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  51156. if (hasHoles) {
  51157. for (var i = 0, len = holeIndices.length; i < len; i++) {
  51158. var start = holeIndices[i] * dim;
  51159. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  51160. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  51161. }
  51162. }
  51163. var trianglesArea = 0;
  51164. for (i = 0; i < triangles.length; i += 3) {
  51165. var a = triangles[i] * dim;
  51166. var b = triangles[i + 1] * dim;
  51167. var c = triangles[i + 2] * dim;
  51168. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  51169. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  51170. }
  51171. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  51172. }
  51173. Earcut.deviation = deviation;
  51174. ;
  51175. function signedArea(data, start, end, dim) {
  51176. var sum = 0;
  51177. for (var i = start, j = end - dim; i < end; i += dim) {
  51178. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  51179. j = i;
  51180. }
  51181. return sum;
  51182. }
  51183. /**
  51184. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  51185. */
  51186. function flatten(data) {
  51187. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  51188. for (var i = 0; i < data.length; i++) {
  51189. for (var j = 0; j < data[i].length; j++) {
  51190. for (var d = 0; d < dim; d++)
  51191. result.vertices.push(data[i][j][d]);
  51192. }
  51193. if (i > 0) {
  51194. holeIndex += data[i - 1].length;
  51195. result.holes.push(holeIndex);
  51196. }
  51197. }
  51198. return result;
  51199. }
  51200. Earcut.flatten = flatten;
  51201. ;
  51202. })(Earcut || (Earcut = {}));
  51203. var BABYLON;
  51204. (function (BABYLON) {
  51205. // Unique ID when we import meshes from Babylon to CSG
  51206. var currentCSGMeshId = 0;
  51207. // # class Vertex
  51208. // Represents a vertex of a polygon. Use your own vertex class instead of this
  51209. // one to provide additional features like texture coordinates and vertex
  51210. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  51211. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  51212. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  51213. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  51214. // is not used anywhere else.
  51215. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  51216. var Vertex = (function () {
  51217. function Vertex(pos, normal, uv) {
  51218. this.pos = pos;
  51219. this.normal = normal;
  51220. this.uv = uv;
  51221. }
  51222. Vertex.prototype.clone = function () {
  51223. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  51224. };
  51225. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  51226. // orientation of a polygon is flipped.
  51227. Vertex.prototype.flip = function () {
  51228. this.normal = this.normal.scale(-1);
  51229. };
  51230. // Create a new vertex between this vertex and `other` by linearly
  51231. // interpolating all properties using a parameter of `t`. Subclasses should
  51232. // override this to interpolate additional properties.
  51233. Vertex.prototype.interpolate = function (other, t) {
  51234. 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));
  51235. };
  51236. return Vertex;
  51237. })();
  51238. // # class Plane
  51239. // Represents a plane in 3D space.
  51240. var Plane = (function () {
  51241. function Plane(normal, w) {
  51242. this.normal = normal;
  51243. this.w = w;
  51244. }
  51245. Plane.FromPoints = function (a, b, c) {
  51246. var v0 = c.subtract(a);
  51247. var v1 = b.subtract(a);
  51248. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  51249. return null;
  51250. }
  51251. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  51252. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  51253. };
  51254. Plane.prototype.clone = function () {
  51255. return new Plane(this.normal.clone(), this.w);
  51256. };
  51257. Plane.prototype.flip = function () {
  51258. this.normal.scaleInPlace(-1);
  51259. this.w = -this.w;
  51260. };
  51261. // Split `polygon` by this plane if needed, then put the polygon or polygon
  51262. // fragments in the appropriate lists. Coplanar polygons go into either
  51263. // `coplanarFront` or `coplanarBack` depending on their orientation with
  51264. // respect to this plane. Polygons in front or in back of this plane go into
  51265. // either `front` or `back`.
  51266. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  51267. var COPLANAR = 0;
  51268. var FRONT = 1;
  51269. var BACK = 2;
  51270. var SPANNING = 3;
  51271. // Classify each point as well as the entire polygon into one of the above
  51272. // four classes.
  51273. var polygonType = 0;
  51274. var types = [];
  51275. var i;
  51276. var t;
  51277. for (i = 0; i < polygon.vertices.length; i++) {
  51278. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  51279. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  51280. polygonType |= type;
  51281. types.push(type);
  51282. }
  51283. // Put the polygon in the correct list, splitting it when necessary.
  51284. switch (polygonType) {
  51285. case COPLANAR:
  51286. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  51287. break;
  51288. case FRONT:
  51289. front.push(polygon);
  51290. break;
  51291. case BACK:
  51292. back.push(polygon);
  51293. break;
  51294. case SPANNING:
  51295. var f = [], b = [];
  51296. for (i = 0; i < polygon.vertices.length; i++) {
  51297. var j = (i + 1) % polygon.vertices.length;
  51298. var ti = types[i], tj = types[j];
  51299. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  51300. if (ti !== BACK)
  51301. f.push(vi);
  51302. if (ti !== FRONT)
  51303. b.push(ti !== BACK ? vi.clone() : vi);
  51304. if ((ti | tj) === SPANNING) {
  51305. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  51306. var v = vi.interpolate(vj, t);
  51307. f.push(v);
  51308. b.push(v.clone());
  51309. }
  51310. }
  51311. var poly;
  51312. if (f.length >= 3) {
  51313. poly = new Polygon(f, polygon.shared);
  51314. if (poly.plane)
  51315. front.push(poly);
  51316. }
  51317. if (b.length >= 3) {
  51318. poly = new Polygon(b, polygon.shared);
  51319. if (poly.plane)
  51320. back.push(poly);
  51321. }
  51322. break;
  51323. }
  51324. };
  51325. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  51326. // point is on the plane.
  51327. Plane.EPSILON = 1e-5;
  51328. return Plane;
  51329. })();
  51330. // # class Polygon
  51331. // Represents a convex polygon. The vertices used to initialize a polygon must
  51332. // be coplanar and form a convex loop.
  51333. //
  51334. // Each convex polygon has a `shared` property, which is shared between all
  51335. // polygons that are clones of each other or were split from the same polygon.
  51336. // This can be used to define per-polygon properties (such as surface color).
  51337. var Polygon = (function () {
  51338. function Polygon(vertices, shared) {
  51339. this.vertices = vertices;
  51340. this.shared = shared;
  51341. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  51342. }
  51343. Polygon.prototype.clone = function () {
  51344. var vertices = this.vertices.map(function (v) { return v.clone(); });
  51345. return new Polygon(vertices, this.shared);
  51346. };
  51347. Polygon.prototype.flip = function () {
  51348. this.vertices.reverse().map(function (v) { v.flip(); });
  51349. this.plane.flip();
  51350. };
  51351. return Polygon;
  51352. })();
  51353. // # class Node
  51354. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  51355. // by picking a polygon to split along. That polygon (and all other coplanar
  51356. // polygons) are added directly to that node and the other polygons are added to
  51357. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  51358. // no distinction between internal and leaf nodes.
  51359. var Node = (function () {
  51360. function Node(polygons) {
  51361. this.plane = null;
  51362. this.front = null;
  51363. this.back = null;
  51364. this.polygons = [];
  51365. if (polygons) {
  51366. this.build(polygons);
  51367. }
  51368. }
  51369. Node.prototype.clone = function () {
  51370. var node = new Node();
  51371. node.plane = this.plane && this.plane.clone();
  51372. node.front = this.front && this.front.clone();
  51373. node.back = this.back && this.back.clone();
  51374. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  51375. return node;
  51376. };
  51377. // Convert solid space to empty space and empty space to solid space.
  51378. Node.prototype.invert = function () {
  51379. for (var i = 0; i < this.polygons.length; i++) {
  51380. this.polygons[i].flip();
  51381. }
  51382. if (this.plane) {
  51383. this.plane.flip();
  51384. }
  51385. if (this.front) {
  51386. this.front.invert();
  51387. }
  51388. if (this.back) {
  51389. this.back.invert();
  51390. }
  51391. var temp = this.front;
  51392. this.front = this.back;
  51393. this.back = temp;
  51394. };
  51395. // Recursively remove all polygons in `polygons` that are inside this BSP
  51396. // tree.
  51397. Node.prototype.clipPolygons = function (polygons) {
  51398. if (!this.plane)
  51399. return polygons.slice();
  51400. var front = [], back = [];
  51401. for (var i = 0; i < polygons.length; i++) {
  51402. this.plane.splitPolygon(polygons[i], front, back, front, back);
  51403. }
  51404. if (this.front) {
  51405. front = this.front.clipPolygons(front);
  51406. }
  51407. if (this.back) {
  51408. back = this.back.clipPolygons(back);
  51409. }
  51410. else {
  51411. back = [];
  51412. }
  51413. return front.concat(back);
  51414. };
  51415. // Remove all polygons in this BSP tree that are inside the other BSP tree
  51416. // `bsp`.
  51417. Node.prototype.clipTo = function (bsp) {
  51418. this.polygons = bsp.clipPolygons(this.polygons);
  51419. if (this.front)
  51420. this.front.clipTo(bsp);
  51421. if (this.back)
  51422. this.back.clipTo(bsp);
  51423. };
  51424. // Return a list of all polygons in this BSP tree.
  51425. Node.prototype.allPolygons = function () {
  51426. var polygons = this.polygons.slice();
  51427. if (this.front)
  51428. polygons = polygons.concat(this.front.allPolygons());
  51429. if (this.back)
  51430. polygons = polygons.concat(this.back.allPolygons());
  51431. return polygons;
  51432. };
  51433. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  51434. // new polygons are filtered down to the bottom of the tree and become new
  51435. // nodes there. Each set of polygons is partitioned using the first polygon
  51436. // (no heuristic is used to pick a good split).
  51437. Node.prototype.build = function (polygons) {
  51438. if (!polygons.length)
  51439. return;
  51440. if (!this.plane)
  51441. this.plane = polygons[0].plane.clone();
  51442. var front = [], back = [];
  51443. for (var i = 0; i < polygons.length; i++) {
  51444. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  51445. }
  51446. if (front.length) {
  51447. if (!this.front)
  51448. this.front = new Node();
  51449. this.front.build(front);
  51450. }
  51451. if (back.length) {
  51452. if (!this.back)
  51453. this.back = new Node();
  51454. this.back.build(back);
  51455. }
  51456. };
  51457. return Node;
  51458. })();
  51459. var CSG = (function () {
  51460. function CSG() {
  51461. this.polygons = new Array();
  51462. }
  51463. // Convert BABYLON.Mesh to BABYLON.CSG
  51464. CSG.FromMesh = function (mesh) {
  51465. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  51466. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  51467. if (mesh instanceof BABYLON.Mesh) {
  51468. mesh.computeWorldMatrix(true);
  51469. matrix = mesh.getWorldMatrix();
  51470. meshPosition = mesh.position.clone();
  51471. meshRotation = mesh.rotation.clone();
  51472. if (mesh.rotationQuaternion) {
  51473. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  51474. }
  51475. meshScaling = mesh.scaling.clone();
  51476. }
  51477. else {
  51478. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  51479. }
  51480. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51481. var subMeshes = mesh.subMeshes;
  51482. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  51483. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  51484. vertices = [];
  51485. for (var j = 0; j < 3; j++) {
  51486. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  51487. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  51488. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  51489. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  51490. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  51491. vertex = new Vertex(position, normal, uv);
  51492. vertices.push(vertex);
  51493. }
  51494. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  51495. // To handle the case of degenerated triangle
  51496. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  51497. if (polygon.plane)
  51498. polygons.push(polygon);
  51499. }
  51500. }
  51501. var csg = CSG.FromPolygons(polygons);
  51502. csg.matrix = matrix;
  51503. csg.position = meshPosition;
  51504. csg.rotation = meshRotation;
  51505. csg.scaling = meshScaling;
  51506. csg.rotationQuaternion = meshRotationQuaternion;
  51507. currentCSGMeshId++;
  51508. return csg;
  51509. };
  51510. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  51511. CSG.FromPolygons = function (polygons) {
  51512. var csg = new CSG();
  51513. csg.polygons = polygons;
  51514. return csg;
  51515. };
  51516. CSG.prototype.clone = function () {
  51517. var csg = new CSG();
  51518. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  51519. csg.copyTransformAttributes(this);
  51520. return csg;
  51521. };
  51522. CSG.prototype.toPolygons = function () {
  51523. return this.polygons;
  51524. };
  51525. CSG.prototype.union = function (csg) {
  51526. var a = new Node(this.clone().polygons);
  51527. var b = new Node(csg.clone().polygons);
  51528. a.clipTo(b);
  51529. b.clipTo(a);
  51530. b.invert();
  51531. b.clipTo(a);
  51532. b.invert();
  51533. a.build(b.allPolygons());
  51534. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  51535. };
  51536. CSG.prototype.unionInPlace = function (csg) {
  51537. var a = new Node(this.polygons);
  51538. var b = new Node(csg.polygons);
  51539. a.clipTo(b);
  51540. b.clipTo(a);
  51541. b.invert();
  51542. b.clipTo(a);
  51543. b.invert();
  51544. a.build(b.allPolygons());
  51545. this.polygons = a.allPolygons();
  51546. };
  51547. CSG.prototype.subtract = function (csg) {
  51548. var a = new Node(this.clone().polygons);
  51549. var b = new Node(csg.clone().polygons);
  51550. a.invert();
  51551. a.clipTo(b);
  51552. b.clipTo(a);
  51553. b.invert();
  51554. b.clipTo(a);
  51555. b.invert();
  51556. a.build(b.allPolygons());
  51557. a.invert();
  51558. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  51559. };
  51560. CSG.prototype.subtractInPlace = function (csg) {
  51561. var a = new Node(this.polygons);
  51562. var b = new Node(csg.polygons);
  51563. a.invert();
  51564. a.clipTo(b);
  51565. b.clipTo(a);
  51566. b.invert();
  51567. b.clipTo(a);
  51568. b.invert();
  51569. a.build(b.allPolygons());
  51570. a.invert();
  51571. this.polygons = a.allPolygons();
  51572. };
  51573. CSG.prototype.intersect = function (csg) {
  51574. var a = new Node(this.clone().polygons);
  51575. var b = new Node(csg.clone().polygons);
  51576. a.invert();
  51577. b.clipTo(a);
  51578. b.invert();
  51579. a.clipTo(b);
  51580. b.clipTo(a);
  51581. a.build(b.allPolygons());
  51582. a.invert();
  51583. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  51584. };
  51585. CSG.prototype.intersectInPlace = function (csg) {
  51586. var a = new Node(this.polygons);
  51587. var b = new Node(csg.polygons);
  51588. a.invert();
  51589. b.clipTo(a);
  51590. b.invert();
  51591. a.clipTo(b);
  51592. b.clipTo(a);
  51593. a.build(b.allPolygons());
  51594. a.invert();
  51595. this.polygons = a.allPolygons();
  51596. };
  51597. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  51598. // not modified.
  51599. CSG.prototype.inverse = function () {
  51600. var csg = this.clone();
  51601. csg.inverseInPlace();
  51602. return csg;
  51603. };
  51604. CSG.prototype.inverseInPlace = function () {
  51605. this.polygons.map(function (p) { p.flip(); });
  51606. };
  51607. // This is used to keep meshes transformations so they can be restored
  51608. // when we build back a Babylon Mesh
  51609. // NB : All CSG operations are performed in world coordinates
  51610. CSG.prototype.copyTransformAttributes = function (csg) {
  51611. this.matrix = csg.matrix;
  51612. this.position = csg.position;
  51613. this.rotation = csg.rotation;
  51614. this.scaling = csg.scaling;
  51615. this.rotationQuaternion = csg.rotationQuaternion;
  51616. return this;
  51617. };
  51618. // Build Raw mesh from CSG
  51619. // Coordinates here are in world space
  51620. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  51621. var matrix = this.matrix.clone();
  51622. matrix.invert();
  51623. 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;
  51624. if (keepSubMeshes) {
  51625. // Sort Polygons, since subMeshes are indices range
  51626. polygons.sort(function (a, b) {
  51627. if (a.shared.meshId === b.shared.meshId) {
  51628. return a.shared.subMeshId - b.shared.subMeshId;
  51629. }
  51630. else {
  51631. return a.shared.meshId - b.shared.meshId;
  51632. }
  51633. });
  51634. }
  51635. for (var i = 0, il = polygons.length; i < il; i++) {
  51636. polygon = polygons[i];
  51637. // Building SubMeshes
  51638. if (!subMesh_dict[polygon.shared.meshId]) {
  51639. subMesh_dict[polygon.shared.meshId] = {};
  51640. }
  51641. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  51642. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  51643. indexStart: +Infinity,
  51644. indexEnd: -Infinity,
  51645. materialIndex: polygon.shared.materialIndex
  51646. };
  51647. }
  51648. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  51649. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  51650. polygonIndices[0] = 0;
  51651. polygonIndices[1] = j - 1;
  51652. polygonIndices[2] = j;
  51653. for (var k = 0; k < 3; k++) {
  51654. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  51655. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  51656. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  51657. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  51658. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  51659. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  51660. // Check if 2 points can be merged
  51661. if (!(typeof vertex_idx !== 'undefined' &&
  51662. normals[vertex_idx * 3] === localNormal.x &&
  51663. normals[vertex_idx * 3 + 1] === localNormal.y &&
  51664. normals[vertex_idx * 3 + 2] === localNormal.z &&
  51665. uvs[vertex_idx * 2] === uv.x &&
  51666. uvs[vertex_idx * 2 + 1] === uv.y)) {
  51667. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  51668. uvs.push(uv.x, uv.y);
  51669. normals.push(normal.x, normal.y, normal.z);
  51670. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  51671. }
  51672. indices.push(vertex_idx);
  51673. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  51674. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  51675. currentIndex++;
  51676. }
  51677. }
  51678. }
  51679. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  51680. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  51681. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  51682. mesh.setIndices(indices);
  51683. if (keepSubMeshes) {
  51684. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  51685. var materialIndexOffset = 0, materialMaxIndex;
  51686. mesh.subMeshes = new Array();
  51687. for (var m in subMesh_dict) {
  51688. materialMaxIndex = -1;
  51689. for (var sm in subMesh_dict[m]) {
  51690. subMesh_obj = subMesh_dict[m][sm];
  51691. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  51692. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  51693. }
  51694. materialIndexOffset += ++materialMaxIndex;
  51695. }
  51696. }
  51697. return mesh;
  51698. };
  51699. // Build Mesh from CSG taking material and transforms into account
  51700. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  51701. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  51702. mesh.material = material;
  51703. mesh.position.copyFrom(this.position);
  51704. mesh.rotation.copyFrom(this.rotation);
  51705. if (this.rotationQuaternion) {
  51706. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  51707. }
  51708. mesh.scaling.copyFrom(this.scaling);
  51709. mesh.computeWorldMatrix(true);
  51710. return mesh;
  51711. };
  51712. return CSG;
  51713. })();
  51714. BABYLON.CSG = CSG;
  51715. })(BABYLON || (BABYLON = {}));
  51716. var BABYLON;
  51717. (function (BABYLON) {
  51718. var VRDistortionCorrectionPostProcess = (function (_super) {
  51719. __extends(VRDistortionCorrectionPostProcess, _super);
  51720. //ANY
  51721. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  51722. var _this = this;
  51723. _super.call(this, name, "vrDistortionCorrection", [
  51724. 'LensCenter',
  51725. 'Scale',
  51726. 'ScaleIn',
  51727. 'HmdWarpParam'
  51728. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  51729. this._isRightEye = isRightEye;
  51730. this._distortionFactors = vrMetrics.distortionK;
  51731. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  51732. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  51733. this.onSizeChangedObservable.add(function () {
  51734. _this.aspectRatio = _this.width * .5 / _this.height;
  51735. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  51736. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  51737. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  51738. });
  51739. this.onApplyObservable.add(function (effect) {
  51740. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  51741. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  51742. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  51743. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  51744. });
  51745. }
  51746. return VRDistortionCorrectionPostProcess;
  51747. })(BABYLON.PostProcess);
  51748. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  51749. })(BABYLON || (BABYLON = {}));
  51750. // Mainly based on these 2 articles :
  51751. // 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
  51752. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  51753. var BABYLON;
  51754. (function (BABYLON) {
  51755. (function (JoystickAxis) {
  51756. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  51757. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  51758. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  51759. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  51760. var JoystickAxis = BABYLON.JoystickAxis;
  51761. var VirtualJoystick = (function () {
  51762. function VirtualJoystick(leftJoystick) {
  51763. var _this = this;
  51764. if (leftJoystick) {
  51765. this._leftJoystick = true;
  51766. }
  51767. else {
  51768. this._leftJoystick = false;
  51769. }
  51770. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  51771. VirtualJoystick._globalJoystickIndex++;
  51772. // By default left & right arrow keys are moving the X
  51773. // and up & down keys are moving the Y
  51774. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  51775. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  51776. this.reverseLeftRight = false;
  51777. this.reverseUpDown = false;
  51778. // collections of pointers
  51779. this._touches = new BABYLON.StringDictionary();
  51780. this.deltaPosition = BABYLON.Vector3.Zero();
  51781. this._joystickSensibility = 25;
  51782. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  51783. this._rotationSpeed = 25;
  51784. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  51785. this._rotateOnAxisRelativeToMesh = false;
  51786. this._onResize = function (evt) {
  51787. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  51788. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  51789. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  51790. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  51791. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  51792. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  51793. };
  51794. // injecting a canvas element on top of the canvas 3D game
  51795. if (!VirtualJoystick.vjCanvas) {
  51796. window.addEventListener("resize", this._onResize, false);
  51797. VirtualJoystick.vjCanvas = document.createElement("canvas");
  51798. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  51799. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  51800. VirtualJoystick.vjCanvas.width = window.innerWidth;
  51801. VirtualJoystick.vjCanvas.height = window.innerHeight;
  51802. VirtualJoystick.vjCanvas.style.width = "100%";
  51803. VirtualJoystick.vjCanvas.style.height = "100%";
  51804. VirtualJoystick.vjCanvas.style.position = "absolute";
  51805. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  51806. VirtualJoystick.vjCanvas.style.top = "0px";
  51807. VirtualJoystick.vjCanvas.style.left = "0px";
  51808. VirtualJoystick.vjCanvas.style.zIndex = "5";
  51809. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  51810. // Support for jQuery PEP polyfill
  51811. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  51812. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  51813. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  51814. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  51815. document.body.appendChild(VirtualJoystick.vjCanvas);
  51816. }
  51817. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  51818. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  51819. this.pressed = false;
  51820. // default joystick color
  51821. this._joystickColor = "cyan";
  51822. this._joystickPointerID = -1;
  51823. // current joystick position
  51824. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  51825. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  51826. // origin joystick position
  51827. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  51828. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  51829. this._onPointerDownHandlerRef = function (evt) {
  51830. _this._onPointerDown(evt);
  51831. };
  51832. this._onPointerMoveHandlerRef = function (evt) {
  51833. _this._onPointerMove(evt);
  51834. };
  51835. this._onPointerOutHandlerRef = function (evt) {
  51836. _this._onPointerUp(evt);
  51837. };
  51838. this._onPointerUpHandlerRef = function (evt) {
  51839. _this._onPointerUp(evt);
  51840. };
  51841. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  51842. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  51843. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  51844. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  51845. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  51846. evt.preventDefault(); // Disables system menu
  51847. }, false);
  51848. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  51849. }
  51850. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  51851. this._joystickSensibility = newJoystickSensibility;
  51852. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  51853. };
  51854. VirtualJoystick.prototype._onPointerDown = function (e) {
  51855. var positionOnScreenCondition;
  51856. e.preventDefault();
  51857. if (this._leftJoystick === true) {
  51858. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  51859. }
  51860. else {
  51861. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  51862. }
  51863. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  51864. // First contact will be dedicated to the virtual joystick
  51865. this._joystickPointerID = e.pointerId;
  51866. this._joystickPointerStartPos.x = e.clientX;
  51867. this._joystickPointerStartPos.y = e.clientY;
  51868. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  51869. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  51870. this._deltaJoystickVector.x = 0;
  51871. this._deltaJoystickVector.y = 0;
  51872. this.pressed = true;
  51873. this._touches.add(e.pointerId.toString(), e);
  51874. }
  51875. else {
  51876. // You can only trigger the action buttons with a joystick declared
  51877. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  51878. this._action();
  51879. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  51880. }
  51881. }
  51882. };
  51883. VirtualJoystick.prototype._onPointerMove = function (e) {
  51884. // If the current pointer is the one associated to the joystick (first touch contact)
  51885. if (this._joystickPointerID == e.pointerId) {
  51886. this._joystickPointerPos.x = e.clientX;
  51887. this._joystickPointerPos.y = e.clientY;
  51888. this._deltaJoystickVector = this._joystickPointerPos.clone();
  51889. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  51890. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  51891. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  51892. switch (this._axisTargetedByLeftAndRight) {
  51893. case JoystickAxis.X:
  51894. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  51895. break;
  51896. case JoystickAxis.Y:
  51897. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  51898. break;
  51899. case JoystickAxis.Z:
  51900. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  51901. break;
  51902. }
  51903. var directionUpDown = this.reverseUpDown ? 1 : -1;
  51904. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  51905. switch (this._axisTargetedByUpAndDown) {
  51906. case JoystickAxis.X:
  51907. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  51908. break;
  51909. case JoystickAxis.Y:
  51910. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  51911. break;
  51912. case JoystickAxis.Z:
  51913. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  51914. break;
  51915. }
  51916. }
  51917. else {
  51918. var data = this._touches.get(e.pointerId.toString());
  51919. if (data) {
  51920. data.x = e.clientX;
  51921. data.y = e.clientY;
  51922. }
  51923. }
  51924. };
  51925. VirtualJoystick.prototype._onPointerUp = function (e) {
  51926. if (this._joystickPointerID == e.pointerId) {
  51927. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  51928. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  51929. this._joystickPointerID = -1;
  51930. this.pressed = false;
  51931. }
  51932. else {
  51933. var touch = this._touches.get(e.pointerId.toString());
  51934. if (touch) {
  51935. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  51936. }
  51937. }
  51938. this._deltaJoystickVector.x = 0;
  51939. this._deltaJoystickVector.y = 0;
  51940. this._touches.remove(e.pointerId.toString());
  51941. };
  51942. /**
  51943. * Change the color of the virtual joystick
  51944. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  51945. */
  51946. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  51947. this._joystickColor = newColor;
  51948. };
  51949. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  51950. this._action = action;
  51951. };
  51952. // Define which axis you'd like to control for left & right
  51953. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  51954. switch (axis) {
  51955. case JoystickAxis.X:
  51956. case JoystickAxis.Y:
  51957. case JoystickAxis.Z:
  51958. this._axisTargetedByLeftAndRight = axis;
  51959. break;
  51960. default:
  51961. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  51962. break;
  51963. }
  51964. };
  51965. // Define which axis you'd like to control for up & down
  51966. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  51967. switch (axis) {
  51968. case JoystickAxis.X:
  51969. case JoystickAxis.Y:
  51970. case JoystickAxis.Z:
  51971. this._axisTargetedByUpAndDown = axis;
  51972. break;
  51973. default:
  51974. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  51975. break;
  51976. }
  51977. };
  51978. VirtualJoystick.prototype._clearCanvas = function () {
  51979. if (this._leftJoystick) {
  51980. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  51981. }
  51982. else {
  51983. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  51984. }
  51985. };
  51986. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  51987. var _this = this;
  51988. if (this.pressed) {
  51989. this._touches.forEach(function (touch) {
  51990. if (touch.pointerId === _this._joystickPointerID) {
  51991. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  51992. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  51993. VirtualJoystick.vjCanvasContext.beginPath();
  51994. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  51995. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  51996. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  51997. VirtualJoystick.vjCanvasContext.stroke();
  51998. VirtualJoystick.vjCanvasContext.closePath();
  51999. VirtualJoystick.vjCanvasContext.beginPath();
  52000. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  52001. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  52002. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  52003. VirtualJoystick.vjCanvasContext.stroke();
  52004. VirtualJoystick.vjCanvasContext.closePath();
  52005. VirtualJoystick.vjCanvasContext.beginPath();
  52006. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  52007. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  52008. VirtualJoystick.vjCanvasContext.stroke();
  52009. VirtualJoystick.vjCanvasContext.closePath();
  52010. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  52011. }
  52012. else {
  52013. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  52014. VirtualJoystick.vjCanvasContext.beginPath();
  52015. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  52016. VirtualJoystick.vjCanvasContext.beginPath();
  52017. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  52018. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  52019. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  52020. VirtualJoystick.vjCanvasContext.stroke();
  52021. VirtualJoystick.vjCanvasContext.closePath();
  52022. touch.prevX = touch.x;
  52023. touch.prevY = touch.y;
  52024. }
  52025. ;
  52026. });
  52027. }
  52028. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  52029. };
  52030. VirtualJoystick.prototype.releaseCanvas = function () {
  52031. if (VirtualJoystick.vjCanvas) {
  52032. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  52033. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  52034. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  52035. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  52036. window.removeEventListener("resize", this._onResize);
  52037. document.body.removeChild(VirtualJoystick.vjCanvas);
  52038. VirtualJoystick.vjCanvas = null;
  52039. }
  52040. };
  52041. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  52042. VirtualJoystick._globalJoystickIndex = 0;
  52043. return VirtualJoystick;
  52044. })();
  52045. BABYLON.VirtualJoystick = VirtualJoystick;
  52046. })(BABYLON || (BABYLON = {}));
  52047. var BABYLON;
  52048. (function (BABYLON) {
  52049. // We're mainly based on the logic defined into the FreeCamera code
  52050. var VirtualJoysticksCamera = (function (_super) {
  52051. __extends(VirtualJoysticksCamera, _super);
  52052. function VirtualJoysticksCamera(name, position, scene) {
  52053. _super.call(this, name, position, scene);
  52054. this.inputs.addVirtualJoystick();
  52055. }
  52056. return VirtualJoysticksCamera;
  52057. })(BABYLON.FreeCamera);
  52058. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  52059. })(BABYLON || (BABYLON = {}));
  52060. var BABYLON;
  52061. (function (BABYLON) {
  52062. var FreeCameraVirtualJoystickInput = (function () {
  52063. function FreeCameraVirtualJoystickInput() {
  52064. }
  52065. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  52066. return this._leftjoystick;
  52067. };
  52068. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  52069. return this._rightjoystick;
  52070. };
  52071. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  52072. if (this._leftjoystick) {
  52073. var camera = this.camera;
  52074. var speed = camera._computeLocalCameraSpeed() * 50;
  52075. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  52076. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  52077. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  52078. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  52079. if (!this._leftjoystick.pressed) {
  52080. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  52081. }
  52082. if (!this._rightjoystick.pressed) {
  52083. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  52084. }
  52085. }
  52086. };
  52087. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  52088. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  52089. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  52090. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  52091. this._leftjoystick.setJoystickSensibility(0.15);
  52092. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  52093. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  52094. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  52095. this._rightjoystick.reverseUpDown = true;
  52096. this._rightjoystick.setJoystickSensibility(0.05);
  52097. this._rightjoystick.setJoystickColor("yellow");
  52098. };
  52099. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  52100. this._leftjoystick.releaseCanvas();
  52101. this._rightjoystick.releaseCanvas();
  52102. };
  52103. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  52104. return "FreeCameraVirtualJoystickInput";
  52105. };
  52106. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  52107. return "virtualJoystick";
  52108. };
  52109. return FreeCameraVirtualJoystickInput;
  52110. })();
  52111. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  52112. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  52113. })(BABYLON || (BABYLON = {}));
  52114. var BABYLON;
  52115. (function (BABYLON) {
  52116. var AnaglyphPostProcess = (function (_super) {
  52117. __extends(AnaglyphPostProcess, _super);
  52118. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  52119. var _this = this;
  52120. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  52121. this._passedProcess = rigCameras[0]._rigPostProcess;
  52122. this.onApplyObservable.add(function (effect) {
  52123. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  52124. });
  52125. }
  52126. return AnaglyphPostProcess;
  52127. })(BABYLON.PostProcess);
  52128. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  52129. })(BABYLON || (BABYLON = {}));
  52130. var BABYLON;
  52131. (function (BABYLON) {
  52132. var OutlineRenderer = (function () {
  52133. function OutlineRenderer(scene) {
  52134. this._scene = scene;
  52135. }
  52136. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  52137. var _this = this;
  52138. if (useOverlay === void 0) { useOverlay = false; }
  52139. var scene = this._scene;
  52140. var engine = this._scene.getEngine();
  52141. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  52142. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  52143. return;
  52144. }
  52145. var mesh = subMesh.getRenderingMesh();
  52146. var material = subMesh.getMaterial();
  52147. engine.enableEffect(this._effect);
  52148. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  52149. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  52150. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  52151. // Bones
  52152. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52153. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  52154. }
  52155. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  52156. // Alpha test
  52157. if (material && material.needAlphaTesting()) {
  52158. var alphaTexture = material.getAlphaTestTexture();
  52159. this._effect.setTexture("diffuseSampler", alphaTexture);
  52160. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  52161. }
  52162. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  52163. };
  52164. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  52165. var defines = [];
  52166. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  52167. var mesh = subMesh.getMesh();
  52168. var material = subMesh.getMaterial();
  52169. // Alpha test
  52170. if (material && material.needAlphaTesting()) {
  52171. defines.push("#define ALPHATEST");
  52172. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52173. attribs.push(BABYLON.VertexBuffer.UVKind);
  52174. defines.push("#define UV1");
  52175. }
  52176. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52177. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52178. defines.push("#define UV2");
  52179. }
  52180. }
  52181. // Bones
  52182. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52183. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52184. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52185. if (mesh.numBoneInfluencers > 4) {
  52186. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52187. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52188. }
  52189. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52190. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52191. }
  52192. else {
  52193. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52194. }
  52195. // Instances
  52196. if (useInstances) {
  52197. defines.push("#define INSTANCES");
  52198. attribs.push("world0");
  52199. attribs.push("world1");
  52200. attribs.push("world2");
  52201. attribs.push("world3");
  52202. }
  52203. // Get correct effect
  52204. var join = defines.join("\n");
  52205. if (this._cachedDefines !== join) {
  52206. this._cachedDefines = join;
  52207. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  52208. }
  52209. return this._effect.isReady();
  52210. };
  52211. return OutlineRenderer;
  52212. })();
  52213. BABYLON.OutlineRenderer = OutlineRenderer;
  52214. })(BABYLON || (BABYLON = {}));
  52215. var BABYLON;
  52216. (function (BABYLON) {
  52217. var MeshAssetTask = (function () {
  52218. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  52219. this.name = name;
  52220. this.meshesNames = meshesNames;
  52221. this.rootUrl = rootUrl;
  52222. this.sceneFilename = sceneFilename;
  52223. this.isCompleted = false;
  52224. }
  52225. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  52226. var _this = this;
  52227. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  52228. _this.loadedMeshes = meshes;
  52229. _this.loadedParticleSystems = particleSystems;
  52230. _this.loadedSkeletons = skeletons;
  52231. _this.isCompleted = true;
  52232. if (_this.onSuccess) {
  52233. _this.onSuccess(_this);
  52234. }
  52235. onSuccess();
  52236. }, null, function () {
  52237. if (_this.onError) {
  52238. _this.onError(_this);
  52239. }
  52240. onError();
  52241. });
  52242. };
  52243. return MeshAssetTask;
  52244. })();
  52245. BABYLON.MeshAssetTask = MeshAssetTask;
  52246. var TextFileAssetTask = (function () {
  52247. function TextFileAssetTask(name, url) {
  52248. this.name = name;
  52249. this.url = url;
  52250. this.isCompleted = false;
  52251. }
  52252. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  52253. var _this = this;
  52254. BABYLON.Tools.LoadFile(this.url, function (data) {
  52255. _this.text = data;
  52256. _this.isCompleted = true;
  52257. if (_this.onSuccess) {
  52258. _this.onSuccess(_this);
  52259. }
  52260. onSuccess();
  52261. }, null, scene.database, false, function () {
  52262. if (_this.onError) {
  52263. _this.onError(_this);
  52264. }
  52265. onError();
  52266. });
  52267. };
  52268. return TextFileAssetTask;
  52269. })();
  52270. BABYLON.TextFileAssetTask = TextFileAssetTask;
  52271. var BinaryFileAssetTask = (function () {
  52272. function BinaryFileAssetTask(name, url) {
  52273. this.name = name;
  52274. this.url = url;
  52275. this.isCompleted = false;
  52276. }
  52277. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  52278. var _this = this;
  52279. BABYLON.Tools.LoadFile(this.url, function (data) {
  52280. _this.data = data;
  52281. _this.isCompleted = true;
  52282. if (_this.onSuccess) {
  52283. _this.onSuccess(_this);
  52284. }
  52285. onSuccess();
  52286. }, null, scene.database, true, function () {
  52287. if (_this.onError) {
  52288. _this.onError(_this);
  52289. }
  52290. onError();
  52291. });
  52292. };
  52293. return BinaryFileAssetTask;
  52294. })();
  52295. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  52296. var ImageAssetTask = (function () {
  52297. function ImageAssetTask(name, url) {
  52298. this.name = name;
  52299. this.url = url;
  52300. this.isCompleted = false;
  52301. }
  52302. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  52303. var _this = this;
  52304. var img = new Image();
  52305. BABYLON.Tools.SetCorsBehavior(this.url, img);
  52306. img.onload = function () {
  52307. _this.image = img;
  52308. _this.isCompleted = true;
  52309. if (_this.onSuccess) {
  52310. _this.onSuccess(_this);
  52311. }
  52312. onSuccess();
  52313. };
  52314. img.onerror = function () {
  52315. if (_this.onError) {
  52316. _this.onError(_this);
  52317. }
  52318. onError();
  52319. };
  52320. img.src = this.url;
  52321. };
  52322. return ImageAssetTask;
  52323. })();
  52324. BABYLON.ImageAssetTask = ImageAssetTask;
  52325. var TextureAssetTask = (function () {
  52326. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  52327. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52328. this.name = name;
  52329. this.url = url;
  52330. this.noMipmap = noMipmap;
  52331. this.invertY = invertY;
  52332. this.samplingMode = samplingMode;
  52333. this.isCompleted = false;
  52334. }
  52335. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  52336. var _this = this;
  52337. var onload = function () {
  52338. _this.isCompleted = true;
  52339. if (_this.onSuccess) {
  52340. _this.onSuccess(_this);
  52341. }
  52342. onSuccess();
  52343. };
  52344. var onerror = function () {
  52345. if (_this.onError) {
  52346. _this.onError(_this);
  52347. }
  52348. onError();
  52349. };
  52350. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  52351. };
  52352. return TextureAssetTask;
  52353. })();
  52354. BABYLON.TextureAssetTask = TextureAssetTask;
  52355. var AssetsManager = (function () {
  52356. function AssetsManager(scene) {
  52357. this._tasks = new Array();
  52358. this._waitingTasksCount = 0;
  52359. this.useDefaultLoadingScreen = true;
  52360. this._scene = scene;
  52361. }
  52362. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  52363. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  52364. this._tasks.push(task);
  52365. return task;
  52366. };
  52367. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  52368. var task = new TextFileAssetTask(taskName, url);
  52369. this._tasks.push(task);
  52370. return task;
  52371. };
  52372. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  52373. var task = new BinaryFileAssetTask(taskName, url);
  52374. this._tasks.push(task);
  52375. return task;
  52376. };
  52377. AssetsManager.prototype.addImageTask = function (taskName, url) {
  52378. var task = new ImageAssetTask(taskName, url);
  52379. this._tasks.push(task);
  52380. return task;
  52381. };
  52382. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  52383. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52384. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  52385. this._tasks.push(task);
  52386. return task;
  52387. };
  52388. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  52389. this._waitingTasksCount--;
  52390. if (this._waitingTasksCount === 0) {
  52391. if (this.onFinish) {
  52392. this.onFinish(this._tasks);
  52393. }
  52394. this._scene.getEngine().hideLoadingUI();
  52395. }
  52396. };
  52397. AssetsManager.prototype._runTask = function (task) {
  52398. var _this = this;
  52399. task.run(this._scene, function () {
  52400. if (_this.onTaskSuccess) {
  52401. _this.onTaskSuccess(task);
  52402. }
  52403. _this._decreaseWaitingTasksCount();
  52404. }, function () {
  52405. if (_this.onTaskError) {
  52406. _this.onTaskError(task);
  52407. }
  52408. _this._decreaseWaitingTasksCount();
  52409. });
  52410. };
  52411. AssetsManager.prototype.reset = function () {
  52412. this._tasks = new Array();
  52413. return this;
  52414. };
  52415. AssetsManager.prototype.load = function () {
  52416. this._waitingTasksCount = this._tasks.length;
  52417. if (this._waitingTasksCount === 0) {
  52418. if (this.onFinish) {
  52419. this.onFinish(this._tasks);
  52420. }
  52421. return this;
  52422. }
  52423. if (this.useDefaultLoadingScreen) {
  52424. this._scene.getEngine().displayLoadingUI();
  52425. }
  52426. for (var index = 0; index < this._tasks.length; index++) {
  52427. var task = this._tasks[index];
  52428. this._runTask(task);
  52429. }
  52430. return this;
  52431. };
  52432. return AssetsManager;
  52433. })();
  52434. BABYLON.AssetsManager = AssetsManager;
  52435. })(BABYLON || (BABYLON = {}));
  52436. var BABYLON;
  52437. (function (BABYLON) {
  52438. var VRCameraMetrics = (function () {
  52439. function VRCameraMetrics() {
  52440. this.compensateDistortion = true;
  52441. }
  52442. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  52443. get: function () {
  52444. return this.hResolution / (2 * this.vResolution);
  52445. },
  52446. enumerable: true,
  52447. configurable: true
  52448. });
  52449. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  52450. get: function () {
  52451. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  52452. },
  52453. enumerable: true,
  52454. configurable: true
  52455. });
  52456. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  52457. get: function () {
  52458. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  52459. var h = (4 * meters) / this.hScreenSize;
  52460. return BABYLON.Matrix.Translation(h, 0, 0);
  52461. },
  52462. enumerable: true,
  52463. configurable: true
  52464. });
  52465. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  52466. get: function () {
  52467. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  52468. var h = (4 * meters) / this.hScreenSize;
  52469. return BABYLON.Matrix.Translation(-h, 0, 0);
  52470. },
  52471. enumerable: true,
  52472. configurable: true
  52473. });
  52474. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  52475. get: function () {
  52476. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  52477. },
  52478. enumerable: true,
  52479. configurable: true
  52480. });
  52481. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  52482. get: function () {
  52483. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  52484. },
  52485. enumerable: true,
  52486. configurable: true
  52487. });
  52488. VRCameraMetrics.GetDefault = function () {
  52489. var result = new VRCameraMetrics();
  52490. result.hResolution = 1280;
  52491. result.vResolution = 800;
  52492. result.hScreenSize = 0.149759993;
  52493. result.vScreenSize = 0.0935999975;
  52494. result.vScreenCenter = 0.0467999987,
  52495. result.eyeToScreenDistance = 0.0410000011;
  52496. result.lensSeparationDistance = 0.0635000020;
  52497. result.interpupillaryDistance = 0.0640000030;
  52498. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  52499. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  52500. result.postProcessScaleFactor = 1.714605507808412;
  52501. result.lensCenterOffset = 0.151976421;
  52502. return result;
  52503. };
  52504. return VRCameraMetrics;
  52505. })();
  52506. BABYLON.VRCameraMetrics = VRCameraMetrics;
  52507. })(BABYLON || (BABYLON = {}));
  52508. var BABYLON;
  52509. (function (BABYLON) {
  52510. var WebVRFreeCamera = (function (_super) {
  52511. __extends(WebVRFreeCamera, _super);
  52512. function WebVRFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  52513. if (compensateDistortion === void 0) { compensateDistortion = true; }
  52514. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  52515. _super.call(this, name, position, scene);
  52516. this._hmdDevice = null;
  52517. this._sensorDevice = null;
  52518. this._cacheState = null;
  52519. this._vrEnabled = false;
  52520. vrCameraMetrics.compensateDistortion = compensateDistortion;
  52521. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  52522. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  52523. this.rotationQuaternion = new BABYLON.Quaternion();
  52524. this._quaternionCache = new BABYLON.Quaternion();
  52525. }
  52526. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  52527. var size = devices.length;
  52528. var i = 0;
  52529. // Reset devices.
  52530. this._sensorDevice = null;
  52531. this._hmdDevice = null;
  52532. // Search for a HmdDevice.
  52533. while (i < size && this._hmdDevice === null) {
  52534. if (devices[i] instanceof HMDVRDevice) {
  52535. this._hmdDevice = devices[i];
  52536. }
  52537. i++;
  52538. }
  52539. i = 0;
  52540. while (i < size && this._sensorDevice === null) {
  52541. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  52542. this._sensorDevice = devices[i];
  52543. }
  52544. i++;
  52545. }
  52546. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  52547. };
  52548. WebVRFreeCamera.prototype._checkInputs = function () {
  52549. if (this._vrEnabled) {
  52550. this._cacheState = this._sensorDevice.getState();
  52551. this.rotationQuaternion.copyFrom(this._cacheState.orientation);
  52552. //Flip in XY plane
  52553. this.rotationQuaternion.z *= -1;
  52554. this.rotationQuaternion.w *= -1;
  52555. if (this._initialQuaternion) {
  52556. this._quaternionCache.copyFrom(this.rotationQuaternion);
  52557. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  52558. }
  52559. }
  52560. _super.prototype._checkInputs.call(this);
  52561. };
  52562. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  52563. _super.prototype.attachControl.call(this, element, noPreventDefault);
  52564. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  52565. if (navigator.getVRDevices) {
  52566. navigator.getVRDevices().then(this._getWebVRDevices);
  52567. }
  52568. else if (navigator.mozGetVRDevices) {
  52569. navigator.mozGetVRDevices(this._getWebVRDevices);
  52570. }
  52571. };
  52572. WebVRFreeCamera.prototype.detachControl = function (element) {
  52573. _super.prototype.detachControl.call(this, element);
  52574. this._vrEnabled = false;
  52575. };
  52576. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  52577. if (!this._hmdDevice)
  52578. return;
  52579. this.getEngine().switchFullscreen(requestPointerlock, { vrDisplay: this._hmdDevice });
  52580. };
  52581. WebVRFreeCamera.prototype.getTypeName = function () {
  52582. return "WebVRFreeCamera";
  52583. };
  52584. WebVRFreeCamera.prototype.resetToCurrentRotation = function (axis) {
  52585. var _this = this;
  52586. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  52587. //can only work if this camera has a rotation quaternion already.
  52588. if (!this.rotationQuaternion)
  52589. return;
  52590. if (!this._initialQuaternion) {
  52591. this._initialQuaternion = new BABYLON.Quaternion();
  52592. }
  52593. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  52594. ['x', 'y', 'z'].forEach(function (axisName) {
  52595. if (!axis[axisName]) {
  52596. _this._initialQuaternion[axisName] = 0;
  52597. }
  52598. else {
  52599. _this._initialQuaternion[axisName] *= -1;
  52600. }
  52601. });
  52602. this._initialQuaternion.normalize();
  52603. };
  52604. return WebVRFreeCamera;
  52605. })(BABYLON.FreeCamera);
  52606. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  52607. })(BABYLON || (BABYLON = {}));
  52608. var BABYLON;
  52609. (function (BABYLON) {
  52610. // Standard optimizations
  52611. var SceneOptimization = (function () {
  52612. function SceneOptimization(priority) {
  52613. if (priority === void 0) { priority = 0; }
  52614. this.priority = priority;
  52615. this.apply = function (scene) {
  52616. return true; // Return true if everything that can be done was applied
  52617. };
  52618. }
  52619. return SceneOptimization;
  52620. })();
  52621. BABYLON.SceneOptimization = SceneOptimization;
  52622. var TextureOptimization = (function (_super) {
  52623. __extends(TextureOptimization, _super);
  52624. function TextureOptimization(priority, maximumSize) {
  52625. var _this = this;
  52626. if (priority === void 0) { priority = 0; }
  52627. if (maximumSize === void 0) { maximumSize = 1024; }
  52628. _super.call(this, priority);
  52629. this.priority = priority;
  52630. this.maximumSize = maximumSize;
  52631. this.apply = function (scene) {
  52632. var allDone = true;
  52633. for (var index = 0; index < scene.textures.length; index++) {
  52634. var texture = scene.textures[index];
  52635. if (!texture.canRescale) {
  52636. continue;
  52637. }
  52638. var currentSize = texture.getSize();
  52639. var maxDimension = Math.max(currentSize.width, currentSize.height);
  52640. if (maxDimension > _this.maximumSize) {
  52641. texture.scale(0.5);
  52642. allDone = false;
  52643. }
  52644. }
  52645. return allDone;
  52646. };
  52647. }
  52648. return TextureOptimization;
  52649. })(SceneOptimization);
  52650. BABYLON.TextureOptimization = TextureOptimization;
  52651. var HardwareScalingOptimization = (function (_super) {
  52652. __extends(HardwareScalingOptimization, _super);
  52653. function HardwareScalingOptimization(priority, maximumScale) {
  52654. var _this = this;
  52655. if (priority === void 0) { priority = 0; }
  52656. if (maximumScale === void 0) { maximumScale = 2; }
  52657. _super.call(this, priority);
  52658. this.priority = priority;
  52659. this.maximumScale = maximumScale;
  52660. this._currentScale = 1;
  52661. this.apply = function (scene) {
  52662. _this._currentScale++;
  52663. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  52664. return _this._currentScale >= _this.maximumScale;
  52665. };
  52666. }
  52667. return HardwareScalingOptimization;
  52668. })(SceneOptimization);
  52669. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  52670. var ShadowsOptimization = (function (_super) {
  52671. __extends(ShadowsOptimization, _super);
  52672. function ShadowsOptimization() {
  52673. _super.apply(this, arguments);
  52674. this.apply = function (scene) {
  52675. scene.shadowsEnabled = false;
  52676. return true;
  52677. };
  52678. }
  52679. return ShadowsOptimization;
  52680. })(SceneOptimization);
  52681. BABYLON.ShadowsOptimization = ShadowsOptimization;
  52682. var PostProcessesOptimization = (function (_super) {
  52683. __extends(PostProcessesOptimization, _super);
  52684. function PostProcessesOptimization() {
  52685. _super.apply(this, arguments);
  52686. this.apply = function (scene) {
  52687. scene.postProcessesEnabled = false;
  52688. return true;
  52689. };
  52690. }
  52691. return PostProcessesOptimization;
  52692. })(SceneOptimization);
  52693. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  52694. var LensFlaresOptimization = (function (_super) {
  52695. __extends(LensFlaresOptimization, _super);
  52696. function LensFlaresOptimization() {
  52697. _super.apply(this, arguments);
  52698. this.apply = function (scene) {
  52699. scene.lensFlaresEnabled = false;
  52700. return true;
  52701. };
  52702. }
  52703. return LensFlaresOptimization;
  52704. })(SceneOptimization);
  52705. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  52706. var ParticlesOptimization = (function (_super) {
  52707. __extends(ParticlesOptimization, _super);
  52708. function ParticlesOptimization() {
  52709. _super.apply(this, arguments);
  52710. this.apply = function (scene) {
  52711. scene.particlesEnabled = false;
  52712. return true;
  52713. };
  52714. }
  52715. return ParticlesOptimization;
  52716. })(SceneOptimization);
  52717. BABYLON.ParticlesOptimization = ParticlesOptimization;
  52718. var RenderTargetsOptimization = (function (_super) {
  52719. __extends(RenderTargetsOptimization, _super);
  52720. function RenderTargetsOptimization() {
  52721. _super.apply(this, arguments);
  52722. this.apply = function (scene) {
  52723. scene.renderTargetsEnabled = false;
  52724. return true;
  52725. };
  52726. }
  52727. return RenderTargetsOptimization;
  52728. })(SceneOptimization);
  52729. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  52730. var MergeMeshesOptimization = (function (_super) {
  52731. __extends(MergeMeshesOptimization, _super);
  52732. function MergeMeshesOptimization() {
  52733. var _this = this;
  52734. _super.apply(this, arguments);
  52735. this._canBeMerged = function (abstractMesh) {
  52736. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  52737. return false;
  52738. }
  52739. var mesh = abstractMesh;
  52740. if (!mesh.isVisible || !mesh.isEnabled()) {
  52741. return false;
  52742. }
  52743. if (mesh.instances.length > 0) {
  52744. return false;
  52745. }
  52746. if (mesh.skeleton || mesh.hasLODLevels) {
  52747. return false;
  52748. }
  52749. if (mesh.parent) {
  52750. return false;
  52751. }
  52752. return true;
  52753. };
  52754. this.apply = function (scene, updateSelectionTree) {
  52755. var globalPool = scene.meshes.slice(0);
  52756. var globalLength = globalPool.length;
  52757. for (var index = 0; index < globalLength; index++) {
  52758. var currentPool = new Array();
  52759. var current = globalPool[index];
  52760. // Checks
  52761. if (!_this._canBeMerged(current)) {
  52762. continue;
  52763. }
  52764. currentPool.push(current);
  52765. // Find compatible meshes
  52766. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  52767. var otherMesh = globalPool[subIndex];
  52768. if (!_this._canBeMerged(otherMesh)) {
  52769. continue;
  52770. }
  52771. if (otherMesh.material !== current.material) {
  52772. continue;
  52773. }
  52774. if (otherMesh.checkCollisions !== current.checkCollisions) {
  52775. continue;
  52776. }
  52777. currentPool.push(otherMesh);
  52778. globalLength--;
  52779. globalPool.splice(subIndex, 1);
  52780. subIndex--;
  52781. }
  52782. if (currentPool.length < 2) {
  52783. continue;
  52784. }
  52785. // Merge meshes
  52786. BABYLON.Mesh.MergeMeshes(currentPool);
  52787. }
  52788. if (updateSelectionTree != undefined) {
  52789. if (updateSelectionTree) {
  52790. scene.createOrUpdateSelectionOctree();
  52791. }
  52792. }
  52793. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  52794. scene.createOrUpdateSelectionOctree();
  52795. }
  52796. return true;
  52797. };
  52798. }
  52799. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  52800. get: function () {
  52801. return MergeMeshesOptimization._UpdateSelectionTree;
  52802. },
  52803. set: function (value) {
  52804. MergeMeshesOptimization._UpdateSelectionTree = value;
  52805. },
  52806. enumerable: true,
  52807. configurable: true
  52808. });
  52809. MergeMeshesOptimization._UpdateSelectionTree = false;
  52810. return MergeMeshesOptimization;
  52811. })(SceneOptimization);
  52812. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  52813. // Options
  52814. var SceneOptimizerOptions = (function () {
  52815. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  52816. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  52817. if (trackerDuration === void 0) { trackerDuration = 2000; }
  52818. this.targetFrameRate = targetFrameRate;
  52819. this.trackerDuration = trackerDuration;
  52820. this.optimizations = new Array();
  52821. }
  52822. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  52823. var result = new SceneOptimizerOptions(targetFrameRate);
  52824. var priority = 0;
  52825. result.optimizations.push(new MergeMeshesOptimization(priority));
  52826. result.optimizations.push(new ShadowsOptimization(priority));
  52827. result.optimizations.push(new LensFlaresOptimization(priority));
  52828. // Next priority
  52829. priority++;
  52830. result.optimizations.push(new PostProcessesOptimization(priority));
  52831. result.optimizations.push(new ParticlesOptimization(priority));
  52832. // Next priority
  52833. priority++;
  52834. result.optimizations.push(new TextureOptimization(priority, 1024));
  52835. return result;
  52836. };
  52837. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  52838. var result = new SceneOptimizerOptions(targetFrameRate);
  52839. var priority = 0;
  52840. result.optimizations.push(new MergeMeshesOptimization(priority));
  52841. result.optimizations.push(new ShadowsOptimization(priority));
  52842. result.optimizations.push(new LensFlaresOptimization(priority));
  52843. // Next priority
  52844. priority++;
  52845. result.optimizations.push(new PostProcessesOptimization(priority));
  52846. result.optimizations.push(new ParticlesOptimization(priority));
  52847. // Next priority
  52848. priority++;
  52849. result.optimizations.push(new TextureOptimization(priority, 512));
  52850. // Next priority
  52851. priority++;
  52852. result.optimizations.push(new RenderTargetsOptimization(priority));
  52853. // Next priority
  52854. priority++;
  52855. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  52856. return result;
  52857. };
  52858. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  52859. var result = new SceneOptimizerOptions(targetFrameRate);
  52860. var priority = 0;
  52861. result.optimizations.push(new MergeMeshesOptimization(priority));
  52862. result.optimizations.push(new ShadowsOptimization(priority));
  52863. result.optimizations.push(new LensFlaresOptimization(priority));
  52864. // Next priority
  52865. priority++;
  52866. result.optimizations.push(new PostProcessesOptimization(priority));
  52867. result.optimizations.push(new ParticlesOptimization(priority));
  52868. // Next priority
  52869. priority++;
  52870. result.optimizations.push(new TextureOptimization(priority, 256));
  52871. // Next priority
  52872. priority++;
  52873. result.optimizations.push(new RenderTargetsOptimization(priority));
  52874. // Next priority
  52875. priority++;
  52876. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  52877. return result;
  52878. };
  52879. return SceneOptimizerOptions;
  52880. })();
  52881. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  52882. // Scene optimizer tool
  52883. var SceneOptimizer = (function () {
  52884. function SceneOptimizer() {
  52885. }
  52886. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  52887. // TODO: add an epsilon
  52888. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  52889. if (onSuccess) {
  52890. onSuccess();
  52891. }
  52892. return;
  52893. }
  52894. // Apply current level of optimizations
  52895. var allDone = true;
  52896. var noOptimizationApplied = true;
  52897. for (var index = 0; index < options.optimizations.length; index++) {
  52898. var optimization = options.optimizations[index];
  52899. if (optimization.priority === currentPriorityLevel) {
  52900. noOptimizationApplied = false;
  52901. allDone = allDone && optimization.apply(scene);
  52902. }
  52903. }
  52904. // If no optimization was applied, this is a failure :(
  52905. if (noOptimizationApplied) {
  52906. if (onFailure) {
  52907. onFailure();
  52908. }
  52909. return;
  52910. }
  52911. // If all optimizations were done, move to next level
  52912. if (allDone) {
  52913. currentPriorityLevel++;
  52914. }
  52915. // Let's the system running for a specific amount of time before checking FPS
  52916. scene.executeWhenReady(function () {
  52917. setTimeout(function () {
  52918. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  52919. }, options.trackerDuration);
  52920. });
  52921. };
  52922. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  52923. if (!options) {
  52924. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  52925. }
  52926. // Let's the system running for a specific amount of time before checking FPS
  52927. scene.executeWhenReady(function () {
  52928. setTimeout(function () {
  52929. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  52930. }, options.trackerDuration);
  52931. });
  52932. };
  52933. return SceneOptimizer;
  52934. })();
  52935. BABYLON.SceneOptimizer = SceneOptimizer;
  52936. })(BABYLON || (BABYLON = {}));
  52937. var BABYLON;
  52938. (function (BABYLON) {
  52939. var Internals;
  52940. (function (Internals) {
  52941. var MeshLODLevel = (function () {
  52942. function MeshLODLevel(distance, mesh) {
  52943. this.distance = distance;
  52944. this.mesh = mesh;
  52945. }
  52946. return MeshLODLevel;
  52947. })();
  52948. Internals.MeshLODLevel = MeshLODLevel;
  52949. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  52950. })(BABYLON || (BABYLON = {}));
  52951. var BABYLON;
  52952. (function (BABYLON) {
  52953. var RawTexture = (function (_super) {
  52954. __extends(RawTexture, _super);
  52955. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  52956. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52957. if (invertY === void 0) { invertY = false; }
  52958. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52959. _super.call(this, null, scene, !generateMipMaps, invertY);
  52960. this.format = format;
  52961. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  52962. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52963. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52964. }
  52965. RawTexture.prototype.update = function (data) {
  52966. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  52967. };
  52968. // Statics
  52969. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52970. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52971. if (invertY === void 0) { invertY = false; }
  52972. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52973. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  52974. };
  52975. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52976. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52977. if (invertY === void 0) { invertY = false; }
  52978. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52979. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  52980. };
  52981. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52982. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52983. if (invertY === void 0) { invertY = false; }
  52984. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52985. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  52986. };
  52987. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52988. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52989. if (invertY === void 0) { invertY = false; }
  52990. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52991. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  52992. };
  52993. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52994. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52995. if (invertY === void 0) { invertY = false; }
  52996. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52997. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  52998. };
  52999. return RawTexture;
  53000. })(BABYLON.Texture);
  53001. BABYLON.RawTexture = RawTexture;
  53002. })(BABYLON || (BABYLON = {}));
  53003. var BABYLON;
  53004. (function (BABYLON) {
  53005. var IndexedVector2 = (function (_super) {
  53006. __extends(IndexedVector2, _super);
  53007. function IndexedVector2(original, index) {
  53008. _super.call(this, original.x, original.y);
  53009. this.index = index;
  53010. }
  53011. return IndexedVector2;
  53012. })(BABYLON.Vector2);
  53013. var PolygonPoints = (function () {
  53014. function PolygonPoints() {
  53015. this.elements = new Array();
  53016. }
  53017. PolygonPoints.prototype.add = function (originalPoints) {
  53018. var _this = this;
  53019. var result = new Array();
  53020. originalPoints.forEach(function (point) {
  53021. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  53022. var newPoint = new IndexedVector2(point, _this.elements.length);
  53023. result.push(newPoint);
  53024. _this.elements.push(newPoint);
  53025. }
  53026. });
  53027. return result;
  53028. };
  53029. PolygonPoints.prototype.computeBounds = function () {
  53030. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  53031. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  53032. this.elements.forEach(function (point) {
  53033. // x
  53034. if (point.x < lmin.x) {
  53035. lmin.x = point.x;
  53036. }
  53037. else if (point.x > lmax.x) {
  53038. lmax.x = point.x;
  53039. }
  53040. // y
  53041. if (point.y < lmin.y) {
  53042. lmin.y = point.y;
  53043. }
  53044. else if (point.y > lmax.y) {
  53045. lmax.y = point.y;
  53046. }
  53047. });
  53048. return {
  53049. min: lmin,
  53050. max: lmax,
  53051. width: lmax.x - lmin.x,
  53052. height: lmax.y - lmin.y
  53053. };
  53054. };
  53055. return PolygonPoints;
  53056. })();
  53057. var Polygon = (function () {
  53058. function Polygon() {
  53059. }
  53060. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  53061. return [
  53062. new BABYLON.Vector2(xmin, ymin),
  53063. new BABYLON.Vector2(xmax, ymin),
  53064. new BABYLON.Vector2(xmax, ymax),
  53065. new BABYLON.Vector2(xmin, ymax)
  53066. ];
  53067. };
  53068. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  53069. if (cx === void 0) { cx = 0; }
  53070. if (cy === void 0) { cy = 0; }
  53071. if (numberOfSides === void 0) { numberOfSides = 32; }
  53072. var result = new Array();
  53073. var angle = 0;
  53074. var increment = (Math.PI * 2) / numberOfSides;
  53075. for (var i = 0; i < numberOfSides; i++) {
  53076. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  53077. angle -= increment;
  53078. }
  53079. return result;
  53080. };
  53081. Polygon.Parse = function (input) {
  53082. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  53083. var i, result = [];
  53084. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  53085. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  53086. }
  53087. return result;
  53088. };
  53089. Polygon.StartingAt = function (x, y) {
  53090. return BABYLON.Path2.StartingAt(x, y);
  53091. };
  53092. return Polygon;
  53093. })();
  53094. BABYLON.Polygon = Polygon;
  53095. var PolygonMeshBuilder = (function () {
  53096. function PolygonMeshBuilder(name, contours, scene) {
  53097. this._points = new PolygonPoints();
  53098. this._outlinepoints = new PolygonPoints();
  53099. this._holes = [];
  53100. this._epoints = new Array();
  53101. this._eholes = new Array();
  53102. this._name = name;
  53103. this._scene = scene;
  53104. var points;
  53105. if (contours instanceof BABYLON.Path2) {
  53106. points = contours.getPoints();
  53107. }
  53108. else {
  53109. points = contours;
  53110. }
  53111. this._addToepoint(points);
  53112. this._points.add(points);
  53113. this._outlinepoints.add(points);
  53114. }
  53115. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  53116. for (var _i = 0; _i < points.length; _i++) {
  53117. var p = points[_i];
  53118. this._epoints.push(p.x, p.y);
  53119. }
  53120. };
  53121. PolygonMeshBuilder.prototype.addHole = function (hole) {
  53122. this._points.add(hole);
  53123. var holepoints = new PolygonPoints();
  53124. holepoints.add(hole);
  53125. this._holes.push(holepoints);
  53126. this._eholes.push(this._epoints.length / 2);
  53127. this._addToepoint(hole);
  53128. return this;
  53129. };
  53130. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  53131. var _this = this;
  53132. if (updatable === void 0) { updatable = false; }
  53133. var result = new BABYLON.Mesh(this._name, this._scene);
  53134. var normals = [];
  53135. var positions = [];
  53136. var uvs = [];
  53137. var bounds = this._points.computeBounds();
  53138. this._points.elements.forEach(function (p) {
  53139. normals.push(0, 1.0, 0);
  53140. positions.push(p.x, 0, p.y);
  53141. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  53142. });
  53143. var indices = [];
  53144. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  53145. for (var i = 0; i < res.length; i++) {
  53146. indices.push(res[i]);
  53147. }
  53148. if (depth > 0) {
  53149. var positionscount = (positions.length / 3); //get the current pointcount
  53150. this._points.elements.forEach(function (p) {
  53151. normals.push(0, -1.0, 0);
  53152. positions.push(p.x, -depth, p.y);
  53153. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  53154. });
  53155. var totalCount = indices.length;
  53156. for (var i = 0; i < totalCount; i += 3) {
  53157. var i0 = indices[i + 0];
  53158. var i1 = indices[i + 1];
  53159. var i2 = indices[i + 2];
  53160. indices.push(i2 + positionscount);
  53161. indices.push(i1 + positionscount);
  53162. indices.push(i0 + positionscount);
  53163. }
  53164. //Add the sides
  53165. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  53166. this._holes.forEach(function (hole) {
  53167. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  53168. });
  53169. }
  53170. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  53171. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  53172. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  53173. result.setIndices(indices);
  53174. return result;
  53175. };
  53176. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  53177. var StartIndex = positions.length / 3;
  53178. var ulength = 0;
  53179. for (var i = 0; i < points.elements.length; i++) {
  53180. var p = points.elements[i];
  53181. var p1;
  53182. if ((i + 1) > points.elements.length - 1) {
  53183. p1 = points.elements[0];
  53184. }
  53185. else {
  53186. p1 = points.elements[i + 1];
  53187. }
  53188. positions.push(p.x, 0, p.y);
  53189. positions.push(p.x, -depth, p.y);
  53190. positions.push(p1.x, 0, p1.y);
  53191. positions.push(p1.x, -depth, p1.y);
  53192. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  53193. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  53194. var v3 = v2.subtract(v1);
  53195. var v4 = new BABYLON.Vector3(0, 1, 0);
  53196. var vn = BABYLON.Vector3.Cross(v3, v4);
  53197. vn = vn.normalize();
  53198. uvs.push(ulength / bounds.width, 0);
  53199. uvs.push(ulength / bounds.width, 1);
  53200. ulength += v3.length();
  53201. uvs.push((ulength / bounds.width), 0);
  53202. uvs.push((ulength / bounds.width), 1);
  53203. if (!flip) {
  53204. normals.push(-vn.x, -vn.y, -vn.z);
  53205. normals.push(-vn.x, -vn.y, -vn.z);
  53206. normals.push(-vn.x, -vn.y, -vn.z);
  53207. normals.push(-vn.x, -vn.y, -vn.z);
  53208. indices.push(StartIndex);
  53209. indices.push(StartIndex + 1);
  53210. indices.push(StartIndex + 2);
  53211. indices.push(StartIndex + 1);
  53212. indices.push(StartIndex + 3);
  53213. indices.push(StartIndex + 2);
  53214. }
  53215. else {
  53216. normals.push(vn.x, vn.y, vn.z);
  53217. normals.push(vn.x, vn.y, vn.z);
  53218. normals.push(vn.x, vn.y, vn.z);
  53219. normals.push(vn.x, vn.y, vn.z);
  53220. indices.push(StartIndex);
  53221. indices.push(StartIndex + 2);
  53222. indices.push(StartIndex + 1);
  53223. indices.push(StartIndex + 1);
  53224. indices.push(StartIndex + 2);
  53225. indices.push(StartIndex + 3);
  53226. }
  53227. StartIndex += 4;
  53228. }
  53229. ;
  53230. };
  53231. return PolygonMeshBuilder;
  53232. })();
  53233. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  53234. })(BABYLON || (BABYLON = {}));
  53235. var BABYLON;
  53236. (function (BABYLON) {
  53237. var Octree = (function () {
  53238. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  53239. if (maxDepth === void 0) { maxDepth = 2; }
  53240. this.maxDepth = maxDepth;
  53241. this.dynamicContent = new Array();
  53242. this._maxBlockCapacity = maxBlockCapacity || 64;
  53243. this._selectionContent = new BABYLON.SmartArray(1024);
  53244. this._creationFunc = creationFunc;
  53245. }
  53246. // Methods
  53247. Octree.prototype.update = function (worldMin, worldMax, entries) {
  53248. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  53249. };
  53250. Octree.prototype.addMesh = function (entry) {
  53251. for (var index = 0; index < this.blocks.length; index++) {
  53252. var block = this.blocks[index];
  53253. block.addEntry(entry);
  53254. }
  53255. };
  53256. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  53257. this._selectionContent.reset();
  53258. for (var index = 0; index < this.blocks.length; index++) {
  53259. var block = this.blocks[index];
  53260. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  53261. }
  53262. if (allowDuplicate) {
  53263. this._selectionContent.concat(this.dynamicContent);
  53264. }
  53265. else {
  53266. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  53267. }
  53268. return this._selectionContent;
  53269. };
  53270. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  53271. this._selectionContent.reset();
  53272. for (var index = 0; index < this.blocks.length; index++) {
  53273. var block = this.blocks[index];
  53274. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  53275. }
  53276. if (allowDuplicate) {
  53277. this._selectionContent.concat(this.dynamicContent);
  53278. }
  53279. else {
  53280. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  53281. }
  53282. return this._selectionContent;
  53283. };
  53284. Octree.prototype.intersectsRay = function (ray) {
  53285. this._selectionContent.reset();
  53286. for (var index = 0; index < this.blocks.length; index++) {
  53287. var block = this.blocks[index];
  53288. block.intersectsRay(ray, this._selectionContent);
  53289. }
  53290. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  53291. return this._selectionContent;
  53292. };
  53293. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  53294. target.blocks = new Array();
  53295. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  53296. // Segmenting space
  53297. for (var x = 0; x < 2; x++) {
  53298. for (var y = 0; y < 2; y++) {
  53299. for (var z = 0; z < 2; z++) {
  53300. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  53301. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  53302. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  53303. block.addEntries(entries);
  53304. target.blocks.push(block);
  53305. }
  53306. }
  53307. }
  53308. };
  53309. Octree.CreationFuncForMeshes = function (entry, block) {
  53310. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  53311. block.entries.push(entry);
  53312. }
  53313. };
  53314. Octree.CreationFuncForSubMeshes = function (entry, block) {
  53315. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  53316. block.entries.push(entry);
  53317. }
  53318. };
  53319. return Octree;
  53320. })();
  53321. BABYLON.Octree = Octree;
  53322. })(BABYLON || (BABYLON = {}));
  53323. var BABYLON;
  53324. (function (BABYLON) {
  53325. var OctreeBlock = (function () {
  53326. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  53327. this.entries = new Array();
  53328. this._boundingVectors = new Array();
  53329. this._capacity = capacity;
  53330. this._depth = depth;
  53331. this._maxDepth = maxDepth;
  53332. this._creationFunc = creationFunc;
  53333. this._minPoint = minPoint;
  53334. this._maxPoint = maxPoint;
  53335. this._boundingVectors.push(minPoint.clone());
  53336. this._boundingVectors.push(maxPoint.clone());
  53337. this._boundingVectors.push(minPoint.clone());
  53338. this._boundingVectors[2].x = maxPoint.x;
  53339. this._boundingVectors.push(minPoint.clone());
  53340. this._boundingVectors[3].y = maxPoint.y;
  53341. this._boundingVectors.push(minPoint.clone());
  53342. this._boundingVectors[4].z = maxPoint.z;
  53343. this._boundingVectors.push(maxPoint.clone());
  53344. this._boundingVectors[5].z = minPoint.z;
  53345. this._boundingVectors.push(maxPoint.clone());
  53346. this._boundingVectors[6].x = minPoint.x;
  53347. this._boundingVectors.push(maxPoint.clone());
  53348. this._boundingVectors[7].y = minPoint.y;
  53349. }
  53350. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  53351. // Property
  53352. get: function () {
  53353. return this._capacity;
  53354. },
  53355. enumerable: true,
  53356. configurable: true
  53357. });
  53358. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  53359. get: function () {
  53360. return this._minPoint;
  53361. },
  53362. enumerable: true,
  53363. configurable: true
  53364. });
  53365. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  53366. get: function () {
  53367. return this._maxPoint;
  53368. },
  53369. enumerable: true,
  53370. configurable: true
  53371. });
  53372. // Methods
  53373. OctreeBlock.prototype.addEntry = function (entry) {
  53374. if (this.blocks) {
  53375. for (var index = 0; index < this.blocks.length; index++) {
  53376. var block = this.blocks[index];
  53377. block.addEntry(entry);
  53378. }
  53379. return;
  53380. }
  53381. this._creationFunc(entry, this);
  53382. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  53383. this.createInnerBlocks();
  53384. }
  53385. };
  53386. OctreeBlock.prototype.addEntries = function (entries) {
  53387. for (var index = 0; index < entries.length; index++) {
  53388. var mesh = entries[index];
  53389. this.addEntry(mesh);
  53390. }
  53391. };
  53392. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  53393. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  53394. if (this.blocks) {
  53395. for (var index = 0; index < this.blocks.length; index++) {
  53396. var block = this.blocks[index];
  53397. block.select(frustumPlanes, selection, allowDuplicate);
  53398. }
  53399. return;
  53400. }
  53401. if (allowDuplicate) {
  53402. selection.concat(this.entries);
  53403. }
  53404. else {
  53405. selection.concatWithNoDuplicate(this.entries);
  53406. }
  53407. }
  53408. };
  53409. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  53410. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  53411. if (this.blocks) {
  53412. for (var index = 0; index < this.blocks.length; index++) {
  53413. var block = this.blocks[index];
  53414. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  53415. }
  53416. return;
  53417. }
  53418. if (allowDuplicate) {
  53419. selection.concat(this.entries);
  53420. }
  53421. else {
  53422. selection.concatWithNoDuplicate(this.entries);
  53423. }
  53424. }
  53425. };
  53426. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  53427. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  53428. if (this.blocks) {
  53429. for (var index = 0; index < this.blocks.length; index++) {
  53430. var block = this.blocks[index];
  53431. block.intersectsRay(ray, selection);
  53432. }
  53433. return;
  53434. }
  53435. selection.concatWithNoDuplicate(this.entries);
  53436. }
  53437. };
  53438. OctreeBlock.prototype.createInnerBlocks = function () {
  53439. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  53440. };
  53441. return OctreeBlock;
  53442. })();
  53443. BABYLON.OctreeBlock = OctreeBlock;
  53444. })(BABYLON || (BABYLON = {}));
  53445. var BABYLON;
  53446. (function (BABYLON) {
  53447. var BlurPostProcess = (function (_super) {
  53448. __extends(BlurPostProcess, _super);
  53449. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  53450. var _this = this;
  53451. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53452. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  53453. this.direction = direction;
  53454. this.blurWidth = blurWidth;
  53455. this.onApplyObservable.add(function (effect) {
  53456. effect.setFloat2("screenSize", _this.width, _this.height);
  53457. effect.setVector2("direction", _this.direction);
  53458. effect.setFloat("blurWidth", _this.blurWidth);
  53459. });
  53460. }
  53461. return BlurPostProcess;
  53462. })(BABYLON.PostProcess);
  53463. BABYLON.BlurPostProcess = BlurPostProcess;
  53464. })(BABYLON || (BABYLON = {}));
  53465. var BABYLON;
  53466. (function (BABYLON) {
  53467. var RefractionPostProcess = (function (_super) {
  53468. __extends(RefractionPostProcess, _super);
  53469. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  53470. var _this = this;
  53471. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  53472. this.color = color;
  53473. this.depth = depth;
  53474. this.colorLevel = colorLevel;
  53475. this.onActivateObservable.add(function (cam) {
  53476. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  53477. });
  53478. this.onApplyObservable.add(function (effect) {
  53479. effect.setColor3("baseColor", _this.color);
  53480. effect.setFloat("depth", _this.depth);
  53481. effect.setFloat("colorLevel", _this.colorLevel);
  53482. effect.setTexture("refractionSampler", _this._refRexture);
  53483. });
  53484. }
  53485. // Methods
  53486. RefractionPostProcess.prototype.dispose = function (camera) {
  53487. if (this._refRexture) {
  53488. this._refRexture.dispose();
  53489. }
  53490. _super.prototype.dispose.call(this, camera);
  53491. };
  53492. return RefractionPostProcess;
  53493. })(BABYLON.PostProcess);
  53494. BABYLON.RefractionPostProcess = RefractionPostProcess;
  53495. })(BABYLON || (BABYLON = {}));
  53496. var BABYLON;
  53497. (function (BABYLON) {
  53498. var BlackAndWhitePostProcess = (function (_super) {
  53499. __extends(BlackAndWhitePostProcess, _super);
  53500. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  53501. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  53502. }
  53503. return BlackAndWhitePostProcess;
  53504. })(BABYLON.PostProcess);
  53505. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  53506. })(BABYLON || (BABYLON = {}));
  53507. var BABYLON;
  53508. (function (BABYLON) {
  53509. var ConvolutionPostProcess = (function (_super) {
  53510. __extends(ConvolutionPostProcess, _super);
  53511. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  53512. var _this = this;
  53513. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  53514. this.kernel = kernel;
  53515. this.onApply = function (effect) {
  53516. effect.setFloat2("screenSize", _this.width, _this.height);
  53517. effect.setArray("kernel", _this.kernel);
  53518. };
  53519. }
  53520. // Statics
  53521. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  53522. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  53523. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  53524. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  53525. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  53526. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  53527. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  53528. return ConvolutionPostProcess;
  53529. })(BABYLON.PostProcess);
  53530. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  53531. })(BABYLON || (BABYLON = {}));
  53532. var BABYLON;
  53533. (function (BABYLON) {
  53534. var FilterPostProcess = (function (_super) {
  53535. __extends(FilterPostProcess, _super);
  53536. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  53537. var _this = this;
  53538. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  53539. this.kernelMatrix = kernelMatrix;
  53540. this.onApply = function (effect) {
  53541. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  53542. };
  53543. }
  53544. return FilterPostProcess;
  53545. })(BABYLON.PostProcess);
  53546. BABYLON.FilterPostProcess = FilterPostProcess;
  53547. })(BABYLON || (BABYLON = {}));
  53548. var BABYLON;
  53549. (function (BABYLON) {
  53550. var FxaaPostProcess = (function (_super) {
  53551. __extends(FxaaPostProcess, _super);
  53552. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  53553. var _this = this;
  53554. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  53555. this.onSizeChangedObservable.add(function () {
  53556. _this.texelWidth = 1.0 / _this.width;
  53557. _this.texelHeight = 1.0 / _this.height;
  53558. });
  53559. this.onApplyObservable.add(function (effect) {
  53560. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  53561. });
  53562. }
  53563. return FxaaPostProcess;
  53564. })(BABYLON.PostProcess);
  53565. BABYLON.FxaaPostProcess = FxaaPostProcess;
  53566. })(BABYLON || (BABYLON = {}));
  53567. var BABYLON;
  53568. (function (BABYLON) {
  53569. var StereoscopicInterlacePostProcess = (function (_super) {
  53570. __extends(StereoscopicInterlacePostProcess, _super);
  53571. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  53572. var _this = this;
  53573. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  53574. this._passedProcess = rigCameras[0]._rigPostProcess;
  53575. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  53576. this.onSizeChangedObservable.add(function () {
  53577. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  53578. });
  53579. this.onApplyObservable.add(function (effect) {
  53580. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  53581. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  53582. });
  53583. }
  53584. return StereoscopicInterlacePostProcess;
  53585. })(BABYLON.PostProcess);
  53586. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  53587. })(BABYLON || (BABYLON = {}));
  53588. var BABYLON;
  53589. (function (BABYLON) {
  53590. var LensFlare = (function () {
  53591. function LensFlare(size, position, color, imgUrl, system) {
  53592. this.size = size;
  53593. this.position = position;
  53594. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  53595. this.dispose = function () {
  53596. if (this.texture) {
  53597. this.texture.dispose();
  53598. }
  53599. // Remove from scene
  53600. var index = this._system.lensFlares.indexOf(this);
  53601. this._system.lensFlares.splice(index, 1);
  53602. };
  53603. this.color = color || new BABYLON.Color3(1, 1, 1);
  53604. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  53605. this._system = system;
  53606. system.lensFlares.push(this);
  53607. }
  53608. return LensFlare;
  53609. })();
  53610. BABYLON.LensFlare = LensFlare;
  53611. })(BABYLON || (BABYLON = {}));
  53612. var BABYLON;
  53613. (function (BABYLON) {
  53614. var LensFlareSystem = (function () {
  53615. function LensFlareSystem(name, emitter, scene) {
  53616. this.name = name;
  53617. this.lensFlares = new Array();
  53618. this.borderLimit = 300;
  53619. this.layerMask = 0x0FFFFFFF;
  53620. this._vertexBuffers = {};
  53621. this._isEnabled = true;
  53622. this._scene = scene;
  53623. this._emitter = emitter;
  53624. this.id = name;
  53625. scene.lensFlareSystems.push(this);
  53626. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  53627. var engine = scene.getEngine();
  53628. // VBO
  53629. var vertices = [];
  53630. vertices.push(1, 1);
  53631. vertices.push(-1, 1);
  53632. vertices.push(-1, -1);
  53633. vertices.push(1, -1);
  53634. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  53635. // Indices
  53636. var indices = [];
  53637. indices.push(0);
  53638. indices.push(1);
  53639. indices.push(2);
  53640. indices.push(0);
  53641. indices.push(2);
  53642. indices.push(3);
  53643. this._indexBuffer = engine.createIndexBuffer(indices);
  53644. // Effects
  53645. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  53646. }
  53647. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  53648. get: function () {
  53649. return this._isEnabled;
  53650. },
  53651. set: function (value) {
  53652. this._isEnabled = value;
  53653. },
  53654. enumerable: true,
  53655. configurable: true
  53656. });
  53657. LensFlareSystem.prototype.getScene = function () {
  53658. return this._scene;
  53659. };
  53660. LensFlareSystem.prototype.getEmitter = function () {
  53661. return this._emitter;
  53662. };
  53663. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  53664. this._emitter = newEmitter;
  53665. };
  53666. LensFlareSystem.prototype.getEmitterPosition = function () {
  53667. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  53668. };
  53669. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  53670. var position = this.getEmitterPosition();
  53671. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  53672. this._positionX = position.x;
  53673. this._positionY = position.y;
  53674. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  53675. if (position.z > 0) {
  53676. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  53677. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  53678. return true;
  53679. }
  53680. }
  53681. return false;
  53682. };
  53683. LensFlareSystem.prototype._isVisible = function () {
  53684. if (!this._isEnabled) {
  53685. return false;
  53686. }
  53687. var emitterPosition = this.getEmitterPosition();
  53688. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  53689. var distance = direction.length();
  53690. direction.normalize();
  53691. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  53692. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  53693. return !pickInfo.hit || pickInfo.distance > distance;
  53694. };
  53695. LensFlareSystem.prototype.render = function () {
  53696. if (!this._effect.isReady())
  53697. return false;
  53698. var engine = this._scene.getEngine();
  53699. var viewport = this._scene.activeCamera.viewport;
  53700. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  53701. // Position
  53702. if (!this.computeEffectivePosition(globalViewport)) {
  53703. return false;
  53704. }
  53705. // Visibility
  53706. if (!this._isVisible()) {
  53707. return false;
  53708. }
  53709. // Intensity
  53710. var awayX;
  53711. var awayY;
  53712. if (this._positionX < this.borderLimit + globalViewport.x) {
  53713. awayX = this.borderLimit + globalViewport.x - this._positionX;
  53714. }
  53715. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  53716. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  53717. }
  53718. else {
  53719. awayX = 0;
  53720. }
  53721. if (this._positionY < this.borderLimit + globalViewport.y) {
  53722. awayY = this.borderLimit + globalViewport.y - this._positionY;
  53723. }
  53724. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  53725. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  53726. }
  53727. else {
  53728. awayY = 0;
  53729. }
  53730. var away = (awayX > awayY) ? awayX : awayY;
  53731. if (away > this.borderLimit) {
  53732. away = this.borderLimit;
  53733. }
  53734. var intensity = 1.0 - (away / this.borderLimit);
  53735. if (intensity < 0) {
  53736. return false;
  53737. }
  53738. if (intensity > 1.0) {
  53739. intensity = 1.0;
  53740. }
  53741. // Position
  53742. var centerX = globalViewport.x + globalViewport.width / 2;
  53743. var centerY = globalViewport.y + globalViewport.height / 2;
  53744. var distX = centerX - this._positionX;
  53745. var distY = centerY - this._positionY;
  53746. // Effects
  53747. engine.enableEffect(this._effect);
  53748. engine.setState(false);
  53749. engine.setDepthBuffer(false);
  53750. // VBOs
  53751. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  53752. // Flares
  53753. for (var index = 0; index < this.lensFlares.length; index++) {
  53754. var flare = this.lensFlares[index];
  53755. engine.setAlphaMode(flare.alphaMode);
  53756. var x = centerX - (distX * flare.position);
  53757. var y = centerY - (distY * flare.position);
  53758. var cw = flare.size;
  53759. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  53760. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  53761. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  53762. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  53763. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  53764. // Texture
  53765. this._effect.setTexture("textureSampler", flare.texture);
  53766. // Color
  53767. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  53768. // Draw order
  53769. engine.draw(true, 0, 6);
  53770. }
  53771. engine.setDepthBuffer(true);
  53772. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53773. return true;
  53774. };
  53775. LensFlareSystem.prototype.dispose = function () {
  53776. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  53777. if (vertexBuffer) {
  53778. vertexBuffer.dispose();
  53779. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  53780. }
  53781. if (this._indexBuffer) {
  53782. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53783. this._indexBuffer = null;
  53784. }
  53785. while (this.lensFlares.length) {
  53786. this.lensFlares[0].dispose();
  53787. }
  53788. // Remove from scene
  53789. var index = this._scene.lensFlareSystems.indexOf(this);
  53790. this._scene.lensFlareSystems.splice(index, 1);
  53791. };
  53792. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  53793. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  53794. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  53795. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  53796. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  53797. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  53798. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  53799. var parsedFlare = parsedLensFlareSystem.flares[index];
  53800. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  53801. }
  53802. return lensFlareSystem;
  53803. };
  53804. LensFlareSystem.prototype.serialize = function () {
  53805. var serializationObject = {};
  53806. serializationObject.id = this.id;
  53807. serializationObject.name = this.name;
  53808. serializationObject.emitterId = this.getEmitter().id;
  53809. serializationObject.borderLimit = this.borderLimit;
  53810. serializationObject.flares = [];
  53811. for (var index = 0; index < this.lensFlares.length; index++) {
  53812. var flare = this.lensFlares[index];
  53813. serializationObject.flares.push({
  53814. size: flare.size,
  53815. position: flare.position,
  53816. color: flare.color.asArray(),
  53817. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  53818. });
  53819. }
  53820. return serializationObject;
  53821. };
  53822. return LensFlareSystem;
  53823. })();
  53824. BABYLON.LensFlareSystem = LensFlareSystem;
  53825. })(BABYLON || (BABYLON = {}));
  53826. var BABYLON;
  53827. (function (BABYLON) {
  53828. // We're mainly based on the logic defined into the FreeCamera code
  53829. var DeviceOrientationCamera = (function (_super) {
  53830. __extends(DeviceOrientationCamera, _super);
  53831. function DeviceOrientationCamera(name, position, scene) {
  53832. _super.call(this, name, position, scene);
  53833. this.inputs.addDeviceOrientation();
  53834. }
  53835. DeviceOrientationCamera.prototype.getTypeName = function () {
  53836. return "DeviceOrientationCamera";
  53837. };
  53838. DeviceOrientationCamera.prototype._checkInputs = function () {
  53839. _super.prototype._checkInputs.call(this);
  53840. if (this._initialQuaternion) {
  53841. this._quaternionCache.copyFrom(this.rotationQuaternion);
  53842. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  53843. }
  53844. };
  53845. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  53846. var _this = this;
  53847. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  53848. //can only work if this camera has a rotation quaternion already.
  53849. if (!this.rotationQuaternion)
  53850. return;
  53851. if (!this._initialQuaternion) {
  53852. this._initialQuaternion = new BABYLON.Quaternion();
  53853. }
  53854. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  53855. ['x', 'y', 'z'].forEach(function (axisName) {
  53856. if (!axis[axisName]) {
  53857. _this._initialQuaternion[axisName] = 0;
  53858. }
  53859. else {
  53860. _this._initialQuaternion[axisName] *= -1;
  53861. }
  53862. });
  53863. this._initialQuaternion.normalize();
  53864. };
  53865. return DeviceOrientationCamera;
  53866. })(BABYLON.FreeCamera);
  53867. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  53868. })(BABYLON || (BABYLON = {}));
  53869. var BABYLON;
  53870. (function (BABYLON) {
  53871. var VRDeviceOrientationFreeCamera = (function (_super) {
  53872. __extends(VRDeviceOrientationFreeCamera, _super);
  53873. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  53874. if (compensateDistortion === void 0) { compensateDistortion = true; }
  53875. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  53876. _super.call(this, name, position, scene);
  53877. vrCameraMetrics.compensateDistortion = compensateDistortion;
  53878. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  53879. }
  53880. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  53881. return "VRDeviceOrientationFreeCamera";
  53882. };
  53883. return VRDeviceOrientationFreeCamera;
  53884. })(BABYLON.DeviceOrientationCamera);
  53885. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  53886. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  53887. __extends(VRDeviceOrientationArcRotateCamera, _super);
  53888. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
  53889. if (compensateDistortion === void 0) { compensateDistortion = true; }
  53890. _super.call(this, name, alpha, beta, radius, target, scene);
  53891. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  53892. metrics.compensateDistortion = compensateDistortion;
  53893. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  53894. this.inputs.addVRDeviceOrientation();
  53895. }
  53896. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  53897. return "VRDeviceOrientationArcRotateCamera";
  53898. };
  53899. return VRDeviceOrientationArcRotateCamera;
  53900. })(BABYLON.ArcRotateCamera);
  53901. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  53902. })(BABYLON || (BABYLON = {}));
  53903. var BABYLON;
  53904. (function (BABYLON) {
  53905. // We're mainly based on the logic defined into the FreeCamera code
  53906. var UniversalCamera = (function (_super) {
  53907. __extends(UniversalCamera, _super);
  53908. //-- end properties for backward compatibility for inputs
  53909. function UniversalCamera(name, position, scene) {
  53910. _super.call(this, name, position, scene);
  53911. this.inputs.addGamepad();
  53912. }
  53913. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  53914. //-- Begin properties for backward compatibility for inputs
  53915. get: function () {
  53916. var gamepad = this.inputs.attached["gamepad"];
  53917. if (gamepad)
  53918. return gamepad.gamepadAngularSensibility;
  53919. },
  53920. set: function (value) {
  53921. var gamepad = this.inputs.attached["gamepad"];
  53922. if (gamepad)
  53923. gamepad.gamepadAngularSensibility = value;
  53924. },
  53925. enumerable: true,
  53926. configurable: true
  53927. });
  53928. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  53929. get: function () {
  53930. var gamepad = this.inputs.attached["gamepad"];
  53931. if (gamepad)
  53932. return gamepad.gamepadMoveSensibility;
  53933. },
  53934. set: function (value) {
  53935. var gamepad = this.inputs.attached["gamepad"];
  53936. if (gamepad)
  53937. gamepad.gamepadMoveSensibility = value;
  53938. },
  53939. enumerable: true,
  53940. configurable: true
  53941. });
  53942. UniversalCamera.prototype.getTypeName = function () {
  53943. return "UniversalCamera";
  53944. };
  53945. return UniversalCamera;
  53946. })(BABYLON.TouchCamera);
  53947. BABYLON.UniversalCamera = UniversalCamera;
  53948. })(BABYLON || (BABYLON = {}));
  53949. var BABYLON;
  53950. (function (BABYLON) {
  53951. var Gamepads = (function () {
  53952. function Gamepads(ongamedpadconnected) {
  53953. var _this = this;
  53954. this.babylonGamepads = [];
  53955. this.oneGamepadConnected = false;
  53956. this.isMonitoring = false;
  53957. this.gamepadEventSupported = 'GamepadEvent' in window;
  53958. this.gamepadSupportAvailable = (navigator.getGamepads ||
  53959. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  53960. this._callbackGamepadConnected = ongamedpadconnected;
  53961. if (this.gamepadSupportAvailable) {
  53962. // Checking if the gamepad connected event is supported (like in Firefox)
  53963. if (this.gamepadEventSupported) {
  53964. this._onGamepadConnectedEvent = function (evt) {
  53965. _this._onGamepadConnected(evt);
  53966. };
  53967. this._onGamepadDisonnectedEvent = function (evt) {
  53968. _this._onGamepadDisconnected(evt);
  53969. };
  53970. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  53971. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  53972. }
  53973. else {
  53974. this._startMonitoringGamepads();
  53975. }
  53976. }
  53977. }
  53978. Gamepads.prototype.dispose = function () {
  53979. if (Gamepads.gamepadDOMInfo) {
  53980. document.body.removeChild(Gamepads.gamepadDOMInfo);
  53981. }
  53982. if (this._onGamepadConnectedEvent) {
  53983. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  53984. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  53985. this._onGamepadConnectedEvent = null;
  53986. this._onGamepadDisonnectedEvent = null;
  53987. }
  53988. };
  53989. Gamepads.prototype._onGamepadConnected = function (evt) {
  53990. var newGamepad = this._addNewGamepad(evt.gamepad);
  53991. if (this._callbackGamepadConnected)
  53992. this._callbackGamepadConnected(newGamepad);
  53993. this._startMonitoringGamepads();
  53994. };
  53995. Gamepads.prototype._addNewGamepad = function (gamepad) {
  53996. if (!this.oneGamepadConnected) {
  53997. this.oneGamepadConnected = true;
  53998. if (Gamepads.gamepadDOMInfo) {
  53999. document.body.removeChild(Gamepads.gamepadDOMInfo);
  54000. Gamepads.gamepadDOMInfo = null;
  54001. }
  54002. }
  54003. var newGamepad;
  54004. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  54005. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  54006. }
  54007. else {
  54008. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  54009. }
  54010. this.babylonGamepads.push(newGamepad);
  54011. return newGamepad;
  54012. };
  54013. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  54014. // Remove the gamepad from the list of gamepads to monitor.
  54015. for (var i in this.babylonGamepads) {
  54016. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  54017. this.babylonGamepads.splice(+i, 1);
  54018. break;
  54019. }
  54020. }
  54021. // If no gamepads are left, stop the polling loop.
  54022. if (this.babylonGamepads.length == 0) {
  54023. this._stopMonitoringGamepads();
  54024. }
  54025. };
  54026. Gamepads.prototype._startMonitoringGamepads = function () {
  54027. if (!this.isMonitoring) {
  54028. this.isMonitoring = true;
  54029. this._checkGamepadsStatus();
  54030. }
  54031. };
  54032. Gamepads.prototype._stopMonitoringGamepads = function () {
  54033. this.isMonitoring = false;
  54034. };
  54035. Gamepads.prototype._checkGamepadsStatus = function () {
  54036. var _this = this;
  54037. // updating gamepad objects
  54038. this._updateGamepadObjects();
  54039. for (var i in this.babylonGamepads) {
  54040. this.babylonGamepads[i].update();
  54041. }
  54042. if (this.isMonitoring) {
  54043. if (window.requestAnimationFrame) {
  54044. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  54045. }
  54046. else if (window.mozRequestAnimationFrame) {
  54047. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  54048. }
  54049. else if (window.webkitRequestAnimationFrame) {
  54050. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  54051. }
  54052. }
  54053. };
  54054. // This function is called only on Chrome, which does not yet support
  54055. // connection/disconnection events, but requires you to monitor
  54056. // an array for changes.
  54057. Gamepads.prototype._updateGamepadObjects = function () {
  54058. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  54059. for (var i = 0; i < gamepads.length; i++) {
  54060. if (gamepads[i]) {
  54061. if (!(gamepads[i].index in this.babylonGamepads)) {
  54062. var newGamepad = this._addNewGamepad(gamepads[i]);
  54063. if (this._callbackGamepadConnected) {
  54064. this._callbackGamepadConnected(newGamepad);
  54065. }
  54066. }
  54067. else {
  54068. this.babylonGamepads[i].browserGamepad = gamepads[i];
  54069. }
  54070. }
  54071. }
  54072. };
  54073. return Gamepads;
  54074. })();
  54075. BABYLON.Gamepads = Gamepads;
  54076. var StickValues = (function () {
  54077. function StickValues(x, y) {
  54078. this.x = x;
  54079. this.y = y;
  54080. }
  54081. return StickValues;
  54082. })();
  54083. BABYLON.StickValues = StickValues;
  54084. var Gamepad = (function () {
  54085. function Gamepad(id, index, browserGamepad) {
  54086. this.id = id;
  54087. this.index = index;
  54088. this.browserGamepad = browserGamepad;
  54089. if (this.browserGamepad.axes.length >= 2) {
  54090. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  54091. }
  54092. if (this.browserGamepad.axes.length >= 4) {
  54093. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  54094. }
  54095. }
  54096. Gamepad.prototype.onleftstickchanged = function (callback) {
  54097. this._onleftstickchanged = callback;
  54098. };
  54099. Gamepad.prototype.onrightstickchanged = function (callback) {
  54100. this._onrightstickchanged = callback;
  54101. };
  54102. Object.defineProperty(Gamepad.prototype, "leftStick", {
  54103. get: function () {
  54104. return this._leftStick;
  54105. },
  54106. set: function (newValues) {
  54107. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  54108. this._onleftstickchanged(newValues);
  54109. }
  54110. this._leftStick = newValues;
  54111. },
  54112. enumerable: true,
  54113. configurable: true
  54114. });
  54115. Object.defineProperty(Gamepad.prototype, "rightStick", {
  54116. get: function () {
  54117. return this._rightStick;
  54118. },
  54119. set: function (newValues) {
  54120. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  54121. this._onrightstickchanged(newValues);
  54122. }
  54123. this._rightStick = newValues;
  54124. },
  54125. enumerable: true,
  54126. configurable: true
  54127. });
  54128. Gamepad.prototype.update = function () {
  54129. if (this._leftStick) {
  54130. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  54131. }
  54132. if (this._rightStick) {
  54133. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  54134. }
  54135. };
  54136. return Gamepad;
  54137. })();
  54138. BABYLON.Gamepad = Gamepad;
  54139. var GenericPad = (function (_super) {
  54140. __extends(GenericPad, _super);
  54141. function GenericPad(id, index, gamepad) {
  54142. _super.call(this, id, index, gamepad);
  54143. this.id = id;
  54144. this.index = index;
  54145. this.gamepad = gamepad;
  54146. this._buttons = new Array(gamepad.buttons.length);
  54147. }
  54148. GenericPad.prototype.onbuttondown = function (callback) {
  54149. this._onbuttondown = callback;
  54150. };
  54151. GenericPad.prototype.onbuttonup = function (callback) {
  54152. this._onbuttonup = callback;
  54153. };
  54154. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  54155. if (newValue !== currentValue) {
  54156. if (this._onbuttondown && newValue === 1) {
  54157. this._onbuttondown(buttonIndex);
  54158. }
  54159. if (this._onbuttonup && newValue === 0) {
  54160. this._onbuttonup(buttonIndex);
  54161. }
  54162. }
  54163. return newValue;
  54164. };
  54165. GenericPad.prototype.update = function () {
  54166. _super.prototype.update.call(this);
  54167. for (var index = 0; index < this._buttons.length; index++) {
  54168. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  54169. }
  54170. };
  54171. return GenericPad;
  54172. })(Gamepad);
  54173. BABYLON.GenericPad = GenericPad;
  54174. (function (Xbox360Button) {
  54175. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  54176. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  54177. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  54178. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  54179. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  54180. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  54181. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  54182. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  54183. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  54184. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  54185. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  54186. var Xbox360Button = BABYLON.Xbox360Button;
  54187. (function (Xbox360Dpad) {
  54188. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  54189. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  54190. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  54191. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  54192. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  54193. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  54194. var Xbox360Pad = (function (_super) {
  54195. __extends(Xbox360Pad, _super);
  54196. function Xbox360Pad() {
  54197. _super.apply(this, arguments);
  54198. this._leftTrigger = 0;
  54199. this._rightTrigger = 0;
  54200. this._buttonA = 0;
  54201. this._buttonB = 0;
  54202. this._buttonX = 0;
  54203. this._buttonY = 0;
  54204. this._buttonBack = 0;
  54205. this._buttonStart = 0;
  54206. this._buttonLB = 0;
  54207. this._buttonRB = 0;
  54208. this._buttonLeftStick = 0;
  54209. this._buttonRightStick = 0;
  54210. this._dPadUp = 0;
  54211. this._dPadDown = 0;
  54212. this._dPadLeft = 0;
  54213. this._dPadRight = 0;
  54214. }
  54215. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  54216. this._onlefttriggerchanged = callback;
  54217. };
  54218. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  54219. this._onrighttriggerchanged = callback;
  54220. };
  54221. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  54222. get: function () {
  54223. return this._leftTrigger;
  54224. },
  54225. set: function (newValue) {
  54226. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  54227. this._onlefttriggerchanged(newValue);
  54228. }
  54229. this._leftTrigger = newValue;
  54230. },
  54231. enumerable: true,
  54232. configurable: true
  54233. });
  54234. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  54235. get: function () {
  54236. return this._rightTrigger;
  54237. },
  54238. set: function (newValue) {
  54239. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  54240. this._onrighttriggerchanged(newValue);
  54241. }
  54242. this._rightTrigger = newValue;
  54243. },
  54244. enumerable: true,
  54245. configurable: true
  54246. });
  54247. Xbox360Pad.prototype.onbuttondown = function (callback) {
  54248. this._onbuttondown = callback;
  54249. };
  54250. Xbox360Pad.prototype.onbuttonup = function (callback) {
  54251. this._onbuttonup = callback;
  54252. };
  54253. Xbox360Pad.prototype.ondpaddown = function (callback) {
  54254. this._ondpaddown = callback;
  54255. };
  54256. Xbox360Pad.prototype.ondpadup = function (callback) {
  54257. this._ondpadup = callback;
  54258. };
  54259. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  54260. if (newValue !== currentValue) {
  54261. if (this._onbuttondown && newValue === 1) {
  54262. this._onbuttondown(buttonType);
  54263. }
  54264. if (this._onbuttonup && newValue === 0) {
  54265. this._onbuttonup(buttonType);
  54266. }
  54267. }
  54268. return newValue;
  54269. };
  54270. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  54271. if (newValue !== currentValue) {
  54272. if (this._ondpaddown && newValue === 1) {
  54273. this._ondpaddown(buttonType);
  54274. }
  54275. if (this._ondpadup && newValue === 0) {
  54276. this._ondpadup(buttonType);
  54277. }
  54278. }
  54279. return newValue;
  54280. };
  54281. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  54282. get: function () {
  54283. return this._buttonA;
  54284. },
  54285. set: function (value) {
  54286. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  54287. },
  54288. enumerable: true,
  54289. configurable: true
  54290. });
  54291. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  54292. get: function () {
  54293. return this._buttonB;
  54294. },
  54295. set: function (value) {
  54296. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  54297. },
  54298. enumerable: true,
  54299. configurable: true
  54300. });
  54301. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  54302. get: function () {
  54303. return this._buttonX;
  54304. },
  54305. set: function (value) {
  54306. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  54307. },
  54308. enumerable: true,
  54309. configurable: true
  54310. });
  54311. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  54312. get: function () {
  54313. return this._buttonY;
  54314. },
  54315. set: function (value) {
  54316. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  54317. },
  54318. enumerable: true,
  54319. configurable: true
  54320. });
  54321. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  54322. get: function () {
  54323. return this._buttonStart;
  54324. },
  54325. set: function (value) {
  54326. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  54327. },
  54328. enumerable: true,
  54329. configurable: true
  54330. });
  54331. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  54332. get: function () {
  54333. return this._buttonBack;
  54334. },
  54335. set: function (value) {
  54336. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  54337. },
  54338. enumerable: true,
  54339. configurable: true
  54340. });
  54341. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  54342. get: function () {
  54343. return this._buttonLB;
  54344. },
  54345. set: function (value) {
  54346. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  54347. },
  54348. enumerable: true,
  54349. configurable: true
  54350. });
  54351. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  54352. get: function () {
  54353. return this._buttonRB;
  54354. },
  54355. set: function (value) {
  54356. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  54357. },
  54358. enumerable: true,
  54359. configurable: true
  54360. });
  54361. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  54362. get: function () {
  54363. return this._buttonLeftStick;
  54364. },
  54365. set: function (value) {
  54366. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  54367. },
  54368. enumerable: true,
  54369. configurable: true
  54370. });
  54371. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  54372. get: function () {
  54373. return this._buttonRightStick;
  54374. },
  54375. set: function (value) {
  54376. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  54377. },
  54378. enumerable: true,
  54379. configurable: true
  54380. });
  54381. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  54382. get: function () {
  54383. return this._dPadUp;
  54384. },
  54385. set: function (value) {
  54386. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  54387. },
  54388. enumerable: true,
  54389. configurable: true
  54390. });
  54391. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  54392. get: function () {
  54393. return this._dPadDown;
  54394. },
  54395. set: function (value) {
  54396. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  54397. },
  54398. enumerable: true,
  54399. configurable: true
  54400. });
  54401. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  54402. get: function () {
  54403. return this._dPadLeft;
  54404. },
  54405. set: function (value) {
  54406. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  54407. },
  54408. enumerable: true,
  54409. configurable: true
  54410. });
  54411. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  54412. get: function () {
  54413. return this._dPadRight;
  54414. },
  54415. set: function (value) {
  54416. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  54417. },
  54418. enumerable: true,
  54419. configurable: true
  54420. });
  54421. Xbox360Pad.prototype.update = function () {
  54422. _super.prototype.update.call(this);
  54423. this.buttonA = this.browserGamepad.buttons[0].value;
  54424. this.buttonB = this.browserGamepad.buttons[1].value;
  54425. this.buttonX = this.browserGamepad.buttons[2].value;
  54426. this.buttonY = this.browserGamepad.buttons[3].value;
  54427. this.buttonLB = this.browserGamepad.buttons[4].value;
  54428. this.buttonRB = this.browserGamepad.buttons[5].value;
  54429. this.leftTrigger = this.browserGamepad.buttons[6].value;
  54430. this.rightTrigger = this.browserGamepad.buttons[7].value;
  54431. this.buttonBack = this.browserGamepad.buttons[8].value;
  54432. this.buttonStart = this.browserGamepad.buttons[9].value;
  54433. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  54434. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  54435. this.dPadUp = this.browserGamepad.buttons[12].value;
  54436. this.dPadDown = this.browserGamepad.buttons[13].value;
  54437. this.dPadLeft = this.browserGamepad.buttons[14].value;
  54438. this.dPadRight = this.browserGamepad.buttons[15].value;
  54439. };
  54440. return Xbox360Pad;
  54441. })(Gamepad);
  54442. BABYLON.Xbox360Pad = Xbox360Pad;
  54443. })(BABYLON || (BABYLON = {}));
  54444. var BABYLON;
  54445. (function (BABYLON) {
  54446. // We're mainly based on the logic defined into the FreeCamera code
  54447. var GamepadCamera = (function (_super) {
  54448. __extends(GamepadCamera, _super);
  54449. //-- end properties for backward compatibility for inputs
  54450. function GamepadCamera(name, position, scene) {
  54451. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  54452. _super.call(this, name, position, scene);
  54453. }
  54454. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  54455. //-- Begin properties for backward compatibility for inputs
  54456. get: function () {
  54457. var gamepad = this.inputs.attached["gamepad"];
  54458. if (gamepad)
  54459. return gamepad.gamepadAngularSensibility;
  54460. },
  54461. set: function (value) {
  54462. var gamepad = this.inputs.attached["gamepad"];
  54463. if (gamepad)
  54464. gamepad.gamepadAngularSensibility = value;
  54465. },
  54466. enumerable: true,
  54467. configurable: true
  54468. });
  54469. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  54470. get: function () {
  54471. var gamepad = this.inputs.attached["gamepad"];
  54472. if (gamepad)
  54473. return gamepad.gamepadMoveSensibility;
  54474. },
  54475. set: function (value) {
  54476. var gamepad = this.inputs.attached["gamepad"];
  54477. if (gamepad)
  54478. gamepad.gamepadMoveSensibility = value;
  54479. },
  54480. enumerable: true,
  54481. configurable: true
  54482. });
  54483. GamepadCamera.prototype.getTypeName = function () {
  54484. return "GamepadCamera";
  54485. };
  54486. return GamepadCamera;
  54487. })(BABYLON.UniversalCamera);
  54488. BABYLON.GamepadCamera = GamepadCamera;
  54489. })(BABYLON || (BABYLON = {}));
  54490. var BABYLON;
  54491. (function (BABYLON) {
  54492. var Analyser = (function () {
  54493. function Analyser(scene) {
  54494. this.SMOOTHING = 0.75;
  54495. this.FFT_SIZE = 512;
  54496. this.BARGRAPHAMPLITUDE = 256;
  54497. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  54498. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  54499. this._scene = scene;
  54500. this._audioEngine = BABYLON.Engine.audioEngine;
  54501. if (this._audioEngine.canUseWebAudio) {
  54502. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  54503. this._webAudioAnalyser.minDecibels = -140;
  54504. this._webAudioAnalyser.maxDecibels = 0;
  54505. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  54506. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  54507. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  54508. }
  54509. }
  54510. Analyser.prototype.getFrequencyBinCount = function () {
  54511. if (this._audioEngine.canUseWebAudio) {
  54512. return this._webAudioAnalyser.frequencyBinCount;
  54513. }
  54514. else {
  54515. return 0;
  54516. }
  54517. };
  54518. Analyser.prototype.getByteFrequencyData = function () {
  54519. if (this._audioEngine.canUseWebAudio) {
  54520. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54521. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54522. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  54523. }
  54524. return this._byteFreqs;
  54525. };
  54526. Analyser.prototype.getByteTimeDomainData = function () {
  54527. if (this._audioEngine.canUseWebAudio) {
  54528. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54529. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54530. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  54531. }
  54532. return this._byteTime;
  54533. };
  54534. Analyser.prototype.getFloatFrequencyData = function () {
  54535. if (this._audioEngine.canUseWebAudio) {
  54536. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54537. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54538. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  54539. }
  54540. return this._floatFreqs;
  54541. };
  54542. Analyser.prototype.drawDebugCanvas = function () {
  54543. var _this = this;
  54544. if (this._audioEngine.canUseWebAudio) {
  54545. if (!this._debugCanvas) {
  54546. this._debugCanvas = document.createElement("canvas");
  54547. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  54548. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  54549. this._debugCanvas.style.position = "absolute";
  54550. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  54551. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  54552. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  54553. document.body.appendChild(this._debugCanvas);
  54554. this._registerFunc = function () {
  54555. _this.drawDebugCanvas();
  54556. };
  54557. this._scene.registerBeforeRender(this._registerFunc);
  54558. }
  54559. if (this._registerFunc) {
  54560. var workingArray = this.getByteFrequencyData();
  54561. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  54562. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  54563. // Draw the frequency domain chart.
  54564. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  54565. var value = workingArray[i];
  54566. var percent = value / this.BARGRAPHAMPLITUDE;
  54567. var height = this.DEBUGCANVASSIZE.height * percent;
  54568. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  54569. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  54570. var hue = i / this.getFrequencyBinCount() * 360;
  54571. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  54572. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  54573. }
  54574. }
  54575. }
  54576. };
  54577. Analyser.prototype.stopDebugCanvas = function () {
  54578. if (this._debugCanvas) {
  54579. this._scene.unregisterBeforeRender(this._registerFunc);
  54580. this._registerFunc = null;
  54581. document.body.removeChild(this._debugCanvas);
  54582. this._debugCanvas = null;
  54583. this._debugCanvasContext = null;
  54584. }
  54585. };
  54586. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  54587. if (this._audioEngine.canUseWebAudio) {
  54588. inputAudioNode.connect(this._webAudioAnalyser);
  54589. this._webAudioAnalyser.connect(outputAudioNode);
  54590. }
  54591. };
  54592. Analyser.prototype.dispose = function () {
  54593. if (this._audioEngine.canUseWebAudio) {
  54594. this._webAudioAnalyser.disconnect();
  54595. }
  54596. };
  54597. return Analyser;
  54598. })();
  54599. BABYLON.Analyser = Analyser;
  54600. })(BABYLON || (BABYLON = {}));
  54601. var BABYLON;
  54602. (function (BABYLON) {
  54603. var DepthRenderer = (function () {
  54604. function DepthRenderer(scene, type) {
  54605. var _this = this;
  54606. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  54607. this._viewMatrix = BABYLON.Matrix.Zero();
  54608. this._projectionMatrix = BABYLON.Matrix.Zero();
  54609. this._transformMatrix = BABYLON.Matrix.Zero();
  54610. this._worldViewProjection = BABYLON.Matrix.Zero();
  54611. this._scene = scene;
  54612. var engine = scene.getEngine();
  54613. // Render target
  54614. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  54615. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54616. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54617. this._depthMap.refreshRate = 1;
  54618. this._depthMap.renderParticles = false;
  54619. this._depthMap.renderList = null;
  54620. // set default depth value to 1.0 (far away)
  54621. this._depthMap.onClearObservable.add(function (engine) {
  54622. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  54623. });
  54624. // Custom render function
  54625. var renderSubMesh = function (subMesh) {
  54626. var mesh = subMesh.getRenderingMesh();
  54627. var scene = _this._scene;
  54628. var engine = scene.getEngine();
  54629. // Culling
  54630. engine.setState(subMesh.getMaterial().backFaceCulling);
  54631. // Managing instances
  54632. var batch = mesh._getInstancesRenderList(subMesh._id);
  54633. if (batch.mustReturn) {
  54634. return;
  54635. }
  54636. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  54637. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  54638. engine.enableEffect(_this._effect);
  54639. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  54640. var material = subMesh.getMaterial();
  54641. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  54642. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  54643. // Alpha test
  54644. if (material && material.needAlphaTesting()) {
  54645. var alphaTexture = material.getAlphaTestTexture();
  54646. _this._effect.setTexture("diffuseSampler", alphaTexture);
  54647. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  54648. }
  54649. // Bones
  54650. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54651. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  54652. }
  54653. // Draw
  54654. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  54655. }
  54656. };
  54657. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  54658. var index;
  54659. for (index = 0; index < opaqueSubMeshes.length; index++) {
  54660. renderSubMesh(opaqueSubMeshes.data[index]);
  54661. }
  54662. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  54663. renderSubMesh(alphaTestSubMeshes.data[index]);
  54664. }
  54665. };
  54666. }
  54667. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  54668. var material = subMesh.getMaterial();
  54669. if (material.disableDepthWrite) {
  54670. return false;
  54671. }
  54672. var defines = [];
  54673. var attribs = [BABYLON.VertexBuffer.PositionKind];
  54674. var mesh = subMesh.getMesh();
  54675. var scene = mesh.getScene();
  54676. // Alpha test
  54677. if (material && material.needAlphaTesting()) {
  54678. defines.push("#define ALPHATEST");
  54679. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54680. attribs.push(BABYLON.VertexBuffer.UVKind);
  54681. defines.push("#define UV1");
  54682. }
  54683. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  54684. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  54685. defines.push("#define UV2");
  54686. }
  54687. }
  54688. // Bones
  54689. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54690. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54691. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54692. if (mesh.numBoneInfluencers > 4) {
  54693. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54694. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54695. }
  54696. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54697. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54698. }
  54699. else {
  54700. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54701. }
  54702. // Instances
  54703. if (useInstances) {
  54704. defines.push("#define INSTANCES");
  54705. attribs.push("world0");
  54706. attribs.push("world1");
  54707. attribs.push("world2");
  54708. attribs.push("world3");
  54709. }
  54710. // Get correct effect
  54711. var join = defines.join("\n");
  54712. if (this._cachedDefines !== join) {
  54713. this._cachedDefines = join;
  54714. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  54715. }
  54716. return this._effect.isReady();
  54717. };
  54718. DepthRenderer.prototype.getDepthMap = function () {
  54719. return this._depthMap;
  54720. };
  54721. // Methods
  54722. DepthRenderer.prototype.dispose = function () {
  54723. this._depthMap.dispose();
  54724. };
  54725. return DepthRenderer;
  54726. })();
  54727. BABYLON.DepthRenderer = DepthRenderer;
  54728. })(BABYLON || (BABYLON = {}));
  54729. var BABYLON;
  54730. (function (BABYLON) {
  54731. var SSAORenderingPipeline = (function (_super) {
  54732. __extends(SSAORenderingPipeline, _super);
  54733. /**
  54734. * @constructor
  54735. * @param {string} name - The rendering pipeline name
  54736. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54737. * @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 }
  54738. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54739. */
  54740. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  54741. var _this = this;
  54742. _super.call(this, scene.getEngine(), name);
  54743. // Members
  54744. /**
  54745. * The PassPostProcess id in the pipeline that contains the original scene color
  54746. * @type {string}
  54747. */
  54748. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  54749. /**
  54750. * The SSAO PostProcess id in the pipeline
  54751. * @type {string}
  54752. */
  54753. this.SSAORenderEffect = "SSAORenderEffect";
  54754. /**
  54755. * The horizontal blur PostProcess id in the pipeline
  54756. * @type {string}
  54757. */
  54758. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  54759. /**
  54760. * The vertical blur PostProcess id in the pipeline
  54761. * @type {string}
  54762. */
  54763. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  54764. /**
  54765. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  54766. * @type {string}
  54767. */
  54768. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  54769. /**
  54770. * The output strength of the SSAO post-process. Default value is 1.0.
  54771. * @type {number}
  54772. */
  54773. this.totalStrength = 1.0;
  54774. /**
  54775. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  54776. * @type {number}
  54777. */
  54778. this.radius = 0.0001;
  54779. /**
  54780. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  54781. * Must not be equal to fallOff and superior to fallOff.
  54782. * Default value is 0.975
  54783. * @type {number}
  54784. */
  54785. this.area = 0.0075;
  54786. /**
  54787. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  54788. * Must not be equal to area and inferior to area.
  54789. * Default value is 0.0
  54790. * @type {number}
  54791. */
  54792. this.fallOff = 0.000001;
  54793. /**
  54794. * The base color of the SSAO post-process
  54795. * The final result is "base + ssao" between [0, 1]
  54796. * @type {number}
  54797. */
  54798. this.base = 0.5;
  54799. this._firstUpdate = true;
  54800. this._scene = scene;
  54801. // Set up assets
  54802. this._createRandomTexture();
  54803. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  54804. var ssaoRatio = ratio.ssaoRatio || ratio;
  54805. var combineRatio = ratio.combineRatio || ratio;
  54806. this._ratio = {
  54807. ssaoRatio: ssaoRatio,
  54808. combineRatio: combineRatio
  54809. };
  54810. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  54811. this._createSSAOPostProcess(ssaoRatio);
  54812. this._createBlurPostProcess(ssaoRatio);
  54813. this._createSSAOCombinePostProcess(combineRatio);
  54814. // Set up pipeline
  54815. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  54816. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  54817. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  54818. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  54819. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  54820. // Finish
  54821. scene.postProcessRenderPipelineManager.addPipeline(this);
  54822. if (cameras)
  54823. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54824. }
  54825. // Public Methods
  54826. /**
  54827. * Returns the horizontal blur PostProcess
  54828. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  54829. */
  54830. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  54831. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  54832. return null;
  54833. };
  54834. /**
  54835. * Returns the vertical blur PostProcess
  54836. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  54837. */
  54838. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  54839. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  54840. return null;
  54841. };
  54842. /**
  54843. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  54844. */
  54845. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  54846. if (disableDepthRender === void 0) { disableDepthRender = false; }
  54847. for (var i = 0; i < this._scene.cameras.length; i++) {
  54848. var camera = this._scene.cameras[i];
  54849. this._originalColorPostProcess.dispose(camera);
  54850. this._ssaoPostProcess.dispose(camera);
  54851. this._blurHPostProcess.dispose(camera);
  54852. this._blurVPostProcess.dispose(camera);
  54853. this._ssaoCombinePostProcess.dispose(camera);
  54854. }
  54855. this._randomTexture.dispose();
  54856. if (disableDepthRender)
  54857. this._scene.disableDepthRenderer();
  54858. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54859. };
  54860. // Private Methods
  54861. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  54862. var _this = this;
  54863. /*
  54864. var samplerOffsets = [
  54865. -8.0, -6.0, -4.0, -2.0,
  54866. 0.0,
  54867. 2.0, 4.0, 6.0, 8.0
  54868. ];
  54869. */
  54870. var samples = 16;
  54871. var samplerOffsets = [];
  54872. for (var i = -8; i < 8; i++) {
  54873. samplerOffsets.push(i * 2);
  54874. }
  54875. 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");
  54876. this._blurHPostProcess.onApply = function (effect) {
  54877. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  54878. effect.setTexture("depthSampler", _this._depthTexture);
  54879. if (_this._firstUpdate) {
  54880. effect.setArray("samplerOffsets", samplerOffsets);
  54881. }
  54882. };
  54883. 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");
  54884. this._blurVPostProcess.onApply = function (effect) {
  54885. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  54886. effect.setTexture("depthSampler", _this._depthTexture);
  54887. if (_this._firstUpdate) {
  54888. effect.setArray("samplerOffsets", samplerOffsets);
  54889. _this._firstUpdate = false;
  54890. }
  54891. };
  54892. };
  54893. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  54894. var _this = this;
  54895. var numSamples = 16;
  54896. var sampleSphere = [
  54897. 0.5381, 0.1856, -0.4319,
  54898. 0.1379, 0.2486, 0.4430,
  54899. 0.3371, 0.5679, -0.0057,
  54900. -0.6999, -0.0451, -0.0019,
  54901. 0.0689, -0.1598, -0.8547,
  54902. 0.0560, 0.0069, -0.1843,
  54903. -0.0146, 0.1402, 0.0762,
  54904. 0.0100, -0.1924, -0.0344,
  54905. -0.3577, -0.5301, -0.4358,
  54906. -0.3169, 0.1063, 0.0158,
  54907. 0.0103, -0.5869, 0.0046,
  54908. -0.0897, -0.4940, 0.3287,
  54909. 0.7119, -0.0154, -0.0918,
  54910. -0.0533, 0.0596, -0.5411,
  54911. 0.0352, -0.0631, 0.5460,
  54912. -0.4776, 0.2847, -0.0271
  54913. ];
  54914. var samplesFactor = 1.0 / numSamples;
  54915. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  54916. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  54917. "area", "fallOff", "base", "range", "viewport"
  54918. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  54919. var viewport = new BABYLON.Vector2(0, 0);
  54920. this._ssaoPostProcess.onApply = function (effect) {
  54921. if (_this._firstUpdate) {
  54922. effect.setArray3("sampleSphere", sampleSphere);
  54923. effect.setFloat("samplesFactor", samplesFactor);
  54924. effect.setFloat("randTextureTiles", 4.0);
  54925. }
  54926. effect.setFloat("totalStrength", _this.totalStrength);
  54927. effect.setFloat("radius", _this.radius);
  54928. effect.setFloat("area", _this.area);
  54929. effect.setFloat("fallOff", _this.fallOff);
  54930. effect.setFloat("base", _this.base);
  54931. effect.setTexture("textureSampler", _this._depthTexture);
  54932. effect.setTexture("randomSampler", _this._randomTexture);
  54933. };
  54934. };
  54935. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  54936. var _this = this;
  54937. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54938. this._ssaoCombinePostProcess.onApply = function (effect) {
  54939. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  54940. };
  54941. };
  54942. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  54943. var size = 512;
  54944. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  54945. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54946. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54947. var context = this._randomTexture.getContext();
  54948. var rand = function (min, max) {
  54949. return Math.random() * (max - min) + min;
  54950. };
  54951. var randVector = BABYLON.Vector3.Zero();
  54952. for (var x = 0; x < size; x++) {
  54953. for (var y = 0; y < size; y++) {
  54954. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  54955. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  54956. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  54957. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  54958. context.fillRect(x, y, 1, 1);
  54959. }
  54960. }
  54961. this._randomTexture.update(false);
  54962. };
  54963. __decorate([
  54964. BABYLON.serialize()
  54965. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  54966. __decorate([
  54967. BABYLON.serialize()
  54968. ], SSAORenderingPipeline.prototype, "radius", void 0);
  54969. __decorate([
  54970. BABYLON.serialize()
  54971. ], SSAORenderingPipeline.prototype, "area", void 0);
  54972. __decorate([
  54973. BABYLON.serialize()
  54974. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  54975. __decorate([
  54976. BABYLON.serialize()
  54977. ], SSAORenderingPipeline.prototype, "base", void 0);
  54978. __decorate([
  54979. BABYLON.serialize()
  54980. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  54981. return SSAORenderingPipeline;
  54982. })(BABYLON.PostProcessRenderPipeline);
  54983. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  54984. })(BABYLON || (BABYLON = {}));
  54985. var BABYLON;
  54986. (function (BABYLON) {
  54987. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  54988. var VolumetricLightScatteringPostProcess = (function (_super) {
  54989. __extends(VolumetricLightScatteringPostProcess, _super);
  54990. /**
  54991. * @constructor
  54992. * @param {string} name - The post-process name
  54993. * @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)
  54994. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  54995. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  54996. * @param {number} samples - The post-process quality, default 100
  54997. * @param {number} samplingMode - The post-process filtering mode
  54998. * @param {BABYLON.Engine} engine - The babylon engine
  54999. * @param {boolean} reusable - If the post-process is reusable
  55000. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  55001. */
  55002. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  55003. var _this = this;
  55004. if (samples === void 0) { samples = 100; }
  55005. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55006. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  55007. this._screenCoordinates = BABYLON.Vector2.Zero();
  55008. /**
  55009. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  55010. * @type {Vector3}
  55011. */
  55012. this.customMeshPosition = BABYLON.Vector3.Zero();
  55013. /**
  55014. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  55015. * @type {boolean}
  55016. */
  55017. this.useCustomMeshPosition = false;
  55018. /**
  55019. * If the post-process should inverse the light scattering direction
  55020. * @type {boolean}
  55021. */
  55022. this.invert = true;
  55023. /**
  55024. * Array containing the excluded meshes not rendered in the internal pass
  55025. */
  55026. this.excludedMeshes = new Array();
  55027. /**
  55028. * Controls the overall intensity of the post-process
  55029. * @type {number}
  55030. */
  55031. this.exposure = 0.3;
  55032. /**
  55033. * Dissipates each sample's contribution in range [0, 1]
  55034. * @type {number}
  55035. */
  55036. this.decay = 0.96815;
  55037. /**
  55038. * Controls the overall intensity of each sample
  55039. * @type {number}
  55040. */
  55041. this.weight = 0.58767;
  55042. /**
  55043. * Controls the density of each sample
  55044. * @type {number}
  55045. */
  55046. this.density = 0.926;
  55047. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  55048. var engine = scene.getEngine();
  55049. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  55050. // Configure mesh
  55051. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  55052. // Configure
  55053. this._createPass(scene, ratio.passRatio || ratio);
  55054. this.onActivate = function (camera) {
  55055. if (!_this.isSupported) {
  55056. _this.dispose(camera);
  55057. }
  55058. _this.onActivate = null;
  55059. };
  55060. this.onApplyObservable.add(function (effect) {
  55061. _this._updateMeshScreenCoordinates(scene);
  55062. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  55063. effect.setFloat("exposure", _this.exposure);
  55064. effect.setFloat("decay", _this.decay);
  55065. effect.setFloat("weight", _this.weight);
  55066. effect.setFloat("density", _this.density);
  55067. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  55068. });
  55069. }
  55070. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  55071. get: function () {
  55072. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  55073. return false;
  55074. },
  55075. set: function (useDiffuseColor) {
  55076. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  55077. },
  55078. enumerable: true,
  55079. configurable: true
  55080. });
  55081. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  55082. var mesh = subMesh.getMesh();
  55083. // Render this.mesh as default
  55084. if (mesh === this.mesh) {
  55085. return mesh.material.isReady(mesh);
  55086. }
  55087. var defines = [];
  55088. var attribs = [BABYLON.VertexBuffer.PositionKind];
  55089. var material = subMesh.getMaterial();
  55090. var needUV = false;
  55091. // Alpha test
  55092. if (material) {
  55093. if (material.needAlphaTesting()) {
  55094. defines.push("#define ALPHATEST");
  55095. }
  55096. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55097. attribs.push(BABYLON.VertexBuffer.UVKind);
  55098. defines.push("#define UV1");
  55099. }
  55100. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55101. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55102. defines.push("#define UV2");
  55103. }
  55104. }
  55105. // Bones
  55106. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55107. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55108. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55109. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55110. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55111. }
  55112. else {
  55113. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55114. }
  55115. // Instances
  55116. if (useInstances) {
  55117. defines.push("#define INSTANCES");
  55118. attribs.push("world0");
  55119. attribs.push("world1");
  55120. attribs.push("world2");
  55121. attribs.push("world3");
  55122. }
  55123. // Get correct effect
  55124. var join = defines.join("\n");
  55125. if (this._cachedDefines !== join) {
  55126. this._cachedDefines = join;
  55127. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  55128. }
  55129. return this._volumetricLightScatteringPass.isReady();
  55130. };
  55131. /**
  55132. * Sets the new light position for light scattering effect
  55133. * @param {BABYLON.Vector3} The new custom light position
  55134. */
  55135. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  55136. this.customMeshPosition = position;
  55137. };
  55138. /**
  55139. * Returns the light position for light scattering effect
  55140. * @return {BABYLON.Vector3} The custom light position
  55141. */
  55142. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  55143. return this.customMeshPosition;
  55144. };
  55145. /**
  55146. * Disposes the internal assets and detaches the post-process from the camera
  55147. */
  55148. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  55149. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  55150. if (rttIndex !== -1) {
  55151. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  55152. }
  55153. this._volumetricLightScatteringRTT.dispose();
  55154. _super.prototype.dispose.call(this, camera);
  55155. };
  55156. /**
  55157. * Returns the render target texture used by the post-process
  55158. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  55159. */
  55160. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  55161. return this._volumetricLightScatteringRTT;
  55162. };
  55163. // Private methods
  55164. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  55165. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  55166. return true;
  55167. }
  55168. return false;
  55169. };
  55170. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  55171. var _this = this;
  55172. var engine = scene.getEngine();
  55173. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  55174. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55175. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55176. this._volumetricLightScatteringRTT.renderList = null;
  55177. this._volumetricLightScatteringRTT.renderParticles = false;
  55178. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  55179. // Custom render function for submeshes
  55180. var renderSubMesh = function (subMesh) {
  55181. var mesh = subMesh.getRenderingMesh();
  55182. if (_this._meshExcluded(mesh)) {
  55183. return;
  55184. }
  55185. var scene = mesh.getScene();
  55186. var engine = scene.getEngine();
  55187. // Culling
  55188. engine.setState(subMesh.getMaterial().backFaceCulling);
  55189. // Managing instances
  55190. var batch = mesh._getInstancesRenderList(subMesh._id);
  55191. if (batch.mustReturn) {
  55192. return;
  55193. }
  55194. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  55195. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  55196. var effect = _this._volumetricLightScatteringPass;
  55197. if (mesh === _this.mesh) {
  55198. effect = subMesh.getMaterial().getEffect();
  55199. }
  55200. engine.enableEffect(effect);
  55201. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  55202. if (mesh === _this.mesh) {
  55203. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  55204. }
  55205. else {
  55206. var material = subMesh.getMaterial();
  55207. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  55208. // Alpha test
  55209. if (material && material.needAlphaTesting()) {
  55210. var alphaTexture = material.getAlphaTestTexture();
  55211. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  55212. if (alphaTexture) {
  55213. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  55214. }
  55215. }
  55216. // Bones
  55217. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55218. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  55219. }
  55220. }
  55221. // Draw
  55222. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  55223. }
  55224. };
  55225. // Render target texture callbacks
  55226. var savedSceneClearColor;
  55227. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  55228. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  55229. savedSceneClearColor = scene.clearColor;
  55230. scene.clearColor = sceneClearColor;
  55231. });
  55232. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  55233. scene.clearColor = savedSceneClearColor;
  55234. });
  55235. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  55236. var engine = scene.getEngine();
  55237. var index;
  55238. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55239. renderSubMesh(opaqueSubMeshes.data[index]);
  55240. }
  55241. engine.setAlphaTesting(true);
  55242. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55243. renderSubMesh(alphaTestSubMeshes.data[index]);
  55244. }
  55245. engine.setAlphaTesting(false);
  55246. if (transparentSubMeshes.length) {
  55247. // Sort sub meshes
  55248. for (index = 0; index < transparentSubMeshes.length; index++) {
  55249. var submesh = transparentSubMeshes.data[index];
  55250. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  55251. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  55252. }
  55253. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  55254. sortedArray.sort(function (a, b) {
  55255. // Alpha index first
  55256. if (a._alphaIndex > b._alphaIndex) {
  55257. return 1;
  55258. }
  55259. if (a._alphaIndex < b._alphaIndex) {
  55260. return -1;
  55261. }
  55262. // Then distance to camera
  55263. if (a._distanceToCamera < b._distanceToCamera) {
  55264. return 1;
  55265. }
  55266. if (a._distanceToCamera > b._distanceToCamera) {
  55267. return -1;
  55268. }
  55269. return 0;
  55270. });
  55271. // Render sub meshes
  55272. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55273. for (index = 0; index < sortedArray.length; index++) {
  55274. renderSubMesh(sortedArray[index]);
  55275. }
  55276. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55277. }
  55278. };
  55279. };
  55280. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  55281. var transform = scene.getTransformMatrix();
  55282. var meshPosition;
  55283. if (this.useCustomMeshPosition) {
  55284. meshPosition = this.customMeshPosition;
  55285. }
  55286. else if (this.attachedNode) {
  55287. meshPosition = this.attachedNode.position;
  55288. }
  55289. else {
  55290. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  55291. }
  55292. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  55293. this._screenCoordinates.x = pos.x / this._viewPort.width;
  55294. this._screenCoordinates.y = pos.y / this._viewPort.height;
  55295. if (this.invert)
  55296. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  55297. };
  55298. // Static methods
  55299. /**
  55300. * Creates a default mesh for the Volumeric Light Scattering post-process
  55301. * @param {string} The mesh name
  55302. * @param {BABYLON.Scene} The scene where to create the mesh
  55303. * @return {BABYLON.Mesh} the default mesh
  55304. */
  55305. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  55306. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  55307. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55308. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  55309. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  55310. mesh.material = material;
  55311. return mesh;
  55312. };
  55313. __decorate([
  55314. BABYLON.serializeAsVector3()
  55315. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  55316. __decorate([
  55317. BABYLON.serialize()
  55318. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  55319. __decorate([
  55320. BABYLON.serialize()
  55321. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  55322. __decorate([
  55323. BABYLON.serializeAsMeshReference()
  55324. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  55325. __decorate([
  55326. BABYLON.serialize()
  55327. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  55328. __decorate([
  55329. BABYLON.serialize()
  55330. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  55331. __decorate([
  55332. BABYLON.serialize()
  55333. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  55334. __decorate([
  55335. BABYLON.serialize()
  55336. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  55337. __decorate([
  55338. BABYLON.serialize()
  55339. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  55340. return VolumetricLightScatteringPostProcess;
  55341. })(BABYLON.PostProcess);
  55342. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  55343. })(BABYLON || (BABYLON = {}));
  55344. // BABYLON.JS Chromatic Aberration GLSL Shader
  55345. // Author: Olivier Guyot
  55346. // Separates very slightly R, G and B colors on the edges of the screen
  55347. // Inspired by Francois Tarlier & Martins Upitis
  55348. var BABYLON;
  55349. (function (BABYLON) {
  55350. var LensRenderingPipeline = (function (_super) {
  55351. __extends(LensRenderingPipeline, _super);
  55352. /**
  55353. * @constructor
  55354. *
  55355. * Effect parameters are as follow:
  55356. * {
  55357. * chromatic_aberration: number; // from 0 to x (1 for realism)
  55358. * edge_blur: number; // from 0 to x (1 for realism)
  55359. * distortion: number; // from 0 to x (1 for realism)
  55360. * grain_amount: number; // from 0 to 1
  55361. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  55362. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  55363. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  55364. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  55365. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  55366. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  55367. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  55368. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  55369. * }
  55370. * Note: if an effect parameter is unset, effect is disabled
  55371. *
  55372. * @param {string} name - The rendering pipeline name
  55373. * @param {object} parameters - An object containing all parameters (see above)
  55374. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55375. * @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)
  55376. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55377. */
  55378. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  55379. var _this = this;
  55380. if (ratio === void 0) { ratio = 1.0; }
  55381. _super.call(this, scene.getEngine(), name);
  55382. // Lens effects can be of the following:
  55383. // - chromatic aberration (slight shift of RGB colors)
  55384. // - blur on the edge of the lens
  55385. // - lens distortion
  55386. // - depth-of-field blur & highlights enhancing
  55387. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  55388. // - grain effect (noise or custom texture)
  55389. // Two additional texture samplers are needed:
  55390. // - depth map (for depth-of-field)
  55391. // - grain texture
  55392. /**
  55393. * The chromatic aberration PostProcess id in the pipeline
  55394. * @type {string}
  55395. */
  55396. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  55397. /**
  55398. * The highlights enhancing PostProcess id in the pipeline
  55399. * @type {string}
  55400. */
  55401. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  55402. /**
  55403. * The depth-of-field PostProcess id in the pipeline
  55404. * @type {string}
  55405. */
  55406. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  55407. this._scene = scene;
  55408. // Fetch texture samplers
  55409. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  55410. if (parameters.grain_texture) {
  55411. this._grainTexture = parameters.grain_texture;
  55412. }
  55413. else {
  55414. this._createGrainTexture();
  55415. }
  55416. // save parameters
  55417. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  55418. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  55419. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  55420. this._distortion = parameters.distortion ? parameters.distortion : 0;
  55421. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  55422. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  55423. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  55424. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  55425. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  55426. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  55427. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  55428. // Create effects
  55429. this._createChromaticAberrationPostProcess(ratio);
  55430. this._createHighlightsPostProcess(ratio);
  55431. this._createDepthOfFieldPostProcess(ratio / 4);
  55432. // Set up pipeline
  55433. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  55434. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  55435. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  55436. if (this._highlightsGain === -1) {
  55437. this._disableEffect(this.HighlightsEnhancingEffect, null);
  55438. }
  55439. // Finish
  55440. scene.postProcessRenderPipelineManager.addPipeline(this);
  55441. if (cameras) {
  55442. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55443. }
  55444. }
  55445. // public methods (self explanatory)
  55446. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  55447. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  55448. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  55449. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  55450. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  55451. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  55452. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  55453. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  55454. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  55455. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  55456. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  55457. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  55458. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  55459. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  55460. };
  55461. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  55462. this._highlightsPostProcess.updateEffect();
  55463. };
  55464. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  55465. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  55466. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  55467. this._highlightsGain = amount;
  55468. };
  55469. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  55470. if (this._highlightsGain === -1) {
  55471. this._highlightsGain = 1.0;
  55472. }
  55473. this._highlightsThreshold = amount;
  55474. };
  55475. LensRenderingPipeline.prototype.disableHighlights = function () {
  55476. this._highlightsGain = -1;
  55477. };
  55478. /**
  55479. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  55480. */
  55481. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  55482. if (disableDepthRender === void 0) { disableDepthRender = false; }
  55483. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55484. this._chromaticAberrationPostProcess = undefined;
  55485. this._highlightsPostProcess = undefined;
  55486. this._depthOfFieldPostProcess = undefined;
  55487. this._grainTexture.dispose();
  55488. if (disableDepthRender)
  55489. this._scene.disableDepthRenderer();
  55490. };
  55491. // colors shifting and distortion
  55492. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  55493. var _this = this;
  55494. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  55495. [], // samplers
  55496. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  55497. this._chromaticAberrationPostProcess.onApply = function (effect) {
  55498. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  55499. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  55500. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  55501. };
  55502. };
  55503. // highlights enhancing
  55504. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  55505. var _this = this;
  55506. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  55507. [], // samplers
  55508. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  55509. this._highlightsPostProcess.onApply = function (effect) {
  55510. effect.setFloat('gain', _this._highlightsGain);
  55511. effect.setFloat('threshold', _this._highlightsThreshold);
  55512. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  55513. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  55514. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  55515. };
  55516. };
  55517. // colors shifting and distortion
  55518. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  55519. var _this = this;
  55520. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  55521. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  55522. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  55523. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  55524. this._depthOfFieldPostProcess.onApply = function (effect) {
  55525. effect.setTexture("depthSampler", _this._depthTexture);
  55526. effect.setTexture("grainSampler", _this._grainTexture);
  55527. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  55528. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  55529. effect.setFloat('grain_amount', _this._grainAmount);
  55530. effect.setBool('blur_noise', _this._blurNoise);
  55531. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  55532. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  55533. effect.setFloat('distortion', _this._distortion);
  55534. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  55535. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  55536. effect.setFloat('aperture', _this._dofAperture);
  55537. effect.setFloat('darken', _this._dofDarken);
  55538. effect.setFloat('edge_blur', _this._edgeBlur);
  55539. effect.setBool('highlights', (_this._highlightsGain !== -1));
  55540. effect.setFloat('near', _this._scene.activeCamera.minZ);
  55541. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  55542. };
  55543. };
  55544. // creates a black and white random noise texture, 512x512
  55545. LensRenderingPipeline.prototype._createGrainTexture = function () {
  55546. var size = 512;
  55547. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55548. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55549. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55550. var context = this._grainTexture.getContext();
  55551. var rand = function (min, max) {
  55552. return Math.random() * (max - min) + min;
  55553. };
  55554. var value;
  55555. for (var x = 0; x < size; x++) {
  55556. for (var y = 0; y < size; y++) {
  55557. value = Math.floor(rand(0.42, 0.58) * 255);
  55558. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  55559. context.fillRect(x, y, 1, 1);
  55560. }
  55561. }
  55562. this._grainTexture.update(false);
  55563. };
  55564. return LensRenderingPipeline;
  55565. })(BABYLON.PostProcessRenderPipeline);
  55566. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  55567. })(BABYLON || (BABYLON = {}));
  55568. //
  55569. // This post-process allows the modification of rendered colors by using
  55570. // a 'look-up table' (LUT). This effect is also called Color Grading.
  55571. //
  55572. // The object needs to be provided an url to a texture containing the color
  55573. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  55574. // Use an image editing software to tweak the LUT to match your needs.
  55575. //
  55576. // For an example of a color LUT, see here:
  55577. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  55578. // For explanations on color grading, see here:
  55579. // http://udn.epicgames.com/Three/ColorGrading.html
  55580. //
  55581. var BABYLON;
  55582. (function (BABYLON) {
  55583. var ColorCorrectionPostProcess = (function (_super) {
  55584. __extends(ColorCorrectionPostProcess, _super);
  55585. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  55586. var _this = this;
  55587. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  55588. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  55589. this._colorTableTexture.anisotropicFilteringLevel = 1;
  55590. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55591. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55592. this.onApply = function (effect) {
  55593. effect.setTexture("colorTable", _this._colorTableTexture);
  55594. };
  55595. }
  55596. return ColorCorrectionPostProcess;
  55597. })(BABYLON.PostProcess);
  55598. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  55599. })(BABYLON || (BABYLON = {}));
  55600. var BABYLON;
  55601. (function (BABYLON) {
  55602. var AnaglyphFreeCamera = (function (_super) {
  55603. __extends(AnaglyphFreeCamera, _super);
  55604. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  55605. _super.call(this, name, position, scene);
  55606. this.interaxialDistance = interaxialDistance;
  55607. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  55608. }
  55609. AnaglyphFreeCamera.prototype.getTypeName = function () {
  55610. return "AnaglyphFreeCamera";
  55611. };
  55612. return AnaglyphFreeCamera;
  55613. })(BABYLON.FreeCamera);
  55614. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  55615. var AnaglyphArcRotateCamera = (function (_super) {
  55616. __extends(AnaglyphArcRotateCamera, _super);
  55617. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  55618. _super.call(this, name, alpha, beta, radius, target, scene);
  55619. this.interaxialDistance = interaxialDistance;
  55620. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  55621. }
  55622. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  55623. return "AnaglyphArcRotateCamera";
  55624. };
  55625. return AnaglyphArcRotateCamera;
  55626. })(BABYLON.ArcRotateCamera);
  55627. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  55628. var AnaglyphGamepadCamera = (function (_super) {
  55629. __extends(AnaglyphGamepadCamera, _super);
  55630. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  55631. _super.call(this, name, position, scene);
  55632. this.interaxialDistance = interaxialDistance;
  55633. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  55634. }
  55635. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  55636. return "AnaglyphGamepadCamera";
  55637. };
  55638. return AnaglyphGamepadCamera;
  55639. })(BABYLON.GamepadCamera);
  55640. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  55641. var AnaglyphUniversalCamera = (function (_super) {
  55642. __extends(AnaglyphUniversalCamera, _super);
  55643. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  55644. _super.call(this, name, position, scene);
  55645. this.interaxialDistance = interaxialDistance;
  55646. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  55647. }
  55648. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  55649. return "AnaglyphUniversalCamera";
  55650. };
  55651. return AnaglyphUniversalCamera;
  55652. })(BABYLON.UniversalCamera);
  55653. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  55654. var StereoscopicFreeCamera = (function (_super) {
  55655. __extends(StereoscopicFreeCamera, _super);
  55656. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  55657. _super.call(this, name, position, scene);
  55658. this.interaxialDistance = interaxialDistance;
  55659. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  55660. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  55661. }
  55662. StereoscopicFreeCamera.prototype.getTypeName = function () {
  55663. return "StereoscopicFreeCamera";
  55664. };
  55665. return StereoscopicFreeCamera;
  55666. })(BABYLON.FreeCamera);
  55667. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  55668. var StereoscopicArcRotateCamera = (function (_super) {
  55669. __extends(StereoscopicArcRotateCamera, _super);
  55670. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  55671. _super.call(this, name, alpha, beta, radius, target, scene);
  55672. this.interaxialDistance = interaxialDistance;
  55673. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  55674. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  55675. }
  55676. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  55677. return "StereoscopicArcRotateCamera";
  55678. };
  55679. return StereoscopicArcRotateCamera;
  55680. })(BABYLON.ArcRotateCamera);
  55681. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  55682. var StereoscopicGamepadCamera = (function (_super) {
  55683. __extends(StereoscopicGamepadCamera, _super);
  55684. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  55685. _super.call(this, name, position, scene);
  55686. this.interaxialDistance = interaxialDistance;
  55687. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  55688. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  55689. }
  55690. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  55691. return "StereoscopicGamepadCamera";
  55692. };
  55693. return StereoscopicGamepadCamera;
  55694. })(BABYLON.GamepadCamera);
  55695. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  55696. var StereoscopicUniversalCamera = (function (_super) {
  55697. __extends(StereoscopicUniversalCamera, _super);
  55698. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  55699. _super.call(this, name, position, scene);
  55700. this.interaxialDistance = interaxialDistance;
  55701. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  55702. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  55703. }
  55704. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  55705. return "StereoscopicUniversalCamera";
  55706. };
  55707. return StereoscopicUniversalCamera;
  55708. })(BABYLON.UniversalCamera);
  55709. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  55710. })(BABYLON || (BABYLON = {}));
  55711. var BABYLON;
  55712. (function (BABYLON) {
  55713. var HDRRenderingPipeline = (function (_super) {
  55714. __extends(HDRRenderingPipeline, _super);
  55715. /**
  55716. * @constructor
  55717. * @param {string} name - The rendering pipeline name
  55718. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55719. * @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)
  55720. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  55721. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55722. */
  55723. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  55724. var _this = this;
  55725. if (originalPostProcess === void 0) { originalPostProcess = null; }
  55726. _super.call(this, scene.getEngine(), name);
  55727. /**
  55728. * Public members
  55729. */
  55730. // Gaussian Blur
  55731. /**
  55732. * Gaussian blur coefficient
  55733. * @type {number}
  55734. */
  55735. this.gaussCoeff = 0.3;
  55736. /**
  55737. * Gaussian blur mean
  55738. * @type {number}
  55739. */
  55740. this.gaussMean = 1.0;
  55741. /**
  55742. * Gaussian blur standard deviation
  55743. * @type {number}
  55744. */
  55745. this.gaussStandDev = 0.8;
  55746. /**
  55747. * Gaussian blur multiplier. Multiplies the blur effect
  55748. * @type {number}
  55749. */
  55750. this.gaussMultiplier = 4.0;
  55751. // HDR
  55752. /**
  55753. * Exposure, controls the overall intensity of the pipeline
  55754. * @type {number}
  55755. */
  55756. this.exposure = 1.0;
  55757. /**
  55758. * Minimum luminance that the post-process can output. Luminance is >= 0
  55759. * @type {number}
  55760. */
  55761. this.minimumLuminance = 1.0;
  55762. /**
  55763. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  55764. * @type {number}
  55765. */
  55766. this.maximumLuminance = 1e20;
  55767. /**
  55768. * Increase rate for luminance: eye adaptation speed to dark
  55769. * @type {number}
  55770. */
  55771. this.luminanceIncreaserate = 0.5;
  55772. /**
  55773. * Decrease rate for luminance: eye adaptation speed to bright
  55774. * @type {number}
  55775. */
  55776. this.luminanceDecreaseRate = 0.5;
  55777. // Bright pass
  55778. /**
  55779. * Minimum luminance needed to compute HDR
  55780. * @type {number}
  55781. */
  55782. this.brightThreshold = 0.8;
  55783. this._needUpdate = true;
  55784. this._scene = scene;
  55785. // Bright pass
  55786. this._createBrightPassPostProcess(scene, ratio);
  55787. // Down sample X4
  55788. this._createDownSampleX4PostProcess(scene, ratio);
  55789. // Create gaussian blur post-processes
  55790. this._createGaussianBlurPostProcess(scene, ratio);
  55791. // Texture adder
  55792. this._createTextureAdderPostProcess(scene, ratio);
  55793. // Luminance generator
  55794. this._createLuminanceGeneratorPostProcess(scene);
  55795. // HDR
  55796. this._createHDRPostProcess(scene, ratio);
  55797. // Pass postprocess
  55798. if (originalPostProcess === null) {
  55799. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  55800. }
  55801. else {
  55802. this._originalPostProcess = originalPostProcess;
  55803. }
  55804. // Configure pipeline
  55805. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  55806. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  55807. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  55808. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  55809. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  55810. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  55811. var addDownSamplerPostProcess = function (id) {
  55812. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  55813. };
  55814. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  55815. addDownSamplerPostProcess(i);
  55816. }
  55817. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  55818. // Finish
  55819. scene.postProcessRenderPipelineManager.addPipeline(this);
  55820. if (cameras !== null) {
  55821. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55822. }
  55823. this.update();
  55824. }
  55825. /**
  55826. * Tells the pipeline to update its post-processes
  55827. */
  55828. HDRRenderingPipeline.prototype.update = function () {
  55829. this._needUpdate = true;
  55830. };
  55831. /**
  55832. * Returns the current calculated luminance
  55833. */
  55834. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  55835. return this._hdrCurrentLuminance;
  55836. };
  55837. /**
  55838. * Returns the currently drawn luminance
  55839. */
  55840. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  55841. return this._hdrOutputLuminance;
  55842. };
  55843. /**
  55844. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  55845. */
  55846. HDRRenderingPipeline.prototype.dispose = function () {
  55847. this._originalPostProcess = undefined;
  55848. this._brightPassPostProcess = undefined;
  55849. this._downSampleX4PostProcess = undefined;
  55850. this._guassianBlurHPostProcess = undefined;
  55851. this._guassianBlurVPostProcess = undefined;
  55852. this._textureAdderPostProcess = undefined;
  55853. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  55854. this._downSamplePostProcesses[i] = undefined;
  55855. }
  55856. this._hdrPostProcess = undefined;
  55857. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55858. };
  55859. /**
  55860. * Creates the HDR post-process and computes the luminance adaptation
  55861. */
  55862. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  55863. var _this = this;
  55864. var hdrLastLuminance = 0.0;
  55865. this._hdrOutputLuminance = -1.0;
  55866. this._hdrCurrentLuminance = 1.0;
  55867. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  55868. this._hdrPostProcess.onApply = function (effect) {
  55869. if (_this._hdrOutputLuminance < 0.0) {
  55870. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  55871. }
  55872. else {
  55873. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  55874. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  55875. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  55876. }
  55877. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  55878. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  55879. }
  55880. else {
  55881. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  55882. }
  55883. }
  55884. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  55885. hdrLastLuminance += scene.getEngine().getDeltaTime();
  55886. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  55887. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  55888. effect.setFloat("exposure", _this.exposure);
  55889. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  55890. _this._needUpdate = false;
  55891. };
  55892. };
  55893. /**
  55894. * Texture Adder post-process
  55895. */
  55896. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  55897. var _this = this;
  55898. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  55899. this._textureAdderPostProcess.onApply = function (effect) {
  55900. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  55901. };
  55902. };
  55903. /**
  55904. * Down sample X4 post-process
  55905. */
  55906. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  55907. var _this = this;
  55908. var downSampleX4Offsets = new Array(32);
  55909. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  55910. this._downSampleX4PostProcess.onApply = function (effect) {
  55911. if (_this._needUpdate) {
  55912. var id = 0;
  55913. for (var i = -2; i < 2; i++) {
  55914. for (var j = -2; j < 2; j++) {
  55915. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  55916. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  55917. id += 2;
  55918. }
  55919. }
  55920. }
  55921. effect.setArray2("dsOffsets", downSampleX4Offsets);
  55922. };
  55923. };
  55924. /**
  55925. * Bright pass post-process
  55926. */
  55927. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  55928. var _this = this;
  55929. var brightOffsets = new Array(8);
  55930. var brightPassCallback = function (effect) {
  55931. if (_this._needUpdate) {
  55932. var sU = (1.0 / _this._brightPassPostProcess.width);
  55933. var sV = (1.0 / _this._brightPassPostProcess.height);
  55934. brightOffsets[0] = -0.5 * sU;
  55935. brightOffsets[1] = 0.5 * sV;
  55936. brightOffsets[2] = 0.5 * sU;
  55937. brightOffsets[3] = 0.5 * sV;
  55938. brightOffsets[4] = -0.5 * sU;
  55939. brightOffsets[5] = -0.5 * sV;
  55940. brightOffsets[6] = 0.5 * sU;
  55941. brightOffsets[7] = -0.5 * sV;
  55942. }
  55943. effect.setArray2("dsOffsets", brightOffsets);
  55944. effect.setFloat("brightThreshold", _this.brightThreshold);
  55945. };
  55946. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  55947. this._brightPassPostProcess.onApply = brightPassCallback;
  55948. };
  55949. /**
  55950. * Luminance generator. Creates the luminance post-process and down sample post-processes
  55951. */
  55952. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  55953. var _this = this;
  55954. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  55955. var luminanceOffsets = new Array(8);
  55956. var downSampleOffsets = new Array(18);
  55957. var halfDestPixelSize;
  55958. this._downSamplePostProcesses = new Array(lumSteps);
  55959. // Utils for luminance
  55960. var luminanceUpdateSourceOffsets = function (width, height) {
  55961. var sU = (1.0 / width);
  55962. var sV = (1.0 / height);
  55963. luminanceOffsets[0] = -0.5 * sU;
  55964. luminanceOffsets[1] = 0.5 * sV;
  55965. luminanceOffsets[2] = 0.5 * sU;
  55966. luminanceOffsets[3] = 0.5 * sV;
  55967. luminanceOffsets[4] = -0.5 * sU;
  55968. luminanceOffsets[5] = -0.5 * sV;
  55969. luminanceOffsets[6] = 0.5 * sU;
  55970. luminanceOffsets[7] = -0.5 * sV;
  55971. };
  55972. var luminanceUpdateDestOffsets = function (width, height) {
  55973. var id = 0;
  55974. for (var x = -1; x < 2; x++) {
  55975. for (var y = -1; y < 2; y++) {
  55976. downSampleOffsets[id] = (x) / width;
  55977. downSampleOffsets[id + 1] = (y) / height;
  55978. id += 2;
  55979. }
  55980. }
  55981. };
  55982. // Luminance callback
  55983. var luminanceCallback = function (effect) {
  55984. if (_this._needUpdate) {
  55985. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  55986. }
  55987. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  55988. effect.setArray2("lumOffsets", luminanceOffsets);
  55989. };
  55990. // Down sample callbacks
  55991. var downSampleCallback = function (indice) {
  55992. var i = indice;
  55993. return function (effect) {
  55994. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  55995. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  55996. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  55997. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  55998. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  55999. effect.setArray2("dsOffsets", downSampleOffsets);
  56000. };
  56001. };
  56002. var downSampleAfterRenderCallback = function (effect) {
  56003. // Unpack result
  56004. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  56005. 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);
  56006. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  56007. };
  56008. // Create luminance post-process
  56009. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  56010. 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);
  56011. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  56012. // Create down sample post-processes
  56013. for (var i = lumSteps - 2; i >= 0; i--) {
  56014. var length = Math.pow(3, i);
  56015. ratio = { width: length, height: length };
  56016. var defines = "#define DOWN_SAMPLE\n";
  56017. if (i === 0) {
  56018. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  56019. }
  56020. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  56021. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  56022. if (i === 0) {
  56023. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  56024. }
  56025. }
  56026. };
  56027. /**
  56028. * Gaussian blur post-processes. Horizontal and Vertical
  56029. */
  56030. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  56031. var _this = this;
  56032. var blurOffsetsW = new Array(9);
  56033. var blurOffsetsH = new Array(9);
  56034. var blurWeights = new Array(9);
  56035. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  56036. // Utils for gaussian blur
  56037. var calculateBlurOffsets = function (height) {
  56038. var lastOutputDimensions = {
  56039. width: scene.getEngine().getRenderWidth(),
  56040. height: scene.getEngine().getRenderHeight()
  56041. };
  56042. for (var i = 0; i < 9; i++) {
  56043. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  56044. if (height) {
  56045. blurOffsetsH[i] = value;
  56046. }
  56047. else {
  56048. blurOffsetsW[i] = value;
  56049. }
  56050. }
  56051. };
  56052. var calculateWeights = function () {
  56053. var x = 0.0;
  56054. for (var i = 0; i < 9; i++) {
  56055. x = (i - 4.0) / 4.0;
  56056. 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));
  56057. }
  56058. };
  56059. // Callback
  56060. var gaussianBlurCallback = function (height) {
  56061. return function (effect) {
  56062. if (_this._needUpdate) {
  56063. calculateWeights();
  56064. calculateBlurOffsets(height);
  56065. }
  56066. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  56067. effect.setArray("blurWeights", blurWeights);
  56068. effect.setFloat("multiplier", _this.gaussMultiplier);
  56069. };
  56070. };
  56071. // Create horizontal gaussian blur post-processes
  56072. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  56073. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  56074. // Create vertical gaussian blur post-process
  56075. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  56076. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  56077. };
  56078. // Luminance generator
  56079. HDRRenderingPipeline.LUM_STEPS = 6;
  56080. return HDRRenderingPipeline;
  56081. })(BABYLON.PostProcessRenderPipeline);
  56082. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  56083. })(BABYLON || (BABYLON = {}));
  56084. var BABYLON;
  56085. (function (BABYLON) {
  56086. var FaceAdjacencies = (function () {
  56087. function FaceAdjacencies() {
  56088. this.edges = new Array();
  56089. this.edgesConnectedCount = 0;
  56090. }
  56091. return FaceAdjacencies;
  56092. })();
  56093. var EdgesRenderer = (function () {
  56094. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  56095. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  56096. if (epsilon === void 0) { epsilon = 0.95; }
  56097. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  56098. this.edgesWidthScalerForOrthographic = 1000.0;
  56099. this.edgesWidthScalerForPerspective = 50.0;
  56100. this._linesPositions = new Array();
  56101. this._linesNormals = new Array();
  56102. this._linesIndices = new Array();
  56103. this._buffers = {};
  56104. this._checkVerticesInsteadOfIndices = false;
  56105. this._source = source;
  56106. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  56107. this._epsilon = epsilon;
  56108. this._prepareRessources();
  56109. this._generateEdgesLines();
  56110. }
  56111. EdgesRenderer.prototype._prepareRessources = function () {
  56112. if (this._lineShader) {
  56113. return;
  56114. }
  56115. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  56116. attributes: ["position", "normal"],
  56117. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  56118. });
  56119. this._lineShader.disableDepthWrite = true;
  56120. this._lineShader.backFaceCulling = false;
  56121. };
  56122. EdgesRenderer.prototype.dispose = function () {
  56123. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  56124. if (buffer) {
  56125. buffer.dispose();
  56126. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  56127. }
  56128. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  56129. if (buffer) {
  56130. buffer.dispose();
  56131. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  56132. }
  56133. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  56134. this._lineShader.dispose();
  56135. };
  56136. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  56137. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  56138. return 0;
  56139. }
  56140. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  56141. return 1;
  56142. }
  56143. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  56144. return 2;
  56145. }
  56146. return -1;
  56147. };
  56148. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  56149. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  56150. return 0;
  56151. }
  56152. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  56153. return 1;
  56154. }
  56155. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  56156. return 2;
  56157. }
  56158. return -1;
  56159. };
  56160. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  56161. var needToCreateLine;
  56162. if (edge === undefined) {
  56163. needToCreateLine = true;
  56164. }
  56165. else {
  56166. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  56167. needToCreateLine = dotProduct < this._epsilon;
  56168. }
  56169. if (needToCreateLine) {
  56170. var offset = this._linesPositions.length / 3;
  56171. var normal = p0.subtract(p1);
  56172. normal.normalize();
  56173. // Positions
  56174. this._linesPositions.push(p0.x);
  56175. this._linesPositions.push(p0.y);
  56176. this._linesPositions.push(p0.z);
  56177. this._linesPositions.push(p0.x);
  56178. this._linesPositions.push(p0.y);
  56179. this._linesPositions.push(p0.z);
  56180. this._linesPositions.push(p1.x);
  56181. this._linesPositions.push(p1.y);
  56182. this._linesPositions.push(p1.z);
  56183. this._linesPositions.push(p1.x);
  56184. this._linesPositions.push(p1.y);
  56185. this._linesPositions.push(p1.z);
  56186. // Normals
  56187. this._linesNormals.push(p1.x);
  56188. this._linesNormals.push(p1.y);
  56189. this._linesNormals.push(p1.z);
  56190. this._linesNormals.push(-1);
  56191. this._linesNormals.push(p1.x);
  56192. this._linesNormals.push(p1.y);
  56193. this._linesNormals.push(p1.z);
  56194. this._linesNormals.push(1);
  56195. this._linesNormals.push(p0.x);
  56196. this._linesNormals.push(p0.y);
  56197. this._linesNormals.push(p0.z);
  56198. this._linesNormals.push(-1);
  56199. this._linesNormals.push(p0.x);
  56200. this._linesNormals.push(p0.y);
  56201. this._linesNormals.push(p0.z);
  56202. this._linesNormals.push(1);
  56203. // Indices
  56204. this._linesIndices.push(offset);
  56205. this._linesIndices.push(offset + 1);
  56206. this._linesIndices.push(offset + 2);
  56207. this._linesIndices.push(offset);
  56208. this._linesIndices.push(offset + 2);
  56209. this._linesIndices.push(offset + 3);
  56210. }
  56211. };
  56212. EdgesRenderer.prototype._generateEdgesLines = function () {
  56213. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56214. var indices = this._source.getIndices();
  56215. // First let's find adjacencies
  56216. var adjacencies = new Array();
  56217. var faceNormals = new Array();
  56218. var index;
  56219. var faceAdjacencies;
  56220. // Prepare faces
  56221. for (index = 0; index < indices.length; index += 3) {
  56222. faceAdjacencies = new FaceAdjacencies();
  56223. var p0Index = indices[index];
  56224. var p1Index = indices[index + 1];
  56225. var p2Index = indices[index + 2];
  56226. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  56227. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  56228. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  56229. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  56230. faceNormal.normalize();
  56231. faceNormals.push(faceNormal);
  56232. adjacencies.push(faceAdjacencies);
  56233. }
  56234. // Scan
  56235. for (index = 0; index < adjacencies.length; index++) {
  56236. faceAdjacencies = adjacencies[index];
  56237. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  56238. var otherFaceAdjacencies = adjacencies[otherIndex];
  56239. if (faceAdjacencies.edgesConnectedCount === 3) {
  56240. break;
  56241. }
  56242. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  56243. continue;
  56244. }
  56245. var otherP0 = indices[otherIndex * 3];
  56246. var otherP1 = indices[otherIndex * 3 + 1];
  56247. var otherP2 = indices[otherIndex * 3 + 2];
  56248. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  56249. var otherEdgeIndex;
  56250. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  56251. continue;
  56252. }
  56253. switch (edgeIndex) {
  56254. case 0:
  56255. if (this._checkVerticesInsteadOfIndices) {
  56256. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  56257. }
  56258. else {
  56259. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  56260. }
  56261. break;
  56262. case 1:
  56263. if (this._checkVerticesInsteadOfIndices) {
  56264. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  56265. }
  56266. else {
  56267. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  56268. }
  56269. break;
  56270. case 2:
  56271. if (this._checkVerticesInsteadOfIndices) {
  56272. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  56273. }
  56274. else {
  56275. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  56276. }
  56277. break;
  56278. }
  56279. if (otherEdgeIndex === -1) {
  56280. continue;
  56281. }
  56282. faceAdjacencies.edges[edgeIndex] = otherIndex;
  56283. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  56284. faceAdjacencies.edgesConnectedCount++;
  56285. otherFaceAdjacencies.edgesConnectedCount++;
  56286. if (faceAdjacencies.edgesConnectedCount === 3) {
  56287. break;
  56288. }
  56289. }
  56290. }
  56291. }
  56292. // Create lines
  56293. for (index = 0; index < adjacencies.length; index++) {
  56294. // 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
  56295. var current = adjacencies[index];
  56296. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  56297. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  56298. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  56299. }
  56300. // Merge into a single mesh
  56301. var engine = this._source.getScene().getEngine();
  56302. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  56303. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  56304. this._ib = engine.createIndexBuffer(this._linesIndices);
  56305. this._indicesCount = this._linesIndices.length;
  56306. };
  56307. EdgesRenderer.prototype.render = function () {
  56308. if (!this._lineShader.isReady()) {
  56309. return;
  56310. }
  56311. var scene = this._source.getScene();
  56312. var engine = scene.getEngine();
  56313. this._lineShader._preBind();
  56314. // VBOs
  56315. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  56316. scene.resetCachedMaterial();
  56317. this._lineShader.setColor4("color", this._source.edgesColor);
  56318. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  56319. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  56320. }
  56321. else {
  56322. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  56323. }
  56324. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  56325. this._lineShader.bind(this._source.getWorldMatrix());
  56326. // Draw order
  56327. engine.draw(true, 0, this._indicesCount);
  56328. this._lineShader.unbind();
  56329. engine.setDepthWrite(true);
  56330. };
  56331. return EdgesRenderer;
  56332. })();
  56333. BABYLON.EdgesRenderer = EdgesRenderer;
  56334. })(BABYLON || (BABYLON = {}));
  56335. var BABYLON;
  56336. (function (BABYLON) {
  56337. (function (TonemappingOperator) {
  56338. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  56339. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  56340. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  56341. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  56342. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  56343. var TonemappingOperator = BABYLON.TonemappingOperator;
  56344. ;
  56345. var TonemapPostProcess = (function (_super) {
  56346. __extends(TonemapPostProcess, _super);
  56347. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  56348. var _this = this;
  56349. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  56350. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56351. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  56352. this._operator = _operator;
  56353. this.exposureAdjustment = exposureAdjustment;
  56354. var defines = "#define ";
  56355. if (this._operator === TonemappingOperator.Hable)
  56356. defines += "HABLE_TONEMAPPING";
  56357. else if (this._operator === TonemappingOperator.Reinhard)
  56358. defines += "REINHARD_TONEMAPPING";
  56359. else if (this._operator === TonemappingOperator.HejiDawson)
  56360. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  56361. else if (this._operator === TonemappingOperator.Photographic)
  56362. defines += "PHOTOGRAPHIC_TONEMAPPING";
  56363. //sadly a second call to create the effect.
  56364. this.updateEffect(defines);
  56365. this.onApply = function (effect) {
  56366. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  56367. };
  56368. }
  56369. return TonemapPostProcess;
  56370. })(BABYLON.PostProcess);
  56371. BABYLON.TonemapPostProcess = TonemapPostProcess;
  56372. })(BABYLON || (BABYLON = {}));
  56373. var BABYLON;
  56374. (function (BABYLON) {
  56375. var ReflectionProbe = (function () {
  56376. function ReflectionProbe(name, size, scene, generateMipMaps) {
  56377. var _this = this;
  56378. if (generateMipMaps === void 0) { generateMipMaps = true; }
  56379. this.name = name;
  56380. this._viewMatrix = BABYLON.Matrix.Identity();
  56381. this._target = BABYLON.Vector3.Zero();
  56382. this._add = BABYLON.Vector3.Zero();
  56383. this.invertYAxis = false;
  56384. this.position = BABYLON.Vector3.Zero();
  56385. this._scene = scene;
  56386. this._scene.reflectionProbes.push(this);
  56387. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  56388. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  56389. switch (faceIndex) {
  56390. case 0:
  56391. _this._add.copyFromFloats(1, 0, 0);
  56392. break;
  56393. case 1:
  56394. _this._add.copyFromFloats(-1, 0, 0);
  56395. break;
  56396. case 2:
  56397. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  56398. break;
  56399. case 3:
  56400. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  56401. break;
  56402. case 4:
  56403. _this._add.copyFromFloats(0, 0, 1);
  56404. break;
  56405. case 5:
  56406. _this._add.copyFromFloats(0, 0, -1);
  56407. break;
  56408. }
  56409. if (_this._attachedMesh) {
  56410. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  56411. }
  56412. _this.position.addToRef(_this._add, _this._target);
  56413. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  56414. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  56415. });
  56416. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  56417. scene.updateTransformMatrix(true);
  56418. });
  56419. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  56420. }
  56421. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  56422. get: function () {
  56423. return this._renderTargetTexture.refreshRate;
  56424. },
  56425. set: function (value) {
  56426. this._renderTargetTexture.refreshRate = value;
  56427. },
  56428. enumerable: true,
  56429. configurable: true
  56430. });
  56431. ReflectionProbe.prototype.getScene = function () {
  56432. return this._scene;
  56433. };
  56434. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  56435. get: function () {
  56436. return this._renderTargetTexture;
  56437. },
  56438. enumerable: true,
  56439. configurable: true
  56440. });
  56441. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  56442. get: function () {
  56443. return this._renderTargetTexture.renderList;
  56444. },
  56445. enumerable: true,
  56446. configurable: true
  56447. });
  56448. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  56449. this._attachedMesh = mesh;
  56450. };
  56451. ReflectionProbe.prototype.dispose = function () {
  56452. var index = this._scene.reflectionProbes.indexOf(this);
  56453. if (index !== -1) {
  56454. // Remove from the scene if found
  56455. this._scene.reflectionProbes.splice(index, 1);
  56456. }
  56457. if (this._renderTargetTexture) {
  56458. this._renderTargetTexture.dispose();
  56459. this._renderTargetTexture = null;
  56460. }
  56461. };
  56462. return ReflectionProbe;
  56463. })();
  56464. BABYLON.ReflectionProbe = ReflectionProbe;
  56465. })(BABYLON || (BABYLON = {}));
  56466. var BABYLON;
  56467. (function (BABYLON) {
  56468. var SolidParticle = (function () {
  56469. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  56470. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  56471. this.position = BABYLON.Vector3.Zero(); // position
  56472. this.rotation = BABYLON.Vector3.Zero(); // rotation
  56473. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  56474. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  56475. this.velocity = BABYLON.Vector3.Zero(); // velocity
  56476. this.alive = true; // alive
  56477. this.isVisible = true; // visibility
  56478. this.idx = particleIndex;
  56479. this._pos = positionIndex;
  56480. this._model = model;
  56481. this.shapeId = shapeId;
  56482. this.idxInShape = idxInShape;
  56483. }
  56484. Object.defineProperty(SolidParticle.prototype, "scale", {
  56485. //legacy support, changed scale to scaling
  56486. get: function () {
  56487. return this.scaling;
  56488. },
  56489. set: function (scale) {
  56490. this.scaling = scale;
  56491. },
  56492. enumerable: true,
  56493. configurable: true
  56494. });
  56495. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  56496. //legacy support, changed quaternion to rotationQuaternion
  56497. get: function () {
  56498. return this.rotationQuaternion;
  56499. },
  56500. set: function (q) {
  56501. this.rotationQuaternion = q;
  56502. },
  56503. enumerable: true,
  56504. configurable: true
  56505. });
  56506. return SolidParticle;
  56507. })();
  56508. BABYLON.SolidParticle = SolidParticle;
  56509. var ModelShape = (function () {
  56510. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  56511. this.shapeID = id;
  56512. this._shape = shape;
  56513. this._shapeUV = shapeUV;
  56514. this._positionFunction = posFunction;
  56515. this._vertexFunction = vtxFunction;
  56516. }
  56517. return ModelShape;
  56518. })();
  56519. BABYLON.ModelShape = ModelShape;
  56520. })(BABYLON || (BABYLON = {}));
  56521. var BABYLON;
  56522. (function (BABYLON) {
  56523. /**
  56524. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  56525. */
  56526. var SolidParticleSystem = (function () {
  56527. /**
  56528. * Creates a SPS (Solid Particle System) object.
  56529. * `name` (String) is the SPS name, this will be the underlying mesh name.
  56530. * `scene` (Scene) is the scene in which the SPS is added.
  56531. * `updatable` (default true) : if the SPS must be updatable or immutable.
  56532. * `isPickable` (default false) : if the solid particles must be pickable.
  56533. */
  56534. function SolidParticleSystem(name, scene, options) {
  56535. // public members
  56536. /**
  56537. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  56538. * Example : var p = SPS.particles[i];
  56539. */
  56540. this.particles = new Array();
  56541. /**
  56542. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  56543. */
  56544. this.nbParticles = 0;
  56545. /**
  56546. * If the particles must ever face the camera (default false). Useful for planar particles.
  56547. */
  56548. this.billboard = false;
  56549. /**
  56550. * This a counter ofr your own usage. It's not set by any SPS functions.
  56551. */
  56552. this.counter = 0;
  56553. /**
  56554. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  56555. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  56556. */
  56557. this.vars = {};
  56558. this._positions = new Array();
  56559. this._indices = new Array();
  56560. this._normals = new Array();
  56561. this._colors = new Array();
  56562. this._uvs = new Array();
  56563. this._index = 0; // indices index
  56564. this._updatable = true;
  56565. this._pickable = false;
  56566. this._isVisibilityBoxLocked = false;
  56567. this._alwaysVisible = false;
  56568. this._shapeCounter = 0;
  56569. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  56570. this._color = new BABYLON.Color4(0, 0, 0, 0);
  56571. this._computeParticleColor = true;
  56572. this._computeParticleTexture = true;
  56573. this._computeParticleRotation = true;
  56574. this._computeParticleVertex = false;
  56575. this._computeBoundingBox = false;
  56576. this._cam_axisZ = BABYLON.Vector3.Zero();
  56577. this._cam_axisY = BABYLON.Vector3.Zero();
  56578. this._cam_axisX = BABYLON.Vector3.Zero();
  56579. this._axisX = BABYLON.Axis.X;
  56580. this._axisY = BABYLON.Axis.Y;
  56581. this._axisZ = BABYLON.Axis.Z;
  56582. this._camDir = BABYLON.Vector3.Zero();
  56583. this._rotMatrix = new BABYLON.Matrix();
  56584. this._invertMatrix = new BABYLON.Matrix();
  56585. this._rotated = BABYLON.Vector3.Zero();
  56586. this._quaternion = new BABYLON.Quaternion();
  56587. this._vertex = BABYLON.Vector3.Zero();
  56588. this._normal = BABYLON.Vector3.Zero();
  56589. this._yaw = 0.0;
  56590. this._pitch = 0.0;
  56591. this._roll = 0.0;
  56592. this._halfroll = 0.0;
  56593. this._halfpitch = 0.0;
  56594. this._halfyaw = 0.0;
  56595. this._sinRoll = 0.0;
  56596. this._cosRoll = 0.0;
  56597. this._sinPitch = 0.0;
  56598. this._cosPitch = 0.0;
  56599. this._sinYaw = 0.0;
  56600. this._cosYaw = 0.0;
  56601. this._w = 0.0;
  56602. this._minimum = BABYLON.Tmp.Vector3[0];
  56603. this._maximum = BABYLON.Tmp.Vector3[1];
  56604. this.name = name;
  56605. this._scene = scene;
  56606. this._camera = scene.activeCamera;
  56607. this._pickable = options ? options.isPickable : false;
  56608. if (options && options.updatable) {
  56609. this._updatable = options.updatable;
  56610. }
  56611. else {
  56612. this._updatable = true;
  56613. }
  56614. if (this._pickable) {
  56615. this.pickedParticles = [];
  56616. }
  56617. }
  56618. /**
  56619. * Builds the SPS underlying mesh. Returns a standard Mesh.
  56620. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  56621. */
  56622. SolidParticleSystem.prototype.buildMesh = function () {
  56623. if (this.nbParticles === 0) {
  56624. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  56625. this.addShape(triangle, 1);
  56626. triangle.dispose();
  56627. }
  56628. this._positions32 = new Float32Array(this._positions);
  56629. this._uvs32 = new Float32Array(this._uvs);
  56630. this._colors32 = new Float32Array(this._colors);
  56631. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  56632. this._normals32 = new Float32Array(this._normals);
  56633. this._fixedNormal32 = new Float32Array(this._normals);
  56634. var vertexData = new BABYLON.VertexData();
  56635. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  56636. vertexData.indices = this._indices;
  56637. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  56638. if (this._uvs32) {
  56639. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  56640. ;
  56641. }
  56642. if (this._colors32) {
  56643. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  56644. }
  56645. var mesh = new BABYLON.Mesh(this.name, this._scene);
  56646. vertexData.applyToMesh(mesh, this._updatable);
  56647. this.mesh = mesh;
  56648. this.mesh.isPickable = this._pickable;
  56649. // free memory
  56650. this._positions = null;
  56651. this._normals = null;
  56652. this._uvs = null;
  56653. this._colors = null;
  56654. if (!this._updatable) {
  56655. this.particles.length = 0;
  56656. }
  56657. return mesh;
  56658. };
  56659. /**
  56660. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  56661. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  56662. * Thus the particles generated from `digest()` have their property `position` set yet.
  56663. * `mesh` ( Mesh ) is the mesh to be digested
  56664. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  56665. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  56666. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  56667. */
  56668. SolidParticleSystem.prototype.digest = function (mesh, options) {
  56669. var size = (options && options.facetNb) || 1;
  56670. var number = (options && options.number);
  56671. var delta = (options && options.delta) || 0;
  56672. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56673. var meshInd = mesh.getIndices();
  56674. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56675. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56676. var f = 0; // facet counter
  56677. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  56678. // compute size from number
  56679. if (number) {
  56680. number = (number > totalFacets) ? totalFacets : number;
  56681. size = Math.round(totalFacets / number);
  56682. delta = 0;
  56683. }
  56684. else {
  56685. size = (size > totalFacets) ? totalFacets : size;
  56686. }
  56687. var facetPos = []; // submesh positions
  56688. var facetInd = []; // submesh indices
  56689. var facetUV = []; // submesh UV
  56690. var facetCol = []; // submesh colors
  56691. var barycenter = BABYLON.Tmp.Vector3[0];
  56692. var rand;
  56693. var sizeO = size;
  56694. while (f < totalFacets) {
  56695. size = sizeO + Math.floor((1 + delta) * Math.random());
  56696. if (f > totalFacets - size) {
  56697. size = totalFacets - f;
  56698. }
  56699. // reset temp arrays
  56700. facetPos.length = 0;
  56701. facetInd.length = 0;
  56702. facetUV.length = 0;
  56703. facetCol.length = 0;
  56704. // iterate over "size" facets
  56705. var fi = 0;
  56706. for (var j = f * 3; j < (f + size) * 3; j++) {
  56707. facetInd.push(fi);
  56708. var i = meshInd[j];
  56709. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  56710. if (meshUV) {
  56711. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  56712. }
  56713. if (meshCol) {
  56714. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  56715. }
  56716. fi++;
  56717. }
  56718. // create a model shape for each single particle
  56719. var idx = this.nbParticles;
  56720. var shape = this._posToShape(facetPos);
  56721. var shapeUV = this._uvsToShapeUV(facetUV);
  56722. // compute the barycenter of the shape
  56723. var v;
  56724. for (v = 0; v < shape.length; v++) {
  56725. barycenter.addInPlace(shape[v]);
  56726. }
  56727. barycenter.scaleInPlace(1 / shape.length);
  56728. // shift the shape from its barycenter to the origin
  56729. for (v = 0; v < shape.length; v++) {
  56730. shape[v].subtractInPlace(barycenter);
  56731. }
  56732. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  56733. // add the particle in the SPS
  56734. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  56735. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  56736. // initialize the particle position
  56737. this.particles[this.nbParticles].position.addInPlace(barycenter);
  56738. this._index += shape.length;
  56739. idx++;
  56740. this.nbParticles++;
  56741. this._shapeCounter++;
  56742. f += size;
  56743. }
  56744. return this;
  56745. };
  56746. //reset copy
  56747. SolidParticleSystem.prototype._resetCopy = function () {
  56748. this._copy.position.x = 0;
  56749. this._copy.position.y = 0;
  56750. this._copy.position.z = 0;
  56751. this._copy.rotation.x = 0;
  56752. this._copy.rotation.y = 0;
  56753. this._copy.rotation.z = 0;
  56754. this._copy.rotationQuaternion = null;
  56755. this._copy.scaling.x = 1;
  56756. this._copy.scaling.y = 1;
  56757. this._copy.scaling.z = 1;
  56758. this._copy.uvs.x = 0;
  56759. this._copy.uvs.y = 0;
  56760. this._copy.uvs.z = 1;
  56761. this._copy.uvs.w = 1;
  56762. this._copy.color = null;
  56763. };
  56764. // _meshBuilder : inserts the shape model in the global SPS mesh
  56765. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  56766. var i;
  56767. var u = 0;
  56768. var c = 0;
  56769. this._resetCopy();
  56770. if (options && options.positionFunction) {
  56771. options.positionFunction(this._copy, idx, idxInShape);
  56772. }
  56773. if (this._copy.rotationQuaternion) {
  56774. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  56775. }
  56776. else {
  56777. this._yaw = this._copy.rotation.y;
  56778. this._pitch = this._copy.rotation.x;
  56779. this._roll = this._copy.rotation.z;
  56780. this._quaternionRotationYPR();
  56781. }
  56782. this._quaternionToRotationMatrix();
  56783. for (i = 0; i < shape.length; i++) {
  56784. this._vertex.x = shape[i].x;
  56785. this._vertex.y = shape[i].y;
  56786. this._vertex.z = shape[i].z;
  56787. if (options && options.vertexFunction) {
  56788. options.vertexFunction(this._copy, this._vertex, i);
  56789. }
  56790. this._vertex.x *= this._copy.scaling.x;
  56791. this._vertex.y *= this._copy.scaling.y;
  56792. this._vertex.z *= this._copy.scaling.z;
  56793. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  56794. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  56795. if (meshUV) {
  56796. 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);
  56797. u += 2;
  56798. }
  56799. if (this._copy.color) {
  56800. this._color = this._copy.color;
  56801. }
  56802. else if (meshCol && meshCol[c] !== undefined) {
  56803. this._color.r = meshCol[c];
  56804. this._color.g = meshCol[c + 1];
  56805. this._color.b = meshCol[c + 2];
  56806. this._color.a = meshCol[c + 3];
  56807. }
  56808. else {
  56809. this._color.r = 1;
  56810. this._color.g = 1;
  56811. this._color.b = 1;
  56812. this._color.a = 1;
  56813. }
  56814. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  56815. c += 4;
  56816. }
  56817. for (i = 0; i < meshInd.length; i++) {
  56818. indices.push(p + meshInd[i]);
  56819. }
  56820. if (this._pickable) {
  56821. var nbfaces = meshInd.length / 3;
  56822. for (i = 0; i < nbfaces; i++) {
  56823. this.pickedParticles.push({ idx: idx, faceId: i });
  56824. }
  56825. }
  56826. };
  56827. // returns a shape array from positions array
  56828. SolidParticleSystem.prototype._posToShape = function (positions) {
  56829. var shape = [];
  56830. for (var i = 0; i < positions.length; i += 3) {
  56831. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  56832. }
  56833. return shape;
  56834. };
  56835. // returns a shapeUV array from a Vector4 uvs
  56836. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  56837. var shapeUV = [];
  56838. if (uvs) {
  56839. for (var i = 0; i < uvs.length; i++)
  56840. shapeUV.push(uvs[i]);
  56841. }
  56842. return shapeUV;
  56843. };
  56844. // adds a new particle object in the particles array
  56845. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  56846. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  56847. };
  56848. /**
  56849. * Adds some particles to the SPS from the model shape. Returns the shape id.
  56850. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  56851. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  56852. * `nb` (positive integer) the number of particles to be created from this model
  56853. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  56854. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  56855. */
  56856. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  56857. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56858. var meshInd = mesh.getIndices();
  56859. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56860. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56861. var shape = this._posToShape(meshPos);
  56862. var shapeUV = this._uvsToShapeUV(meshUV);
  56863. var posfunc = options ? options.positionFunction : null;
  56864. var vtxfunc = options ? options.vertexFunction : null;
  56865. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  56866. // particles
  56867. var idx = this.nbParticles;
  56868. for (var i = 0; i < nb; i++) {
  56869. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  56870. if (this._updatable) {
  56871. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  56872. }
  56873. this._index += shape.length;
  56874. idx++;
  56875. }
  56876. this.nbParticles += nb;
  56877. this._shapeCounter++;
  56878. return this._shapeCounter - 1;
  56879. };
  56880. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  56881. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  56882. this._resetCopy();
  56883. if (particle._model._positionFunction) {
  56884. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  56885. }
  56886. if (this._copy.rotationQuaternion) {
  56887. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  56888. }
  56889. else {
  56890. this._yaw = this._copy.rotation.y;
  56891. this._pitch = this._copy.rotation.x;
  56892. this._roll = this._copy.rotation.z;
  56893. this._quaternionRotationYPR();
  56894. }
  56895. this._quaternionToRotationMatrix();
  56896. this._shape = particle._model._shape;
  56897. for (var pt = 0; pt < this._shape.length; pt++) {
  56898. this._vertex.x = this._shape[pt].x;
  56899. this._vertex.y = this._shape[pt].y;
  56900. this._vertex.z = this._shape[pt].z;
  56901. if (particle._model._vertexFunction) {
  56902. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  56903. }
  56904. this._vertex.x *= this._copy.scaling.x;
  56905. this._vertex.y *= this._copy.scaling.y;
  56906. this._vertex.z *= this._copy.scaling.z;
  56907. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  56908. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  56909. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  56910. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  56911. }
  56912. particle.position.x = 0;
  56913. particle.position.y = 0;
  56914. particle.position.z = 0;
  56915. particle.rotation.x = 0;
  56916. particle.rotation.y = 0;
  56917. particle.rotation.z = 0;
  56918. particle.rotationQuaternion = null;
  56919. particle.scaling.x = 1;
  56920. particle.scaling.y = 1;
  56921. particle.scaling.z = 1;
  56922. };
  56923. /**
  56924. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  56925. */
  56926. SolidParticleSystem.prototype.rebuildMesh = function () {
  56927. for (var p = 0; p < this.particles.length; p++) {
  56928. this._rebuildParticle(this.particles[p]);
  56929. }
  56930. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  56931. };
  56932. /**
  56933. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  56934. * This method calls `updateParticle()` for each particle of the SPS.
  56935. * For an animated SPS, it is usually called within the render loop.
  56936. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  56937. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  56938. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  56939. */
  56940. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  56941. if (start === void 0) { start = 0; }
  56942. if (end === void 0) { end = this.nbParticles - 1; }
  56943. if (update === void 0) { update = true; }
  56944. if (!this._updatable) {
  56945. return;
  56946. }
  56947. // custom beforeUpdate
  56948. this.beforeUpdateParticles(start, end, update);
  56949. this._cam_axisX.x = 1.0;
  56950. this._cam_axisX.y = 0.0;
  56951. this._cam_axisX.z = 0.0;
  56952. this._cam_axisY.x = 0.0;
  56953. this._cam_axisY.y = 1.0;
  56954. this._cam_axisY.z = 0.0;
  56955. this._cam_axisZ.x = 0.0;
  56956. this._cam_axisZ.y = 0.0;
  56957. this._cam_axisZ.z = 1.0;
  56958. // if the particles will always face the camera
  56959. if (this.billboard) {
  56960. // compute the camera position and un-rotate it by the current mesh rotation
  56961. this._yaw = this.mesh.rotation.y;
  56962. this._pitch = this.mesh.rotation.x;
  56963. this._roll = this.mesh.rotation.z;
  56964. this._quaternionRotationYPR();
  56965. this._quaternionToRotationMatrix();
  56966. this._rotMatrix.invertToRef(this._invertMatrix);
  56967. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  56968. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  56969. this._cam_axisZ.normalize();
  56970. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  56971. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  56972. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  56973. this._cam_axisY.normalize();
  56974. this._cam_axisX.normalize();
  56975. }
  56976. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  56977. var idx = 0;
  56978. var index = 0;
  56979. var colidx = 0;
  56980. var colorIndex = 0;
  56981. var uvidx = 0;
  56982. var uvIndex = 0;
  56983. var pt = 0;
  56984. if (this._computeBoundingBox) {
  56985. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  56986. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  56987. }
  56988. // particle loop
  56989. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  56990. for (var p = start; p <= end; p++) {
  56991. this._particle = this.particles[p];
  56992. this._shape = this._particle._model._shape;
  56993. this._shapeUV = this._particle._model._shapeUV;
  56994. // call to custom user function to update the particle properties
  56995. this.updateParticle(this._particle);
  56996. if (this._particle.isVisible) {
  56997. // particle rotation matrix
  56998. if (this.billboard) {
  56999. this._particle.rotation.x = 0.0;
  57000. this._particle.rotation.y = 0.0;
  57001. }
  57002. if (this._computeParticleRotation || this.billboard) {
  57003. if (this._particle.rotationQuaternion) {
  57004. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57005. }
  57006. else {
  57007. this._yaw = this._particle.rotation.y;
  57008. this._pitch = this._particle.rotation.x;
  57009. this._roll = this._particle.rotation.z;
  57010. this._quaternionRotationYPR();
  57011. }
  57012. this._quaternionToRotationMatrix();
  57013. }
  57014. // particle vertex loop
  57015. for (pt = 0; pt < this._shape.length; pt++) {
  57016. idx = index + pt * 3;
  57017. colidx = colorIndex + pt * 4;
  57018. uvidx = uvIndex + pt * 2;
  57019. this._vertex.x = this._shape[pt].x;
  57020. this._vertex.y = this._shape[pt].y;
  57021. this._vertex.z = this._shape[pt].z;
  57022. if (this._computeParticleVertex) {
  57023. this.updateParticleVertex(this._particle, this._vertex, pt);
  57024. }
  57025. // positions
  57026. this._vertex.x *= this._particle.scaling.x;
  57027. this._vertex.y *= this._particle.scaling.y;
  57028. this._vertex.z *= this._particle.scaling.z;
  57029. 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];
  57030. 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;
  57031. 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;
  57032. 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;
  57033. 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;
  57034. 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;
  57035. 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;
  57036. if (this._computeBoundingBox) {
  57037. if (this._positions32[idx] < this._minimum.x) {
  57038. this._minimum.x = this._positions32[idx];
  57039. }
  57040. if (this._positions32[idx] > this._maximum.x) {
  57041. this._maximum.x = this._positions32[idx];
  57042. }
  57043. if (this._positions32[idx + 1] < this._minimum.y) {
  57044. this._minimum.y = this._positions32[idx + 1];
  57045. }
  57046. if (this._positions32[idx + 1] > this._maximum.y) {
  57047. this._maximum.y = this._positions32[idx + 1];
  57048. }
  57049. if (this._positions32[idx + 2] < this._minimum.z) {
  57050. this._minimum.z = this._positions32[idx + 2];
  57051. }
  57052. if (this._positions32[idx + 2] > this._maximum.z) {
  57053. this._maximum.z = this._positions32[idx + 2];
  57054. }
  57055. }
  57056. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  57057. if (!this._computeParticleVertex) {
  57058. this._normal.x = this._fixedNormal32[idx];
  57059. this._normal.y = this._fixedNormal32[idx + 1];
  57060. this._normal.z = this._fixedNormal32[idx + 2];
  57061. 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];
  57062. 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;
  57063. 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;
  57064. 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;
  57065. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  57066. 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;
  57067. 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;
  57068. }
  57069. if (this._computeParticleColor) {
  57070. this._colors32[colidx] = this._particle.color.r;
  57071. this._colors32[colidx + 1] = this._particle.color.g;
  57072. this._colors32[colidx + 2] = this._particle.color.b;
  57073. this._colors32[colidx + 3] = this._particle.color.a;
  57074. }
  57075. if (this._computeParticleTexture) {
  57076. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57077. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57078. }
  57079. }
  57080. }
  57081. else {
  57082. for (pt = 0; pt < this._shape.length; pt++) {
  57083. idx = index + pt * 3;
  57084. colidx = colorIndex + pt * 4;
  57085. uvidx = uvIndex + pt * 2;
  57086. this._positions32[idx] = this._camera.position.x;
  57087. this._positions32[idx + 1] = this._camera.position.y;
  57088. this._positions32[idx + 2] = this._camera.position.z;
  57089. this._normals32[idx] = 0.0;
  57090. this._normals32[idx + 1] = 0.0;
  57091. this._normals32[idx + 2] = 0.0;
  57092. if (this._computeParticleColor) {
  57093. this._colors32[colidx] = this._particle.color.r;
  57094. this._colors32[colidx + 1] = this._particle.color.g;
  57095. this._colors32[colidx + 2] = this._particle.color.b;
  57096. this._colors32[colidx + 3] = this._particle.color.a;
  57097. }
  57098. if (this._computeParticleTexture) {
  57099. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57100. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57101. }
  57102. }
  57103. }
  57104. // increment indexes for the next particle
  57105. index = idx + 3;
  57106. colorIndex = colidx + 4;
  57107. uvIndex = uvidx + 2;
  57108. }
  57109. // if the VBO must be updated
  57110. if (update) {
  57111. if (this._computeParticleColor) {
  57112. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  57113. }
  57114. if (this._computeParticleTexture) {
  57115. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  57116. }
  57117. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57118. if (!this.mesh.areNormalsFrozen) {
  57119. if (this._computeParticleVertex) {
  57120. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  57121. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  57122. for (var i = 0; i < this._normals32.length; i++) {
  57123. this._fixedNormal32[i] = this._normals32[i];
  57124. }
  57125. }
  57126. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  57127. }
  57128. }
  57129. if (this._computeBoundingBox) {
  57130. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  57131. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  57132. }
  57133. this.afterUpdateParticles(start, end, update);
  57134. };
  57135. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  57136. this._halfroll = this._roll * 0.5;
  57137. this._halfpitch = this._pitch * 0.5;
  57138. this._halfyaw = this._yaw * 0.5;
  57139. this._sinRoll = Math.sin(this._halfroll);
  57140. this._cosRoll = Math.cos(this._halfroll);
  57141. this._sinPitch = Math.sin(this._halfpitch);
  57142. this._cosPitch = Math.cos(this._halfpitch);
  57143. this._sinYaw = Math.sin(this._halfyaw);
  57144. this._cosYaw = Math.cos(this._halfyaw);
  57145. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  57146. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  57147. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  57148. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  57149. };
  57150. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  57151. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  57152. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  57153. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  57154. this._rotMatrix.m[3] = 0;
  57155. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  57156. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  57157. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  57158. this._rotMatrix.m[7] = 0;
  57159. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  57160. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  57161. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  57162. this._rotMatrix.m[11] = 0;
  57163. this._rotMatrix.m[12] = 0;
  57164. this._rotMatrix.m[13] = 0;
  57165. this._rotMatrix.m[14] = 0;
  57166. this._rotMatrix.m[15] = 1.0;
  57167. };
  57168. /**
  57169. * Disposes the SPS
  57170. */
  57171. SolidParticleSystem.prototype.dispose = function () {
  57172. this.mesh.dispose();
  57173. this.vars = null;
  57174. // drop references to internal big arrays for the GC
  57175. this._positions = null;
  57176. this._indices = null;
  57177. this._normals = null;
  57178. this._uvs = null;
  57179. this._colors = null;
  57180. this._positions32 = null;
  57181. this._normals32 = null;
  57182. this._fixedNormal32 = null;
  57183. this._uvs32 = null;
  57184. this._colors32 = null;
  57185. this.pickedParticles = null;
  57186. };
  57187. /**
  57188. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  57189. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57190. */
  57191. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  57192. if (!this._isVisibilityBoxLocked) {
  57193. this.mesh.refreshBoundingInfo();
  57194. }
  57195. };
  57196. /**
  57197. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  57198. * @param size the size (float) of the visibility box
  57199. * note : this doesn't lock the SPS mesh bounding box.
  57200. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57201. */
  57202. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  57203. var vis = size / 2;
  57204. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  57205. };
  57206. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  57207. // getter and setter
  57208. get: function () {
  57209. return this._alwaysVisible;
  57210. },
  57211. /**
  57212. * Sets the SPS as always visible or not
  57213. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57214. */
  57215. set: function (val) {
  57216. this._alwaysVisible = val;
  57217. this.mesh.alwaysSelectAsActiveMesh = val;
  57218. },
  57219. enumerable: true,
  57220. configurable: true
  57221. });
  57222. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  57223. get: function () {
  57224. return this._isVisibilityBoxLocked;
  57225. },
  57226. /**
  57227. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  57228. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57229. */
  57230. set: function (val) {
  57231. this._isVisibilityBoxLocked = val;
  57232. this.mesh.getBoundingInfo().isLocked = val;
  57233. },
  57234. enumerable: true,
  57235. configurable: true
  57236. });
  57237. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  57238. // getters
  57239. get: function () {
  57240. return this._computeParticleRotation;
  57241. },
  57242. // Optimizer setters
  57243. /**
  57244. * Tells to `setParticles()` to compute the particle rotations or not.
  57245. * Default value : true. The SPS is faster when it's set to false.
  57246. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  57247. */
  57248. set: function (val) {
  57249. this._computeParticleRotation = val;
  57250. },
  57251. enumerable: true,
  57252. configurable: true
  57253. });
  57254. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  57255. get: function () {
  57256. return this._computeParticleColor;
  57257. },
  57258. /**
  57259. * Tells to `setParticles()` to compute the particle colors or not.
  57260. * Default value : true. The SPS is faster when it's set to false.
  57261. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  57262. */
  57263. set: function (val) {
  57264. this._computeParticleColor = val;
  57265. },
  57266. enumerable: true,
  57267. configurable: true
  57268. });
  57269. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  57270. get: function () {
  57271. return this._computeParticleTexture;
  57272. },
  57273. /**
  57274. * Tells to `setParticles()` to compute the particle textures or not.
  57275. * Default value : true. The SPS is faster when it's set to false.
  57276. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  57277. */
  57278. set: function (val) {
  57279. this._computeParticleTexture = val;
  57280. },
  57281. enumerable: true,
  57282. configurable: true
  57283. });
  57284. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  57285. get: function () {
  57286. return this._computeParticleVertex;
  57287. },
  57288. /**
  57289. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  57290. * Default value : false. The SPS is faster when it's set to false.
  57291. * Note : the particle custom vertex positions aren't stored values.
  57292. */
  57293. set: function (val) {
  57294. this._computeParticleVertex = val;
  57295. },
  57296. enumerable: true,
  57297. configurable: true
  57298. });
  57299. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  57300. get: function () {
  57301. return this._computeBoundingBox;
  57302. },
  57303. /**
  57304. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  57305. */
  57306. set: function (val) {
  57307. this._computeBoundingBox = val;
  57308. },
  57309. enumerable: true,
  57310. configurable: true
  57311. });
  57312. // =======================================================================
  57313. // Particle behavior logic
  57314. // these following methods may be overwritten by the user to fit his needs
  57315. /**
  57316. * This function does nothing. It may be overwritten to set all the particle first values.
  57317. * The SPS doesn't call this function, you may have to call it by your own.
  57318. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57319. */
  57320. SolidParticleSystem.prototype.initParticles = function () {
  57321. };
  57322. /**
  57323. * This function does nothing. It may be overwritten to recycle a particle.
  57324. * The SPS doesn't call this function, you may have to call it by your own.
  57325. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57326. */
  57327. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  57328. return particle;
  57329. };
  57330. /**
  57331. * Updates a particle : this function should be overwritten by the user.
  57332. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  57333. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57334. * ex : just set a particle position or velocity and recycle conditions
  57335. */
  57336. SolidParticleSystem.prototype.updateParticle = function (particle) {
  57337. return particle;
  57338. };
  57339. /**
  57340. * Updates a vertex of a particle : it can be overwritten by the user.
  57341. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  57342. * @param particle the current particle
  57343. * @param vertex the current index of the current particle
  57344. * @param pt the index of the current vertex in the particle shape
  57345. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  57346. * ex : just set a vertex particle position
  57347. */
  57348. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  57349. return vertex;
  57350. };
  57351. /**
  57352. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  57353. * This does nothing and may be overwritten by the user.
  57354. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57355. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57356. * @param update the boolean update value actually passed to setParticles()
  57357. */
  57358. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  57359. };
  57360. /**
  57361. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  57362. * This will be passed three parameters.
  57363. * This does nothing and may be overwritten by the user.
  57364. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57365. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57366. * @param update the boolean update value actually passed to setParticles()
  57367. */
  57368. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  57369. };
  57370. return SolidParticleSystem;
  57371. })();
  57372. BABYLON.SolidParticleSystem = SolidParticleSystem;
  57373. })(BABYLON || (BABYLON = {}));
  57374. var BABYLON;
  57375. (function (BABYLON) {
  57376. var Internals;
  57377. (function (Internals) {
  57378. var FileFaceOrientation = (function () {
  57379. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  57380. this.name = name;
  57381. this.worldAxisForNormal = worldAxisForNormal;
  57382. this.worldAxisForFileX = worldAxisForFileX;
  57383. this.worldAxisForFileY = worldAxisForFileY;
  57384. }
  57385. return FileFaceOrientation;
  57386. })();
  57387. ;
  57388. /**
  57389. * Helper class dealing with the extraction of spherical polynomial dataArray
  57390. * from a cube map.
  57391. */
  57392. var CubeMapToSphericalPolynomialTools = (function () {
  57393. function CubeMapToSphericalPolynomialTools() {
  57394. }
  57395. /**
  57396. * Converts a cubemap to the according Spherical Polynomial data.
  57397. * This extracts the first 3 orders only as they are the only one used in the lighting.
  57398. *
  57399. * @param cubeInfo The Cube map to extract the information from.
  57400. * @return The Spherical Polynomial data.
  57401. */
  57402. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  57403. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  57404. var totalSolidAngle = 0.0;
  57405. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  57406. var du = 2.0 / cubeInfo.size;
  57407. var dv = du;
  57408. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  57409. var minUV = du * 0.5 - 1.0;
  57410. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57411. var fileFace = this.FileFaces[faceIndex];
  57412. var dataArray = cubeInfo[fileFace.name];
  57413. var v = minUV;
  57414. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  57415. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  57416. // Because SP is still linear, so summation is fine in that basis.
  57417. for (var y = 0; y < cubeInfo.size; y++) {
  57418. var u = minUV;
  57419. for (var x = 0; x < cubeInfo.size; x++) {
  57420. // World direction (not normalised)
  57421. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  57422. worldDirection.normalize();
  57423. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  57424. if (1) {
  57425. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  57426. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  57427. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  57428. var color = new BABYLON.Color3(r, g, b);
  57429. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  57430. }
  57431. else {
  57432. if (faceIndex == 0) {
  57433. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  57434. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  57435. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  57436. }
  57437. else if (faceIndex == 1) {
  57438. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  57439. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  57440. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  57441. }
  57442. else if (faceIndex == 2) {
  57443. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  57444. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  57445. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  57446. }
  57447. else if (faceIndex == 3) {
  57448. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  57449. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  57450. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  57451. }
  57452. else if (faceIndex == 4) {
  57453. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  57454. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  57455. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  57456. }
  57457. else if (faceIndex == 5) {
  57458. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  57459. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  57460. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  57461. }
  57462. 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]);
  57463. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  57464. }
  57465. totalSolidAngle += deltaSolidAngle;
  57466. u += du;
  57467. }
  57468. v += dv;
  57469. }
  57470. }
  57471. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  57472. var correction = correctSolidAngle / totalSolidAngle;
  57473. sphericalHarmonics.scale(correction);
  57474. // Additionally scale by pi -- audit needed
  57475. sphericalHarmonics.scale(1.0 / Math.PI);
  57476. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  57477. };
  57478. CubeMapToSphericalPolynomialTools.FileFaces = [
  57479. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  57480. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  57481. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  57482. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  57483. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  57484. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  57485. ];
  57486. return CubeMapToSphericalPolynomialTools;
  57487. })();
  57488. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  57489. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57490. })(BABYLON || (BABYLON = {}));
  57491. var BABYLON;
  57492. (function (BABYLON) {
  57493. var Internals;
  57494. (function (Internals) {
  57495. /**
  57496. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  57497. */
  57498. var PanoramaToCubeMapTools = (function () {
  57499. function PanoramaToCubeMapTools() {
  57500. }
  57501. /**
  57502. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  57503. *
  57504. * @param float32Array The source data.
  57505. * @param inputWidth The width of the input panorama.
  57506. * @param inputhHeight The height of the input panorama.
  57507. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  57508. * @return The cubemap data
  57509. */
  57510. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  57511. if (!float32Array) {
  57512. throw "ConvertPanoramaToCubemap: input cannot be null";
  57513. }
  57514. if (float32Array.length != inputWidth * inputHeight * 3) {
  57515. throw "ConvertPanoramaToCubemap: input size is wrong";
  57516. }
  57517. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  57518. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  57519. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  57520. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  57521. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  57522. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  57523. return {
  57524. front: textureFront,
  57525. back: textureBack,
  57526. left: textureLeft,
  57527. right: textureRight,
  57528. up: textureUp,
  57529. down: textureDown,
  57530. size: size
  57531. };
  57532. };
  57533. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  57534. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  57535. var textureArray = new Float32Array(buffer);
  57536. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  57537. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  57538. var dy = 1 / texSize;
  57539. var fy = 0;
  57540. for (var y = 0; y < texSize; y++) {
  57541. var xv1 = faceData[0];
  57542. var xv2 = faceData[2];
  57543. for (var x = 0; x < texSize; x++) {
  57544. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  57545. v.normalize();
  57546. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  57547. // 3 channels per pixels
  57548. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  57549. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  57550. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  57551. xv1 = xv1.add(rotDX1);
  57552. xv2 = xv2.add(rotDX2);
  57553. }
  57554. fy += dy;
  57555. }
  57556. return textureArray;
  57557. };
  57558. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  57559. var theta = Math.atan2(vDir.z, vDir.x);
  57560. var phi = Math.acos(vDir.y);
  57561. while (theta < -Math.PI)
  57562. theta += 2 * Math.PI;
  57563. while (theta > Math.PI)
  57564. theta -= 2 * Math.PI;
  57565. var dx = theta / Math.PI;
  57566. var dy = phi / Math.PI;
  57567. // recenter.
  57568. dx = dx * 0.5 + 0.5;
  57569. var px = Math.round(dx * inputWidth);
  57570. if (px < 0)
  57571. px = 0;
  57572. else if (px >= inputWidth)
  57573. px = inputWidth - 1;
  57574. var py = Math.round(dy * inputHeight);
  57575. if (py < 0)
  57576. py = 0;
  57577. else if (py >= inputHeight)
  57578. py = inputHeight - 1;
  57579. var inputY = (inputHeight - py - 1);
  57580. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  57581. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  57582. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  57583. return {
  57584. r: r,
  57585. g: g,
  57586. b: b
  57587. };
  57588. };
  57589. PanoramaToCubeMapTools.FACE_FRONT = [
  57590. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  57591. new BABYLON.Vector3(1.0, -1.0, -1.0),
  57592. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  57593. new BABYLON.Vector3(1.0, 1.0, -1.0)
  57594. ];
  57595. PanoramaToCubeMapTools.FACE_BACK = [
  57596. new BABYLON.Vector3(1.0, -1.0, 1.0),
  57597. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57598. new BABYLON.Vector3(1.0, 1.0, 1.0),
  57599. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  57600. ];
  57601. PanoramaToCubeMapTools.FACE_RIGHT = [
  57602. new BABYLON.Vector3(1.0, -1.0, -1.0),
  57603. new BABYLON.Vector3(1.0, -1.0, 1.0),
  57604. new BABYLON.Vector3(1.0, 1.0, -1.0),
  57605. new BABYLON.Vector3(1.0, 1.0, 1.0)
  57606. ];
  57607. PanoramaToCubeMapTools.FACE_LEFT = [
  57608. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57609. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  57610. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  57611. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  57612. ];
  57613. PanoramaToCubeMapTools.FACE_DOWN = [
  57614. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  57615. new BABYLON.Vector3(1.0, 1.0, -1.0),
  57616. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  57617. new BABYLON.Vector3(1.0, 1.0, 1.0)
  57618. ];
  57619. PanoramaToCubeMapTools.FACE_UP = [
  57620. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57621. new BABYLON.Vector3(1.0, -1.0, 1.0),
  57622. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  57623. new BABYLON.Vector3(1.0, -1.0, -1.0)
  57624. ];
  57625. return PanoramaToCubeMapTools;
  57626. })();
  57627. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  57628. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57629. })(BABYLON || (BABYLON = {}));
  57630. var BABYLON;
  57631. (function (BABYLON) {
  57632. var Internals;
  57633. (function (Internals) {
  57634. ;
  57635. /**
  57636. * This groups tools to convert HDR texture to native colors array.
  57637. */
  57638. var HDRTools = (function () {
  57639. function HDRTools() {
  57640. }
  57641. HDRTools.Ldexp = function (mantissa, exponent) {
  57642. if (exponent > 1023) {
  57643. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  57644. }
  57645. if (exponent < -1074) {
  57646. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  57647. }
  57648. return mantissa * Math.pow(2, exponent);
  57649. };
  57650. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  57651. if (exponent > 0) {
  57652. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  57653. float32array[index + 0] = red * exponent;
  57654. float32array[index + 1] = green * exponent;
  57655. float32array[index + 2] = blue * exponent;
  57656. }
  57657. else {
  57658. float32array[index + 0] = 0;
  57659. float32array[index + 1] = 0;
  57660. float32array[index + 2] = 0;
  57661. }
  57662. };
  57663. HDRTools.readStringLine = function (uint8array, startIndex) {
  57664. var line = "";
  57665. var character = "";
  57666. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  57667. character = String.fromCharCode(uint8array[i]);
  57668. if (character == "\n") {
  57669. break;
  57670. }
  57671. line += character;
  57672. }
  57673. return line;
  57674. };
  57675. /**
  57676. * Reads header information from an RGBE texture stored in a native array.
  57677. * More information on this format are available here:
  57678. * https://en.wikipedia.org/wiki/RGBE_image_format
  57679. *
  57680. * @param uint8array The binary file stored in native array.
  57681. * @return The header information.
  57682. */
  57683. HDRTools.RGBE_ReadHeader = function (uint8array) {
  57684. var height = 0;
  57685. var width = 0;
  57686. var line = this.readStringLine(uint8array, 0);
  57687. if (line[0] != '#' || line[1] != '?') {
  57688. throw "Bad HDR Format.";
  57689. }
  57690. var endOfHeader = false;
  57691. var findFormat = false;
  57692. var lineIndex = 0;
  57693. do {
  57694. lineIndex += (line.length + 1);
  57695. line = this.readStringLine(uint8array, lineIndex);
  57696. if (line == "FORMAT=32-bit_rle_rgbe") {
  57697. findFormat = true;
  57698. }
  57699. else if (line.length == 0) {
  57700. endOfHeader = true;
  57701. }
  57702. } while (!endOfHeader);
  57703. if (!findFormat) {
  57704. throw "HDR Bad header format, unsupported FORMAT";
  57705. }
  57706. lineIndex += (line.length + 1);
  57707. line = this.readStringLine(uint8array, lineIndex);
  57708. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  57709. var match = sizeRegexp.exec(line);
  57710. // TODO. Support +Y and -X if needed.
  57711. if (match.length < 3) {
  57712. throw "HDR Bad header format, no size";
  57713. }
  57714. width = parseInt(match[2]);
  57715. height = parseInt(match[1]);
  57716. if (width < 8 || width > 0x7fff) {
  57717. throw "HDR Bad header format, unsupported size";
  57718. }
  57719. lineIndex += (line.length + 1);
  57720. return {
  57721. height: height,
  57722. width: width,
  57723. dataPosition: lineIndex
  57724. };
  57725. };
  57726. /**
  57727. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  57728. * This RGBE texture needs to store the information as a panorama.
  57729. *
  57730. * More information on this format are available here:
  57731. * https://en.wikipedia.org/wiki/RGBE_image_format
  57732. *
  57733. * @param buffer The binary file stored in an array buffer.
  57734. * @param size The expected size of the extracted cubemap.
  57735. * @return The Cube Map information.
  57736. */
  57737. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  57738. var uint8array = new Uint8Array(buffer);
  57739. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  57740. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  57741. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  57742. return cubeMapData;
  57743. };
  57744. /**
  57745. * Returns the pixels data extracted from an RGBE texture.
  57746. * This pixels will be stored left to right up to down in the R G B order in one array.
  57747. *
  57748. * More information on this format are available here:
  57749. * https://en.wikipedia.org/wiki/RGBE_image_format
  57750. *
  57751. * @param uint8array The binary file stored in an array buffer.
  57752. * @param hdrInfo The header information of the file.
  57753. * @return The pixels data in RGB right to left up to down order.
  57754. */
  57755. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  57756. // Keep for multi format supports.
  57757. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  57758. };
  57759. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  57760. var num_scanlines = hdrInfo.height;
  57761. var scanline_width = hdrInfo.width;
  57762. var a, b, c, d, count;
  57763. var dataIndex = hdrInfo.dataPosition;
  57764. var index = 0, endIndex = 0, i = 0;
  57765. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  57766. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  57767. // 3 channels of 4 bytes per pixel in float.
  57768. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  57769. var resultArray = new Float32Array(resultBuffer);
  57770. // read in each successive scanline
  57771. while (num_scanlines > 0) {
  57772. a = uint8array[dataIndex++];
  57773. b = uint8array[dataIndex++];
  57774. c = uint8array[dataIndex++];
  57775. d = uint8array[dataIndex++];
  57776. if (a != 2 || b != 2 || (c & 0x80)) {
  57777. // this file is not run length encoded
  57778. throw "HDR Bad header format, not RLE";
  57779. }
  57780. if (((c << 8) | d) != scanline_width) {
  57781. throw "HDR Bad header format, wrong scan line width";
  57782. }
  57783. index = 0;
  57784. // read each of the four channels for the scanline into the buffer
  57785. for (i = 0; i < 4; i++) {
  57786. endIndex = (i + 1) * scanline_width;
  57787. while (index < endIndex) {
  57788. a = uint8array[dataIndex++];
  57789. b = uint8array[dataIndex++];
  57790. if (a > 128) {
  57791. // a run of the same value
  57792. count = a - 128;
  57793. if ((count == 0) || (count > endIndex - index)) {
  57794. throw "HDR Bad Format, bad scanline data (run)";
  57795. }
  57796. while (count-- > 0) {
  57797. scanLineArray[index++] = b;
  57798. }
  57799. }
  57800. else {
  57801. // a non-run
  57802. count = a;
  57803. if ((count == 0) || (count > endIndex - index)) {
  57804. throw "HDR Bad Format, bad scanline data (non-run)";
  57805. }
  57806. scanLineArray[index++] = b;
  57807. if (--count > 0) {
  57808. for (var j = 0; j < count; j++) {
  57809. scanLineArray[index++] = uint8array[dataIndex++];
  57810. }
  57811. }
  57812. }
  57813. }
  57814. }
  57815. // now convert data from buffer into floats
  57816. for (i = 0; i < scanline_width; i++) {
  57817. a = scanLineArray[i];
  57818. b = scanLineArray[i + scanline_width];
  57819. c = scanLineArray[i + 2 * scanline_width];
  57820. d = scanLineArray[i + 3 * scanline_width];
  57821. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  57822. }
  57823. num_scanlines--;
  57824. }
  57825. return resultArray;
  57826. };
  57827. return HDRTools;
  57828. })();
  57829. Internals.HDRTools = HDRTools;
  57830. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57831. })(BABYLON || (BABYLON = {}));
  57832. //_______________________________________________________________
  57833. // Extracted from CubeMapGen:
  57834. // https://code.google.com/archive/p/cubemapgen/
  57835. //
  57836. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  57837. //_______________________________________________________________
  57838. var BABYLON;
  57839. (function (BABYLON) {
  57840. var Internals;
  57841. (function (Internals) {
  57842. /**
  57843. * The bounding box information used during the conversion process.
  57844. */
  57845. var CMGBoundinBox = (function () {
  57846. function CMGBoundinBox() {
  57847. this.min = new BABYLON.Vector3(0, 0, 0);
  57848. this.max = new BABYLON.Vector3(0, 0, 0);
  57849. this.clear();
  57850. }
  57851. CMGBoundinBox.prototype.clear = function () {
  57852. this.min.x = CMGBoundinBox.MAX;
  57853. this.min.y = CMGBoundinBox.MAX;
  57854. this.min.z = CMGBoundinBox.MAX;
  57855. this.max.x = CMGBoundinBox.MIN;
  57856. this.max.y = CMGBoundinBox.MIN;
  57857. this.max.z = CMGBoundinBox.MIN;
  57858. };
  57859. CMGBoundinBox.prototype.augment = function (x, y, z) {
  57860. this.min.x = Math.min(this.min.x, x);
  57861. this.min.y = Math.min(this.min.y, y);
  57862. this.min.z = Math.min(this.min.z, z);
  57863. this.max.x = Math.max(this.max.x, x);
  57864. this.max.y = Math.max(this.max.y, y);
  57865. this.max.z = Math.max(this.max.z, z);
  57866. };
  57867. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  57868. this.min.x = Math.max(this.min.x, x);
  57869. this.min.y = Math.max(this.min.y, y);
  57870. this.min.z = Math.max(this.min.z, z);
  57871. };
  57872. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  57873. this.max.x = Math.min(this.max.x, x);
  57874. this.max.y = Math.min(this.max.y, y);
  57875. this.max.z = Math.min(this.max.z, z);
  57876. };
  57877. CMGBoundinBox.prototype.empty = function () {
  57878. if ((this.min.x > this.max.y) ||
  57879. (this.min.y > this.max.y) ||
  57880. (this.min.z > this.max.y)) {
  57881. return true;
  57882. }
  57883. else {
  57884. return false;
  57885. }
  57886. };
  57887. CMGBoundinBox.MAX = Number.MAX_VALUE;
  57888. CMGBoundinBox.MIN = Number.MIN_VALUE;
  57889. return CMGBoundinBox;
  57890. })();
  57891. /**
  57892. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  57893. * required by the glossinees of a material.
  57894. *
  57895. * This only supports the cosine drop power as well as Warp fixup generation method.
  57896. *
  57897. * This is using the process from CubeMapGen described here:
  57898. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  57899. */
  57900. var PMREMGenerator = (function () {
  57901. /**
  57902. * Constructor of the generator.
  57903. *
  57904. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  57905. * @param inputSize The size of the cubemap faces
  57906. * @param outputSize The size of the output cubemap faces
  57907. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  57908. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  57909. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  57910. * @param specularPower The max specular level of the desired cubemap
  57911. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  57912. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  57913. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  57914. */
  57915. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  57916. this.input = input;
  57917. this.inputSize = inputSize;
  57918. this.outputSize = outputSize;
  57919. this.maxNumMipLevels = maxNumMipLevels;
  57920. this.numChannels = numChannels;
  57921. this.isFloat = isFloat;
  57922. this.specularPower = specularPower;
  57923. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  57924. this.excludeBase = excludeBase;
  57925. this.fixup = fixup;
  57926. this._outputSurface = [];
  57927. this._numMipLevels = 0;
  57928. }
  57929. /**
  57930. * Launches the filter process and return the result.
  57931. *
  57932. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  57933. */
  57934. PMREMGenerator.prototype.filterCubeMap = function () {
  57935. // Init cubemap processor
  57936. this.init();
  57937. // Filters the cubemap
  57938. this.filterCubeMapMipChain();
  57939. // Returns the filtered mips.
  57940. return this._outputSurface;
  57941. };
  57942. PMREMGenerator.prototype.init = function () {
  57943. var i;
  57944. var j;
  57945. var mipLevelSize;
  57946. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  57947. if (this.maxNumMipLevels == 0) {
  57948. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  57949. }
  57950. //first miplevel size
  57951. mipLevelSize = this.outputSize;
  57952. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  57953. for (j = 0; j < this.maxNumMipLevels; j++) {
  57954. this._outputSurface.length++;
  57955. this._outputSurface[j] = [];
  57956. //Iterate over faces for output images
  57957. for (i = 0; i < 6; i++) {
  57958. this._outputSurface[j].length++;
  57959. // Initializes a new array for the output.
  57960. if (this.isFloat) {
  57961. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  57962. }
  57963. else {
  57964. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  57965. }
  57966. }
  57967. //next mip level is half size
  57968. mipLevelSize >>= 1;
  57969. this._numMipLevels++;
  57970. //terminate if mip chain becomes too small
  57971. if (mipLevelSize == 0) {
  57972. this.maxNumMipLevels = j;
  57973. return;
  57974. }
  57975. }
  57976. };
  57977. //--------------------------------------------------------------------------------------
  57978. //Cube map filtering and mip chain generation.
  57979. // the cube map filtereing is specified using a number of parameters:
  57980. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  57981. // indicates the region of the hemisphere to filter over for each tap.
  57982. //
  57983. // Note that the top mip level is also a filtered version of the original input images
  57984. // as well in order to create mip chains for diffuse environment illumination.
  57985. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  57986. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  57987. //
  57988. // Then the mip angle used to genreate the next level of the mip chain from the first level
  57989. // is a_InitialMipAngle
  57990. //
  57991. // The angle for the subsequent levels of the mip chain are specified by their parents
  57992. // filtering angle and a per-level scale and bias
  57993. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  57994. //
  57995. //--------------------------------------------------------------------------------------
  57996. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  57997. // First, take count of the lighting model to modify SpecularPower
  57998. // 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;
  57999. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  58000. //Cone angle start (for generating subsequent mip levels)
  58001. var currentSpecularPower = this.specularPower;
  58002. //Build filter lookup tables based on the source miplevel size
  58003. this.precomputeFilterLookupTables(this.inputSize);
  58004. // Note that we need to filter the first level before generating mipmap
  58005. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  58006. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  58007. // TODO : Write a function to copy and scale the base mipmap in output
  58008. // I am just lazy here and just put a high specular power value, and do some if.
  58009. if (this.excludeBase && (levelIndex == 0)) {
  58010. // 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).
  58011. currentSpecularPower = 100000.0;
  58012. }
  58013. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  58014. var srcCubeImage = this.input;
  58015. var dstCubeImage = this._outputSurface[levelIndex];
  58016. var dstSize = this.outputSize >> levelIndex;
  58017. // Compute required angle.
  58018. var angle = this.getBaseFilterAngle(currentSpecularPower);
  58019. // filter cube surfaces
  58020. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  58021. // fix seams
  58022. if (this.fixup) {
  58023. this.fixupCubeEdges(dstCubeImage, dstSize);
  58024. }
  58025. // Decrease the specular power to generate the mipmap chain
  58026. // TODO : Use another method for Exclude (see first comment at start of the function
  58027. if (this.excludeBase && (levelIndex == 0)) {
  58028. currentSpecularPower = this.specularPower;
  58029. }
  58030. currentSpecularPower *= this.cosinePowerDropPerMip;
  58031. }
  58032. };
  58033. //--------------------------------------------------------------------------------------
  58034. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  58035. // It allow to optimize the texel to access base on the specular power.
  58036. //--------------------------------------------------------------------------------------
  58037. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  58038. // We want to find the alpha such that:
  58039. // cos(alpha)^cosinePower = epsilon
  58040. // That's: acos(epsilon^(1/cosinePower))
  58041. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  58042. var angle = 180.0;
  58043. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  58044. angle *= 180.0 / Math.PI; // Convert to degree
  58045. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  58046. return angle;
  58047. };
  58048. //--------------------------------------------------------------------------------------
  58049. //Builds the following lookup tables prior to filtering:
  58050. // -normalizer cube map
  58051. // -tap weight lookup table
  58052. //
  58053. //--------------------------------------------------------------------------------------
  58054. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  58055. var srcTexelAngle;
  58056. var iCubeFace;
  58057. //clear pre-existing normalizer cube map
  58058. this._normCubeMap = [];
  58059. //Normalized vectors per cubeface and per-texel solid angle
  58060. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  58061. };
  58062. //--------------------------------------------------------------------------------------
  58063. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  58064. //
  58065. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  58066. //
  58067. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  58068. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  58069. // below
  58070. //--------------------------------------------------------------------------------------
  58071. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  58072. var iCubeFace;
  58073. var u;
  58074. var v;
  58075. //iterate over cube faces
  58076. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  58077. //First three channels for norm cube, and last channel for solid angle
  58078. this._normCubeMap.push(new Float32Array(size * size * 4));
  58079. //fast texture walk, build normalizer cube map
  58080. var facesData = this.input[iCubeFace];
  58081. for (v = 0; v < size; v++) {
  58082. for (u = 0; u < size; u++) {
  58083. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  58084. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  58085. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  58086. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  58087. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  58088. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  58089. }
  58090. }
  58091. }
  58092. };
  58093. //--------------------------------------------------------------------------------------
  58094. // Convert cubemap face texel coordinates and face idx to 3D vector
  58095. // note the U and V coords are integer coords and range from 0 to size-1
  58096. // this routine can be used to generate a normalizer cube map
  58097. //--------------------------------------------------------------------------------------
  58098. // SL BEGIN
  58099. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  58100. var nvcU;
  58101. var nvcV;
  58102. var tempVec;
  58103. // Change from original AMD code
  58104. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  58105. // + 0.5f is for texel center addressing
  58106. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  58107. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  58108. // warp fixup
  58109. if (fixup && size > 1) {
  58110. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  58111. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  58112. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  58113. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  58114. }
  58115. // Get current vector
  58116. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  58117. // U contribution
  58118. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  58119. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  58120. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  58121. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  58122. // V contribution and Sum
  58123. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  58124. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  58125. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  58126. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  58127. //add face axis
  58128. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  58129. PMREMGenerator._vectorTemp.x += faceAxis[0];
  58130. PMREMGenerator._vectorTemp.y += faceAxis[1];
  58131. PMREMGenerator._vectorTemp.z += faceAxis[2];
  58132. //normalize vector
  58133. PMREMGenerator._vectorTemp.normalize();
  58134. return PMREMGenerator._vectorTemp;
  58135. };
  58136. //--------------------------------------------------------------------------------------
  58137. // Convert 3D vector to cubemap face texel coordinates and face idx
  58138. // note the U and V coords are integer coords and range from 0 to size-1
  58139. // this routine can be used to generate a normalizer cube map
  58140. //
  58141. // returns face IDX and texel coords
  58142. //--------------------------------------------------------------------------------------
  58143. // SL BEGIN
  58144. /*
  58145. Mapping Texture Coordinates to Cube Map Faces
  58146. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  58147. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  58148. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  58149. map arrangement in Pixar's RenderMan package.
  58150. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  58151. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  58152. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  58153. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  58154. the major axis direction). The target column in the table below explains how the major axis direction
  58155. maps to the 2D image of a particular cube map target.
  58156. major axis
  58157. direction target sc tc ma
  58158. ---------- --------------------------------- --- --- ---
  58159. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  58160. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  58161. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  58162. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  58163. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  58164. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  58165. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  58166. an updated (s,t) is calculated as follows
  58167. s = ( sc/|ma| + 1 ) / 2
  58168. t = ( tc/|ma| + 1 ) / 2
  58169. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  58170. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  58171. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  58172. */
  58173. // Note this method return U and V in range from 0 to size-1
  58174. // SL END
  58175. // Store the information in vector3 for convenience (faceindex, u, v)
  58176. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  58177. var maxCoord;
  58178. var faceIdx;
  58179. //absolute value 3
  58180. var absX = Math.abs(x);
  58181. var absY = Math.abs(y);
  58182. var absZ = Math.abs(z);
  58183. if (absX >= absY && absX >= absZ) {
  58184. maxCoord = absX;
  58185. if (x >= 0) {
  58186. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  58187. }
  58188. else {
  58189. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  58190. }
  58191. }
  58192. else if (absY >= absX && absY >= absZ) {
  58193. maxCoord = absY;
  58194. if (y >= 0) {
  58195. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  58196. }
  58197. else {
  58198. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  58199. }
  58200. }
  58201. else {
  58202. maxCoord = absZ;
  58203. if (z >= 0) {
  58204. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  58205. }
  58206. else {
  58207. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  58208. }
  58209. }
  58210. //divide through by max coord so face vector lies on cube face
  58211. var scale = 1 / maxCoord;
  58212. x *= scale;
  58213. y *= scale;
  58214. z *= scale;
  58215. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  58216. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  58217. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  58218. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  58219. // Modify original AMD code to return value from 0 to Size - 1
  58220. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  58221. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  58222. PMREMGenerator._vectorTemp.x = faceIdx;
  58223. PMREMGenerator._vectorTemp.y = u;
  58224. PMREMGenerator._vectorTemp.z = v;
  58225. return PMREMGenerator._vectorTemp;
  58226. };
  58227. //--------------------------------------------------------------------------------------
  58228. //Original code from Ignacio CastaÒo
  58229. // This formula is from Manne ÷hrstrˆm's thesis.
  58230. // Take two coordiantes in the range [-1, 1] that define a portion of a
  58231. // cube face and return the area of the projection of that portion on the
  58232. // surface of the sphere.
  58233. //--------------------------------------------------------------------------------------
  58234. PMREMGenerator.prototype.areaElement = function (x, y) {
  58235. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  58236. };
  58237. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  58238. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  58239. // (+ 0.5f is for texel center addressing)
  58240. u = (2.0 * (u + 0.5) / size) - 1.0;
  58241. v = (2.0 * (v + 0.5) / size) - 1.0;
  58242. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  58243. var invResolution = 1.0 / size;
  58244. // U and V are the -1..1 texture coordinate on the current face.
  58245. // Get projected area for this texel
  58246. var x0 = u - invResolution;
  58247. var y0 = v - invResolution;
  58248. var x1 = u + invResolution;
  58249. var y1 = v + invResolution;
  58250. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  58251. return solidAngle;
  58252. };
  58253. //--------------------------------------------------------------------------------------
  58254. //The key to the speed of these filtering routines is to quickly define a per-face
  58255. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  58256. // Later these pixels are selectively processed based on their dot products to see if
  58257. // they reside within the filtering cone.
  58258. //
  58259. //This is done by computing the smallest per-texel angle to get a conservative estimate
  58260. // of the number of texels needed to be covered in width and height order to filter the
  58261. // region. the bounding box for the center taps face is defined first, and if the
  58262. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  58263. // defined next
  58264. //--------------------------------------------------------------------------------------
  58265. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  58266. // note that pixels within these regions may be rejected
  58267. // based on the anlge
  58268. var iCubeFace;
  58269. var u;
  58270. var v;
  58271. // bounding box per face to specify region to process
  58272. var filterExtents = [];
  58273. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  58274. filterExtents.push(new CMGBoundinBox());
  58275. }
  58276. // min angle a src texel can cover (in degrees)
  58277. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  58278. // angle about center tap to define filter cone
  58279. // filter angle is 1/2 the cone angle
  58280. var filterAngle = filterConeAngle / 2.0;
  58281. //ensure filter angle is larger than a texel
  58282. if (filterAngle < srcTexelAngle) {
  58283. filterAngle = srcTexelAngle;
  58284. }
  58285. //ensure filter cone is always smaller than the hemisphere
  58286. if (filterAngle > 90.0) {
  58287. filterAngle = 90.0;
  58288. }
  58289. // the maximum number of texels in 1D the filter cone angle will cover
  58290. // used to determine bounding box size for filter extents
  58291. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  58292. // ensure conservative region always covers at least one texel
  58293. if (filterSize < 1) {
  58294. filterSize = 1;
  58295. }
  58296. // dotProdThresh threshold based on cone angle to determine whether or not taps
  58297. // reside within the cone angle
  58298. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  58299. // process required faces
  58300. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  58301. //iterate over dst cube map face texel
  58302. for (v = 0; v < dstSize; v++) {
  58303. for (u = 0; u < dstSize; u++) {
  58304. //get center tap direction
  58305. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  58306. //clear old per-face filter extents
  58307. this.clearFilterExtents(filterExtents);
  58308. //define per-face filter extents
  58309. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  58310. //perform filtering of src faces using filter extents
  58311. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  58312. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  58313. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  58314. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  58315. }
  58316. }
  58317. }
  58318. };
  58319. //--------------------------------------------------------------------------------------
  58320. //Clear filter extents for the 6 cube map faces
  58321. //--------------------------------------------------------------------------------------
  58322. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  58323. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  58324. filterExtents[iCubeFaces].clear();
  58325. }
  58326. };
  58327. //--------------------------------------------------------------------------------------
  58328. //Define per-face bounding box filter extents
  58329. //
  58330. // These define conservative texel regions in each of the faces the filter can possibly
  58331. // process. When the pixels in the regions are actually processed, the dot product
  58332. // between the tap vector and the center tap vector is used to determine the weight of
  58333. // the tap and whether or not the tap is within the cone.
  58334. //
  58335. //--------------------------------------------------------------------------------------
  58336. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  58337. //neighboring face and bleed over amount, and width of BBOX for
  58338. // left, right, top, and bottom edges of this face
  58339. var bleedOverAmount = [0, 0, 0, 0];
  58340. var bleedOverBBoxMin = [0, 0, 0, 0];
  58341. var bleedOverBBoxMax = [0, 0, 0, 0];
  58342. var neighborFace;
  58343. var neighborEdge;
  58344. var oppositeFaceIdx;
  58345. //get face idx, and u, v info from center tap dir
  58346. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  58347. var faceIdx = result.x;
  58348. var u = result.y;
  58349. var v = result.z;
  58350. //define bbox size within face
  58351. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  58352. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  58353. filterExtents[faceIdx].clampMin(0, 0, 0);
  58354. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  58355. //u and v extent in face corresponding to center tap
  58356. var minU = filterExtents[faceIdx].min.x;
  58357. var minV = filterExtents[faceIdx].min.y;
  58358. var maxU = filterExtents[faceIdx].max.x;
  58359. var maxV = filterExtents[faceIdx].max.y;
  58360. //bleed over amounts for face across u=0 edge (left)
  58361. bleedOverAmount[0] = (bboxSize - u);
  58362. bleedOverBBoxMin[0] = minV;
  58363. bleedOverBBoxMax[0] = maxV;
  58364. //bleed over amounts for face across u=1 edge (right)
  58365. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  58366. bleedOverBBoxMin[1] = minV;
  58367. bleedOverBBoxMax[1] = maxV;
  58368. //bleed over to face across v=0 edge (up)
  58369. bleedOverAmount[2] = (bboxSize - v);
  58370. bleedOverBBoxMin[2] = minU;
  58371. bleedOverBBoxMax[2] = maxU;
  58372. //bleed over to face across v=1 edge (down)
  58373. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  58374. bleedOverBBoxMin[3] = minU;
  58375. bleedOverBBoxMax[3] = maxU;
  58376. //compute bleed over regions in neighboring faces
  58377. for (var i = 0; i < 4; i++) {
  58378. if (bleedOverAmount[i] > 0) {
  58379. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  58380. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  58381. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  58382. // be flipped: the cases are
  58383. // if a left edge mates with a left or bottom edge on the neighbor
  58384. // if a top edge mates with a top or right edge on the neighbor
  58385. // if a right edge mates with a right or top edge on the neighbor
  58386. // if a bottom edge mates with a bottom or left edge on the neighbor
  58387. //Seeing as the edges are enumerated as follows
  58388. // left =0
  58389. // right =1
  58390. // top =2
  58391. // bottom =3
  58392. //
  58393. // so if the edge enums are the same, or the sum of the enums == 3,
  58394. // the bbox needs to be flipped
  58395. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  58396. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  58397. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  58398. }
  58399. //The way the bounding box is extended onto the neighboring face
  58400. // depends on which edge of neighboring face abuts with this one
  58401. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  58402. case PMREMGenerator.CP_EDGE_LEFT:
  58403. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  58404. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  58405. break;
  58406. case PMREMGenerator.CP_EDGE_RIGHT:
  58407. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  58408. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  58409. break;
  58410. case PMREMGenerator.CP_EDGE_TOP:
  58411. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  58412. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  58413. break;
  58414. case PMREMGenerator.CP_EDGE_BOTTOM:
  58415. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  58416. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  58417. break;
  58418. }
  58419. //clamp filter extents in non-center tap faces to remain within surface
  58420. filterExtents[neighborFace].clampMin(0, 0, 0);
  58421. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  58422. }
  58423. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  58424. // from the center tap face, then process the opposite face entirely for now.
  58425. //Note that the cases in which this happens, what usually happens is that
  58426. // more than one edge bleeds onto the opposite face, and the bounding box
  58427. // encompasses the entire cube map face.
  58428. if (bleedOverAmount[i] > srcSize) {
  58429. //determine opposite face
  58430. switch (faceIdx) {
  58431. case PMREMGenerator.CP_FACE_X_POS:
  58432. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  58433. break;
  58434. case PMREMGenerator.CP_FACE_X_NEG:
  58435. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  58436. break;
  58437. case PMREMGenerator.CP_FACE_Y_POS:
  58438. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  58439. break;
  58440. case PMREMGenerator.CP_FACE_Y_NEG:
  58441. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  58442. break;
  58443. case PMREMGenerator.CP_FACE_Z_POS:
  58444. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  58445. break;
  58446. case PMREMGenerator.CP_FACE_Z_NEG:
  58447. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  58448. break;
  58449. default:
  58450. break;
  58451. }
  58452. //just encompass entire face for now
  58453. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  58454. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  58455. }
  58456. }
  58457. };
  58458. //--------------------------------------------------------------------------------------
  58459. //ProcessFilterExtents
  58460. // Process bounding box in each cube face
  58461. //
  58462. //--------------------------------------------------------------------------------------
  58463. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  58464. //accumulators are 64-bit floats in order to have the precision needed
  58465. // over a summation of a large number of pixels
  58466. var dstAccum = [0, 0, 0, 0];
  58467. var weightAccum = 0;
  58468. var k = 0;
  58469. var nSrcChannels = this.numChannels;
  58470. // norm cube map and srcCubeMap have same face width
  58471. var faceWidth = srcSize;
  58472. //amount to add to pointer to move to next scanline in images
  58473. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  58474. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  58475. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  58476. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  58477. // iterate over cubefaces
  58478. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  58479. //if bbox is non empty
  58480. if (!filterExtents[iFaceIdx].empty()) {
  58481. var uStart = filterExtents[iFaceIdx].min.x;
  58482. var vStart = filterExtents[iFaceIdx].min.y;
  58483. var uEnd = filterExtents[iFaceIdx].max.x;
  58484. var vEnd = filterExtents[iFaceIdx].max.y;
  58485. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  58486. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  58487. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  58488. for (var v = vStart; v <= vEnd; v++) {
  58489. var normCubeRowWalk = 0;
  58490. var srcCubeRowWalk = 0;
  58491. for (var u = uStart; u <= uEnd; u++) {
  58492. //pointer to direction in cube map associated with texel
  58493. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  58494. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  58495. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  58496. //check dot product to see if texel is within cone
  58497. var tapDotProd = texelVectX * centerTapDir.x +
  58498. texelVectY * centerTapDir.y +
  58499. texelVectZ * centerTapDir.z;
  58500. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  58501. //solid angle stored in 4th channel of normalizer/solid angle cube map
  58502. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  58503. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  58504. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  58505. // so just adding one to specularpower do the trick.
  58506. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  58507. //iterate over channels
  58508. for (k = 0; k < nSrcChannels; k++) {
  58509. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  58510. srcCubeRowWalk++;
  58511. }
  58512. weightAccum += weight; //accumulate weight
  58513. }
  58514. else {
  58515. //step across source pixel
  58516. srcCubeRowWalk += nSrcChannels;
  58517. }
  58518. normCubeRowWalk += 4; // 4 channels per norm cube map.
  58519. }
  58520. startIndexNormCubeMap += normCubePitch;
  58521. startIndexSrcCubeMap += srcCubePitch;
  58522. }
  58523. }
  58524. }
  58525. //divide through by weights if weight is non zero
  58526. if (weightAccum != 0.0) {
  58527. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  58528. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  58529. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  58530. if (this.numChannels > 3) {
  58531. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  58532. }
  58533. }
  58534. else {
  58535. // otherwise sample nearest
  58536. // get face idx and u, v texel coordinate in face
  58537. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  58538. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  58539. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  58540. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  58541. if (this.numChannels > 3) {
  58542. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  58543. }
  58544. }
  58545. return PMREMGenerator._vectorTemp;
  58546. };
  58547. //--------------------------------------------------------------------------------------
  58548. // Fixup cube edges
  58549. //
  58550. // average texels on cube map faces across the edges
  58551. // WARP/BENT Method Only.
  58552. //--------------------------------------------------------------------------------------
  58553. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  58554. var k;
  58555. var j;
  58556. var i;
  58557. var iFace;
  58558. var iCorner = 0;
  58559. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  58560. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  58561. // note that if functionality to filter across the three texels for each corner, then
  58562. //indexed by corner and face idx. the array contains the face the start points belongs to.
  58563. var cornerPtr = [
  58564. [[], [], []],
  58565. [[], [], []],
  58566. [[], [], []],
  58567. [[], [], []],
  58568. [[], [], []],
  58569. [[], [], []],
  58570. [[], [], []],
  58571. [[], [], []]
  58572. ];
  58573. //if there is no fixup, or fixup width = 0, do nothing
  58574. if (cubeMapSize < 1) {
  58575. return;
  58576. }
  58577. //special case 1x1 cubemap, average face colors
  58578. if (cubeMapSize == 1) {
  58579. //iterate over channels
  58580. for (k = 0; k < this.numChannels; k++) {
  58581. var accum = 0.0;
  58582. //iterate over faces to accumulate face colors
  58583. for (iFace = 0; iFace < 6; iFace++) {
  58584. accum += cubeMap[iFace][k];
  58585. }
  58586. //compute average over 6 face colors
  58587. accum /= 6.0;
  58588. //iterate over faces to distribute face colors
  58589. for (iFace = 0; iFace < 6; iFace++) {
  58590. cubeMap[iFace][k] = accum;
  58591. }
  58592. }
  58593. return;
  58594. }
  58595. //iterate over faces to collect list of corner texel pointers
  58596. for (iFace = 0; iFace < 6; iFace++) {
  58597. //the 4 corner pointers for this face
  58598. faceCornerStartIndicies[0] = [iFace, 0];
  58599. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  58600. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  58601. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  58602. //iterate over face corners to collect cube corner pointers
  58603. for (iCorner = 0; iCorner < 4; iCorner++) {
  58604. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  58605. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  58606. cornerNumPtrs[corner]++;
  58607. }
  58608. }
  58609. //iterate over corners to average across corner tap values
  58610. for (iCorner = 0; iCorner < 8; iCorner++) {
  58611. for (k = 0; k < this.numChannels; k++) {
  58612. var cornerTapAccum = 0.0;
  58613. //iterate over corner texels and average results
  58614. for (i = 0; i < 3; i++) {
  58615. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  58616. }
  58617. //divide by 3 to compute average of corner tap values
  58618. cornerTapAccum *= (1.0 / 3.0);
  58619. //iterate over corner texels and average results
  58620. for (i = 0; i < 3; i++) {
  58621. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  58622. }
  58623. }
  58624. }
  58625. //iterate over the twelve edges of the cube to average across edges
  58626. for (i = 0; i < 12; i++) {
  58627. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  58628. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  58629. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  58630. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  58631. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  58632. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  58633. var edgeWalk = 0;
  58634. var neighborEdgeWalk = 0;
  58635. //Determine walking pointers based on edge type
  58636. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  58637. switch (edge) {
  58638. case PMREMGenerator.CP_EDGE_LEFT:
  58639. // no change to faceEdgeStartPtr
  58640. edgeWalk = this.numChannels * cubeMapSize;
  58641. break;
  58642. case PMREMGenerator.CP_EDGE_RIGHT:
  58643. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  58644. edgeWalk = this.numChannels * cubeMapSize;
  58645. break;
  58646. case PMREMGenerator.CP_EDGE_TOP:
  58647. // no change to faceEdgeStartPtr
  58648. edgeWalk = this.numChannels;
  58649. break;
  58650. case PMREMGenerator.CP_EDGE_BOTTOM:
  58651. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  58652. edgeWalk = this.numChannels;
  58653. break;
  58654. }
  58655. //For certain types of edge abutments, the neighbor edge walk needs to
  58656. // be flipped: the cases are
  58657. // if a left edge mates with a left or bottom edge on the neighbor
  58658. // if a top edge mates with a top or right edge on the neighbor
  58659. // if a right edge mates with a right or top edge on the neighbor
  58660. // if a bottom edge mates with a bottom or left edge on the neighbor
  58661. //Seeing as the edges are enumerated as follows
  58662. // left =0
  58663. // right =1
  58664. // top =2
  58665. // bottom =3
  58666. //
  58667. //If the edge enums are the same, or the sum of the enums == 3,
  58668. // the neighbor edge walk needs to be flipped
  58669. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  58670. switch (neighborEdge) {
  58671. case PMREMGenerator.CP_EDGE_LEFT:
  58672. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  58673. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  58674. break;
  58675. case PMREMGenerator.CP_EDGE_RIGHT:
  58676. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  58677. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  58678. break;
  58679. case PMREMGenerator.CP_EDGE_TOP:
  58680. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  58681. neighborEdgeWalk = -this.numChannels;
  58682. break;
  58683. case PMREMGenerator.CP_EDGE_BOTTOM:
  58684. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  58685. neighborEdgeWalk = -this.numChannels;
  58686. break;
  58687. }
  58688. }
  58689. else {
  58690. //swapped direction neighbor edge walk
  58691. switch (neighborEdge) {
  58692. case PMREMGenerator.CP_EDGE_LEFT:
  58693. //no change to neighborEdgeStartPtr for this case since it points
  58694. // to the upper left corner already
  58695. neighborEdgeWalk = this.numChannels * cubeMapSize;
  58696. break;
  58697. case PMREMGenerator.CP_EDGE_RIGHT:
  58698. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  58699. neighborEdgeWalk = this.numChannels * cubeMapSize;
  58700. break;
  58701. case PMREMGenerator.CP_EDGE_TOP:
  58702. //no change to neighborEdgeStartPtr for this case since it points
  58703. // to the upper left corner already
  58704. neighborEdgeWalk = this.numChannels;
  58705. break;
  58706. case PMREMGenerator.CP_EDGE_BOTTOM:
  58707. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  58708. neighborEdgeWalk = this.numChannels;
  58709. break;
  58710. }
  58711. }
  58712. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  58713. //nearby neighborhood
  58714. //step ahead one texel on edge
  58715. edgeStartIndex += edgeWalk;
  58716. neighborEdgeStartIndex += neighborEdgeWalk;
  58717. // note that this loop does not process the corner texels, since they have already been
  58718. // averaged across faces across earlier
  58719. for (j = 1; j < (cubeMapSize - 1); j++) {
  58720. //for each set of taps along edge, average them
  58721. // and rewrite the results into the edges
  58722. for (k = 0; k < this.numChannels; k++) {
  58723. var edgeTap = cubeMap[face][edgeStartIndex + k];
  58724. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  58725. //compute average of tap intensity values
  58726. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  58727. //propagate average of taps to edge taps
  58728. cubeMap[face][edgeStartIndex + k] = avgTap;
  58729. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  58730. }
  58731. edgeStartIndex += edgeWalk;
  58732. neighborEdgeStartIndex += neighborEdgeWalk;
  58733. }
  58734. }
  58735. };
  58736. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  58737. PMREMGenerator.CP_UDIR = 0;
  58738. PMREMGenerator.CP_VDIR = 1;
  58739. PMREMGenerator.CP_FACEAXIS = 2;
  58740. //used to index cube faces
  58741. PMREMGenerator.CP_FACE_X_POS = 0;
  58742. PMREMGenerator.CP_FACE_X_NEG = 1;
  58743. PMREMGenerator.CP_FACE_Y_POS = 2;
  58744. PMREMGenerator.CP_FACE_Y_NEG = 3;
  58745. PMREMGenerator.CP_FACE_Z_POS = 4;
  58746. PMREMGenerator.CP_FACE_Z_NEG = 5;
  58747. //used to index image edges
  58748. // NOTE.. the actual number corresponding to the edge is important
  58749. // do not change these, or the code will break
  58750. //
  58751. // CP_EDGE_LEFT is u = 0
  58752. // CP_EDGE_RIGHT is u = width-1
  58753. // CP_EDGE_TOP is v = 0
  58754. // CP_EDGE_BOTTOM is v = height-1
  58755. PMREMGenerator.CP_EDGE_LEFT = 0;
  58756. PMREMGenerator.CP_EDGE_RIGHT = 1;
  58757. PMREMGenerator.CP_EDGE_TOP = 2;
  58758. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  58759. //corners of CUBE map (P or N specifys if it corresponds to the
  58760. // positive or negative direction each of X, Y, and Z
  58761. PMREMGenerator.CP_CORNER_NNN = 0;
  58762. PMREMGenerator.CP_CORNER_NNP = 1;
  58763. PMREMGenerator.CP_CORNER_NPN = 2;
  58764. PMREMGenerator.CP_CORNER_NPP = 3;
  58765. PMREMGenerator.CP_CORNER_PNN = 4;
  58766. PMREMGenerator.CP_CORNER_PNP = 5;
  58767. PMREMGenerator.CP_CORNER_PPN = 6;
  58768. PMREMGenerator.CP_CORNER_PPP = 7;
  58769. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  58770. //3x2 matrices that map cube map indexing vectors in 3d
  58771. // (after face selection and divide through by the
  58772. // _ABSOLUTE VALUE_ of the max coord)
  58773. // into NVC space
  58774. //Note this currently assumes the D3D cube face ordering and orientation
  58775. PMREMGenerator._sgFace2DMapping = [
  58776. //XPOS face
  58777. [[0, 0, -1],
  58778. [0, -1, 0],
  58779. [1, 0, 0]],
  58780. //XNEG face
  58781. [[0, 0, 1],
  58782. [0, -1, 0],
  58783. [-1, 0, 0]],
  58784. //YPOS face
  58785. [[1, 0, 0],
  58786. [0, 0, 1],
  58787. [0, 1, 0]],
  58788. //YNEG face
  58789. [[1, 0, 0],
  58790. [0, 0, -1],
  58791. [0, -1, 0]],
  58792. //ZPOS face
  58793. [[1, 0, 0],
  58794. [0, -1, 0],
  58795. [0, 0, 1]],
  58796. //ZNEG face
  58797. [[-1, 0, 0],
  58798. [0, -1, 0],
  58799. [0, 0, -1]],
  58800. ];
  58801. //------------------------------------------------------------------------------
  58802. // D3D cube map face specification
  58803. // mapping from 3D x,y,z cube map lookup coordinates
  58804. // to 2D within face u,v coordinates
  58805. //
  58806. // --------------------> U direction
  58807. // | (within-face texture space)
  58808. // | _____
  58809. // | | |
  58810. // | | +Y |
  58811. // | _____|_____|_____ _____
  58812. // | | | | | |
  58813. // | | -X | +Z | +X | -Z |
  58814. // | |_____|_____|_____|_____|
  58815. // | | |
  58816. // | | -Y |
  58817. // | |_____|
  58818. // |
  58819. // v V direction
  58820. // (within-face texture space)
  58821. //------------------------------------------------------------------------------
  58822. //Information about neighbors and how texture coorrdinates change across faces
  58823. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  58824. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  58825. //Note this currently assumes the D3D cube face ordering and orientation
  58826. PMREMGenerator._sgCubeNgh = [
  58827. //XPOS face
  58828. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  58829. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  58830. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  58831. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  58832. //XNEG face
  58833. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  58834. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  58835. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  58836. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  58837. //YPOS face
  58838. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  58839. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  58840. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  58841. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  58842. //YNEG face
  58843. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  58844. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  58845. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  58846. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  58847. //ZPOS face
  58848. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  58849. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  58850. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  58851. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  58852. //ZNEG face
  58853. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  58854. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  58855. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  58856. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  58857. ];
  58858. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  58859. // this table is used to average over the edges.
  58860. PMREMGenerator._sgCubeEdgeList = [
  58861. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  58862. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  58863. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  58864. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  58865. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  58866. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  58867. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  58868. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  58869. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  58870. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  58871. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  58872. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  58873. ];
  58874. //Information about which of the 8 cube corners are correspond to the
  58875. // the 4 corners in each cube face
  58876. // the order is upper left, upper right, lower left, lower right
  58877. PMREMGenerator._sgCubeCornerList = [
  58878. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  58879. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  58880. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  58881. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  58882. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  58883. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  58884. ];
  58885. return PMREMGenerator;
  58886. })();
  58887. Internals.PMREMGenerator = PMREMGenerator;
  58888. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58889. })(BABYLON || (BABYLON = {}));
  58890. var BABYLON;
  58891. (function (BABYLON) {
  58892. /**
  58893. * This represents a texture coming from an HDR input.
  58894. *
  58895. * The only supported format is currently panorama picture stored in RGBE format.
  58896. * Example of such files can be found on HDRLib: http://hdrlib.com/
  58897. */
  58898. var HDRCubeTexture = (function (_super) {
  58899. __extends(HDRCubeTexture, _super);
  58900. /**
  58901. * Instantiates an HDRTexture from the following parameters.
  58902. *
  58903. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  58904. * @param scene The scene the texture will be used in
  58905. * @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.
  58906. * @param noMipmap Forces to not generate the mipmap if true
  58907. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  58908. * @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)
  58909. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  58910. */
  58911. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  58912. if (noMipmap === void 0) { noMipmap = false; }
  58913. if (generateHarmonics === void 0) { generateHarmonics = true; }
  58914. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  58915. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  58916. _super.call(this, scene);
  58917. this._useInGammaSpace = false;
  58918. this._generateHarmonics = true;
  58919. this._isBABYLONPreprocessed = false;
  58920. /**
  58921. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  58922. */
  58923. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58924. /**
  58925. * The spherical polynomial data extracted from the texture.
  58926. */
  58927. this.sphericalPolynomial = null;
  58928. /**
  58929. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  58930. * This is usefull at run time to apply the good shader.
  58931. */
  58932. this.isPMREM = false;
  58933. if (!url) {
  58934. return;
  58935. }
  58936. this.name = url;
  58937. this.url = url;
  58938. this.hasAlpha = false;
  58939. this.isCube = true;
  58940. this._textureMatrix = BABYLON.Matrix.Identity();
  58941. if (size) {
  58942. this._isBABYLONPreprocessed = false;
  58943. this._noMipmap = noMipmap;
  58944. this._size = size;
  58945. this._useInGammaSpace = useInGammaSpace;
  58946. this._usePMREMGenerator = usePMREMGenerator &&
  58947. scene.getEngine().getCaps().textureLOD &&
  58948. this.getScene().getEngine().getCaps().textureFloat &&
  58949. !this._useInGammaSpace;
  58950. }
  58951. else {
  58952. this._isBABYLONPreprocessed = true;
  58953. this._noMipmap = false;
  58954. this._useInGammaSpace = false;
  58955. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  58956. this.getScene().getEngine().getCaps().textureFloat &&
  58957. !this._useInGammaSpace;
  58958. }
  58959. this.isPMREM = this._usePMREMGenerator;
  58960. this._texture = this._getFromCache(url, this._noMipmap);
  58961. if (!this._texture) {
  58962. if (!scene.useDelayedTextureLoading) {
  58963. this.loadTexture();
  58964. }
  58965. else {
  58966. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58967. }
  58968. }
  58969. }
  58970. /**
  58971. * Occurs when the file is a preprocessed .babylon.hdr file.
  58972. */
  58973. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  58974. var _this = this;
  58975. var mipLevels = 0;
  58976. var floatArrayView = null;
  58977. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  58978. var mips = [];
  58979. var startIndex = 30;
  58980. for (var level = 0; level < mipLevels; level++) {
  58981. mips.push([]);
  58982. // Fill each pixel of the mip level.
  58983. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  58984. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  58985. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  58986. mips[level].push(faceData);
  58987. startIndex += faceSize;
  58988. }
  58989. }
  58990. return mips;
  58991. } : null;
  58992. var callback = function (buffer) {
  58993. // Create Native Array Views
  58994. var intArrayView = new Int32Array(buffer);
  58995. floatArrayView = new Float32Array(buffer);
  58996. // Fill header.
  58997. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  58998. _this._size = intArrayView[1]; // CubeMap max mip face size.
  58999. // Update Texture Information.
  59000. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  59001. // Fill polynomial information.
  59002. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  59003. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  59004. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  59005. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  59006. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  59007. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  59008. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  59009. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  59010. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  59011. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  59012. // Fill pixel data.
  59013. mipLevels = intArrayView[29]; // Number of mip levels.
  59014. var startIndex = 30;
  59015. var data = [];
  59016. var faceSize = Math.pow(_this._size, 2) * 3;
  59017. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59018. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  59019. startIndex += faceSize;
  59020. }
  59021. var results = [];
  59022. var byteArray = null;
  59023. // Push each faces.
  59024. for (var k = 0; k < 6; k++) {
  59025. var dataFace = null;
  59026. // If special cases.
  59027. if (!mipmapGenerator) {
  59028. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  59029. dataFace = data[j];
  59030. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  59031. // 3 channels of 1 bytes per pixel in bytes.
  59032. var byteBuffer = new ArrayBuffer(faceSize);
  59033. byteArray = new Uint8Array(byteBuffer);
  59034. }
  59035. for (var i = 0; i < _this._size * _this._size; i++) {
  59036. // Put in gamma space if requested.
  59037. if (_this._useInGammaSpace) {
  59038. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  59039. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  59040. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  59041. }
  59042. // Convert to int texture for fallback.
  59043. if (byteArray) {
  59044. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  59045. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  59046. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  59047. // May use luminance instead if the result is not accurate.
  59048. var max = Math.max(Math.max(r, g), b);
  59049. if (max > 255) {
  59050. var scale = 255 / max;
  59051. r *= scale;
  59052. g *= scale;
  59053. b *= scale;
  59054. }
  59055. byteArray[(i * 3) + 0] = r;
  59056. byteArray[(i * 3) + 1] = g;
  59057. byteArray[(i * 3) + 2] = b;
  59058. }
  59059. }
  59060. }
  59061. else {
  59062. dataFace = data[k];
  59063. }
  59064. // Fill the array accordingly.
  59065. if (byteArray) {
  59066. results.push(byteArray);
  59067. }
  59068. else {
  59069. results.push(dataFace);
  59070. }
  59071. }
  59072. return results;
  59073. };
  59074. 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);
  59075. };
  59076. /**
  59077. * Occurs when the file is raw .hdr file.
  59078. */
  59079. HDRCubeTexture.prototype.loadHDRTexture = function () {
  59080. var _this = this;
  59081. var callback = function (buffer) {
  59082. // Extract the raw linear data.
  59083. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  59084. // Generate harmonics if needed.
  59085. if (_this._generateHarmonics) {
  59086. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  59087. }
  59088. var results = [];
  59089. var byteArray = null;
  59090. // Push each faces.
  59091. for (var j = 0; j < 6; j++) {
  59092. // Create uintarray fallback.
  59093. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  59094. // 3 channels of 1 bytes per pixel in bytes.
  59095. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  59096. byteArray = new Uint8Array(byteBuffer);
  59097. }
  59098. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  59099. // If special cases.
  59100. if (_this._useInGammaSpace || byteArray) {
  59101. for (var i = 0; i < _this._size * _this._size; i++) {
  59102. // Put in gamma space if requested.
  59103. if (_this._useInGammaSpace) {
  59104. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  59105. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  59106. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  59107. }
  59108. // Convert to int texture for fallback.
  59109. if (byteArray) {
  59110. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  59111. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  59112. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  59113. // May use luminance instead if the result is not accurate.
  59114. var max = Math.max(Math.max(r, g), b);
  59115. if (max > 255) {
  59116. var scale = 255 / max;
  59117. r *= scale;
  59118. g *= scale;
  59119. b *= scale;
  59120. }
  59121. byteArray[(i * 3) + 0] = r;
  59122. byteArray[(i * 3) + 1] = g;
  59123. byteArray[(i * 3) + 2] = b;
  59124. }
  59125. }
  59126. }
  59127. if (byteArray) {
  59128. results.push(byteArray);
  59129. }
  59130. else {
  59131. results.push(dataFace);
  59132. }
  59133. }
  59134. return results;
  59135. };
  59136. var mipmapGenerator = null;
  59137. if (!this._noMipmap &&
  59138. this._usePMREMGenerator) {
  59139. mipmapGenerator = function (data) {
  59140. // Custom setup of the generator matching with the PBR shader values.
  59141. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  59142. return generator.filterCubeMap();
  59143. };
  59144. }
  59145. 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);
  59146. };
  59147. /**
  59148. * Starts the loading process of the texture.
  59149. */
  59150. HDRCubeTexture.prototype.loadTexture = function () {
  59151. if (this._isBABYLONPreprocessed) {
  59152. this.loadBabylonTexture();
  59153. }
  59154. else {
  59155. this.loadHDRTexture();
  59156. }
  59157. };
  59158. HDRCubeTexture.prototype.clone = function () {
  59159. var size = this._isBABYLONPreprocessed ? null : this._size;
  59160. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  59161. // Base texture
  59162. newTexture.level = this.level;
  59163. newTexture.wrapU = this.wrapU;
  59164. newTexture.wrapV = this.wrapV;
  59165. newTexture.coordinatesIndex = this.coordinatesIndex;
  59166. newTexture.coordinatesMode = this.coordinatesMode;
  59167. return newTexture;
  59168. };
  59169. // Methods
  59170. HDRCubeTexture.prototype.delayLoad = function () {
  59171. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  59172. return;
  59173. }
  59174. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  59175. this._texture = this._getFromCache(this.url, this._noMipmap);
  59176. if (!this._texture) {
  59177. this.loadTexture();
  59178. }
  59179. };
  59180. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  59181. return this._textureMatrix;
  59182. };
  59183. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  59184. var texture = null;
  59185. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  59186. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  59187. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  59188. texture.name = parsedTexture.name;
  59189. texture.hasAlpha = parsedTexture.hasAlpha;
  59190. texture.level = parsedTexture.level;
  59191. texture.coordinatesMode = parsedTexture.coordinatesMode;
  59192. }
  59193. return texture;
  59194. };
  59195. HDRCubeTexture.prototype.serialize = function () {
  59196. if (!this.name) {
  59197. return null;
  59198. }
  59199. var serializationObject = {};
  59200. serializationObject.name = this.name;
  59201. serializationObject.hasAlpha = this.hasAlpha;
  59202. serializationObject.isCube = true;
  59203. serializationObject.level = this.level;
  59204. serializationObject.size = this._size;
  59205. serializationObject.coordinatesMode = this.coordinatesMode;
  59206. serializationObject.useInGammaSpace = this._useInGammaSpace;
  59207. serializationObject.generateHarmonics = this._generateHarmonics;
  59208. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  59209. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  59210. serializationObject.customType = "BABYLON.HDRCubeTexture";
  59211. return serializationObject;
  59212. };
  59213. /**
  59214. * Saves as a file the data contained in the texture in a binary format.
  59215. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  59216. * as the spherical used in the lighting.
  59217. * @param url The HDR file url.
  59218. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  59219. * @param onError Method called if any error happens during download.
  59220. * @return The packed binary data.
  59221. */
  59222. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  59223. if (onError === void 0) { onError = null; }
  59224. var callback = function (buffer) {
  59225. var data = new Blob([buffer], { type: 'application/octet-stream' });
  59226. // Returns a URL you can use as a href.
  59227. var objUrl = window.URL.createObjectURL(data);
  59228. // Simulates a link to it and click to dowload.
  59229. var a = document.createElement("a");
  59230. document.body.appendChild(a);
  59231. a.style.display = "none";
  59232. a.href = objUrl;
  59233. a.download = "envmap.babylon.hdr";
  59234. a.click();
  59235. };
  59236. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  59237. };
  59238. /**
  59239. * Serializes the data contained in the texture in a binary format.
  59240. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  59241. * as the spherical used in the lighting.
  59242. * @param url The HDR file url.
  59243. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  59244. * @param onError Method called if any error happens during download.
  59245. * @return The packed binary data.
  59246. */
  59247. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  59248. if (onError === void 0) { onError = null; }
  59249. // Needs the url tho create the texture.
  59250. if (!url) {
  59251. return null;
  59252. }
  59253. // Check Power of two size.
  59254. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  59255. return null;
  59256. }
  59257. var getDataCallback = function (dataBuffer) {
  59258. // Extract the raw linear data.
  59259. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  59260. // Generate harmonics if needed.
  59261. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  59262. // Generate seamless faces
  59263. var mipGeneratorArray = [];
  59264. // Data are known to be in +X +Y +Z -X -Y -Z
  59265. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  59266. mipGeneratorArray.push(cubeData.right); // +X
  59267. mipGeneratorArray.push(cubeData.left); // -X
  59268. mipGeneratorArray.push(cubeData.up); // +Y
  59269. mipGeneratorArray.push(cubeData.down); // -Y
  59270. mipGeneratorArray.push(cubeData.front); // +Z
  59271. mipGeneratorArray.push(cubeData.back); // -Z
  59272. // Custom setup of the generator matching with the PBR shader values.
  59273. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  59274. var mippedData = generator.filterCubeMap();
  59275. // Compute required byte length.
  59276. var byteLength = 1 * 4; // Raw Data Version int32.
  59277. byteLength += 4; // CubeMap max mip face size int32.
  59278. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  59279. // Add data size.
  59280. byteLength += 4; // Number of mip levels int32.
  59281. for (var level = 0; level < mippedData.length; level++) {
  59282. var mipSize = size >> level;
  59283. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  59284. }
  59285. // Prepare binary structure.
  59286. var buffer = new ArrayBuffer(byteLength);
  59287. var intArrayView = new Int32Array(buffer);
  59288. var floatArrayView = new Float32Array(buffer);
  59289. // Fill header.
  59290. intArrayView[0] = 1; // Version 1.
  59291. intArrayView[1] = size; // CubeMap max mip face size.
  59292. // Fill polynomial information.
  59293. sphericalPolynomial.x.toArray(floatArrayView, 2);
  59294. sphericalPolynomial.y.toArray(floatArrayView, 5);
  59295. sphericalPolynomial.z.toArray(floatArrayView, 8);
  59296. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  59297. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  59298. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  59299. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  59300. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  59301. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  59302. // Fill pixel data.
  59303. intArrayView[29] = mippedData.length; // Number of mip levels.
  59304. var startIndex = 30;
  59305. for (var level = 0; level < mippedData.length; level++) {
  59306. // Fill each pixel of the mip level.
  59307. var faceSize = Math.pow(size >> level, 2) * 3;
  59308. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59309. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  59310. startIndex += faceSize;
  59311. }
  59312. }
  59313. // Callback.
  59314. callback(buffer);
  59315. };
  59316. // Download and process.
  59317. BABYLON.Tools.LoadFile(url, function (data) {
  59318. getDataCallback(data);
  59319. }, null, null, true, onError);
  59320. };
  59321. HDRCubeTexture._facesMapping = [
  59322. "right",
  59323. "up",
  59324. "front",
  59325. "left",
  59326. "down",
  59327. "back"
  59328. ];
  59329. return HDRCubeTexture;
  59330. })(BABYLON.BaseTexture);
  59331. BABYLON.HDRCubeTexture = HDRCubeTexture;
  59332. })(BABYLON || (BABYLON = {}));
  59333. var BABYLON;
  59334. (function (BABYLON) {
  59335. var Debug;
  59336. (function (Debug) {
  59337. /**
  59338. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  59339. */
  59340. var SkeletonViewer = (function () {
  59341. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  59342. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  59343. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  59344. this.skeleton = skeleton;
  59345. this.mesh = mesh;
  59346. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  59347. this.renderingGroupId = renderingGroupId;
  59348. this.color = BABYLON.Color3.White();
  59349. this._debugLines = [];
  59350. this._isEnabled = false;
  59351. this._scene = scene;
  59352. this.update();
  59353. this._renderFunction = this.update.bind(this);
  59354. }
  59355. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  59356. get: function () {
  59357. return this._isEnabled;
  59358. },
  59359. set: function (value) {
  59360. if (this._isEnabled === value) {
  59361. return;
  59362. }
  59363. this._isEnabled = value;
  59364. if (value) {
  59365. this._scene.registerBeforeRender(this._renderFunction);
  59366. }
  59367. else {
  59368. this._scene.unregisterBeforeRender(this._renderFunction);
  59369. }
  59370. },
  59371. enumerable: true,
  59372. configurable: true
  59373. });
  59374. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  59375. if (x === void 0) { x = 0; }
  59376. if (y === void 0) { y = 0; }
  59377. if (z === void 0) { z = 0; }
  59378. var tmat = BABYLON.Tmp.Matrix[0];
  59379. var parentBone = bone.getParent();
  59380. tmat.copyFrom(bone.getLocalMatrix());
  59381. if (x !== 0 || y !== 0 || z !== 0) {
  59382. var tmat2 = BABYLON.Tmp.Matrix[1];
  59383. BABYLON.Matrix.IdentityToRef(tmat2);
  59384. tmat2.m[12] = x;
  59385. tmat2.m[13] = y;
  59386. tmat2.m[14] = z;
  59387. tmat2.multiplyToRef(tmat, tmat);
  59388. }
  59389. if (parentBone) {
  59390. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  59391. }
  59392. tmat.multiplyToRef(meshMat, tmat);
  59393. position.x = tmat.m[12];
  59394. position.y = tmat.m[13];
  59395. position.z = tmat.m[14];
  59396. };
  59397. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  59398. var len = bones.length;
  59399. for (var i = 0; i < len; i++) {
  59400. var bone = bones[i];
  59401. var points = this._debugLines[i];
  59402. if (!points) {
  59403. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59404. this._debugLines[i] = points;
  59405. }
  59406. this._getBonePosition(points[0], bone, meshMat);
  59407. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  59408. }
  59409. };
  59410. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  59411. var len = bones.length;
  59412. var boneNum = 0;
  59413. for (var i = len - 1; i >= 0; i--) {
  59414. var childBone = bones[i];
  59415. var parentBone = childBone.getParent();
  59416. if (!parentBone) {
  59417. continue;
  59418. }
  59419. var points = this._debugLines[boneNum];
  59420. if (!points) {
  59421. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59422. this._debugLines[boneNum] = points;
  59423. }
  59424. this._getBonePosition(points[0], childBone, meshMat);
  59425. this._getBonePosition(points[1], parentBone, meshMat);
  59426. boneNum++;
  59427. }
  59428. };
  59429. SkeletonViewer.prototype.update = function () {
  59430. if (this.autoUpdateBonesMatrices) {
  59431. this._updateBoneMatrix(this.skeleton.bones[0]);
  59432. }
  59433. if (this.skeleton.bones[0].length === undefined) {
  59434. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59435. }
  59436. else {
  59437. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59438. }
  59439. if (!this._debugMesh) {
  59440. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  59441. this._debugMesh.renderingGroupId = this.renderingGroupId;
  59442. }
  59443. else {
  59444. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  59445. }
  59446. this._debugMesh.color = this.color;
  59447. };
  59448. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  59449. if (bone.getParent()) {
  59450. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  59451. }
  59452. var children = bone.children;
  59453. var len = children.length;
  59454. for (var i = 0; i < len; i++) {
  59455. this._updateBoneMatrix(children[i]);
  59456. }
  59457. };
  59458. SkeletonViewer.prototype.dispose = function () {
  59459. if (this._debugMesh) {
  59460. this.isEnabled = false;
  59461. this._debugMesh.dispose();
  59462. this._debugMesh = null;
  59463. }
  59464. };
  59465. return SkeletonViewer;
  59466. })();
  59467. Debug.SkeletonViewer = SkeletonViewer;
  59468. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59469. })(BABYLON || (BABYLON = {}));
  59470. var BABYLON;
  59471. (function (BABYLON) {
  59472. /**
  59473. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  59474. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  59475. * 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;
  59476. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  59477. */
  59478. var ColorCurves = (function () {
  59479. function ColorCurves() {
  59480. this._dirty = true;
  59481. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  59482. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  59483. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  59484. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  59485. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  59486. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  59487. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  59488. this._globalHue = 30;
  59489. this._globalDensity = 0;
  59490. this._globalSaturation = 0;
  59491. this._globalExposure = 0;
  59492. this._highlightsHue = 30;
  59493. this._highlightsDensity = 0;
  59494. this._highlightsSaturation = 0;
  59495. this._highlightsExposure = 0;
  59496. this._midtonesHue = 30;
  59497. this._midtonesDensity = 0;
  59498. this._midtonesSaturation = 0;
  59499. this._midtonesExposure = 0;
  59500. this._shadowsHue = 30;
  59501. this._shadowsDensity = 0;
  59502. this._shadowsSaturation = 0;
  59503. this._shadowsExposure = 0;
  59504. }
  59505. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  59506. /**
  59507. * Gets the global Hue value.
  59508. * 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).
  59509. */
  59510. get: function () {
  59511. return this._globalHue;
  59512. },
  59513. /**
  59514. * Sets the global Hue value.
  59515. * 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).
  59516. */
  59517. set: function (value) {
  59518. this._globalHue = value;
  59519. this._dirty = true;
  59520. },
  59521. enumerable: true,
  59522. configurable: true
  59523. });
  59524. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  59525. /**
  59526. * Gets the global Density value.
  59527. * 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.
  59528. * Values less than zero provide a filter of opposite hue.
  59529. */
  59530. get: function () {
  59531. return this._globalDensity;
  59532. },
  59533. /**
  59534. * Sets the global Density value.
  59535. * 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.
  59536. * Values less than zero provide a filter of opposite hue.
  59537. */
  59538. set: function (value) {
  59539. this._globalDensity = value;
  59540. this._dirty = true;
  59541. },
  59542. enumerable: true,
  59543. configurable: true
  59544. });
  59545. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  59546. /**
  59547. * Gets the global Saturation value.
  59548. * 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.
  59549. */
  59550. get: function () {
  59551. return this._globalSaturation;
  59552. },
  59553. /**
  59554. * Sets the global Saturation value.
  59555. * 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.
  59556. */
  59557. set: function (value) {
  59558. this._globalSaturation = value;
  59559. this._dirty = true;
  59560. },
  59561. enumerable: true,
  59562. configurable: true
  59563. });
  59564. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  59565. /**
  59566. * Gets the highlights Hue value.
  59567. * 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).
  59568. */
  59569. get: function () {
  59570. return this._highlightsHue;
  59571. },
  59572. /**
  59573. * Sets the highlights Hue value.
  59574. * 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).
  59575. */
  59576. set: function (value) {
  59577. this._highlightsHue = value;
  59578. this._dirty = true;
  59579. },
  59580. enumerable: true,
  59581. configurable: true
  59582. });
  59583. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  59584. /**
  59585. * Gets the highlights Density value.
  59586. * 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.
  59587. * Values less than zero provide a filter of opposite hue.
  59588. */
  59589. get: function () {
  59590. return this._highlightsDensity;
  59591. },
  59592. /**
  59593. * Sets the highlights Density value.
  59594. * 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.
  59595. * Values less than zero provide a filter of opposite hue.
  59596. */
  59597. set: function (value) {
  59598. this._highlightsDensity = value;
  59599. this._dirty = true;
  59600. },
  59601. enumerable: true,
  59602. configurable: true
  59603. });
  59604. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  59605. /**
  59606. * Gets the highlights Saturation value.
  59607. * 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.
  59608. */
  59609. get: function () {
  59610. return this._highlightsSaturation;
  59611. },
  59612. /**
  59613. * Sets the highlights Saturation value.
  59614. * 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.
  59615. */
  59616. set: function (value) {
  59617. this._highlightsSaturation = value;
  59618. this._dirty = true;
  59619. },
  59620. enumerable: true,
  59621. configurable: true
  59622. });
  59623. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  59624. /**
  59625. * Gets the highlights Exposure value.
  59626. * 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.
  59627. */
  59628. get: function () {
  59629. return this._highlightsExposure;
  59630. },
  59631. /**
  59632. * Sets the highlights Exposure value.
  59633. * 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.
  59634. */
  59635. set: function (value) {
  59636. this._highlightsExposure = value;
  59637. this._dirty = true;
  59638. },
  59639. enumerable: true,
  59640. configurable: true
  59641. });
  59642. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  59643. /**
  59644. * Gets the midtones Hue value.
  59645. * 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).
  59646. */
  59647. get: function () {
  59648. return this._midtonesHue;
  59649. },
  59650. /**
  59651. * Sets the midtones Hue value.
  59652. * 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).
  59653. */
  59654. set: function (value) {
  59655. this._midtonesHue = value;
  59656. this._dirty = true;
  59657. },
  59658. enumerable: true,
  59659. configurable: true
  59660. });
  59661. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  59662. /**
  59663. * Gets the midtones Density value.
  59664. * 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.
  59665. * Values less than zero provide a filter of opposite hue.
  59666. */
  59667. get: function () {
  59668. return this._midtonesDensity;
  59669. },
  59670. /**
  59671. * Sets the midtones Density value.
  59672. * 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.
  59673. * Values less than zero provide a filter of opposite hue.
  59674. */
  59675. set: function (value) {
  59676. this._midtonesDensity = value;
  59677. this._dirty = true;
  59678. },
  59679. enumerable: true,
  59680. configurable: true
  59681. });
  59682. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  59683. /**
  59684. * Gets the midtones Saturation value.
  59685. * 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.
  59686. */
  59687. get: function () {
  59688. return this._midtonesSaturation;
  59689. },
  59690. /**
  59691. * Sets the midtones Saturation value.
  59692. * 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.
  59693. */
  59694. set: function (value) {
  59695. this._midtonesSaturation = value;
  59696. this._dirty = true;
  59697. },
  59698. enumerable: true,
  59699. configurable: true
  59700. });
  59701. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  59702. /**
  59703. * Gets the midtones Exposure value.
  59704. * 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.
  59705. */
  59706. get: function () {
  59707. return this._midtonesExposure;
  59708. },
  59709. /**
  59710. * Sets the midtones Exposure value.
  59711. * 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.
  59712. */
  59713. set: function (value) {
  59714. this._midtonesExposure = value;
  59715. this._dirty = true;
  59716. },
  59717. enumerable: true,
  59718. configurable: true
  59719. });
  59720. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  59721. /**
  59722. * Gets the shadows Hue value.
  59723. * 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).
  59724. */
  59725. get: function () {
  59726. return this._shadowsHue;
  59727. },
  59728. /**
  59729. * Sets the shadows Hue value.
  59730. * 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).
  59731. */
  59732. set: function (value) {
  59733. this._shadowsHue = value;
  59734. this._dirty = true;
  59735. },
  59736. enumerable: true,
  59737. configurable: true
  59738. });
  59739. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  59740. /**
  59741. * Gets the shadows Density value.
  59742. * 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.
  59743. * Values less than zero provide a filter of opposite hue.
  59744. */
  59745. get: function () {
  59746. return this._shadowsDensity;
  59747. },
  59748. /**
  59749. * Sets the shadows Density value.
  59750. * 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.
  59751. * Values less than zero provide a filter of opposite hue.
  59752. */
  59753. set: function (value) {
  59754. this._shadowsDensity = value;
  59755. this._dirty = true;
  59756. },
  59757. enumerable: true,
  59758. configurable: true
  59759. });
  59760. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  59761. /**
  59762. * Gets the shadows Saturation value.
  59763. * 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.
  59764. */
  59765. get: function () {
  59766. return this._shadowsSaturation;
  59767. },
  59768. /**
  59769. * Sets the shadows Saturation value.
  59770. * 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.
  59771. */
  59772. set: function (value) {
  59773. this._shadowsSaturation = value;
  59774. this._dirty = true;
  59775. },
  59776. enumerable: true,
  59777. configurable: true
  59778. });
  59779. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  59780. /**
  59781. * Gets the shadows Exposure value.
  59782. * 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.
  59783. */
  59784. get: function () {
  59785. return this._shadowsExposure;
  59786. },
  59787. /**
  59788. * Sets the shadows Exposure value.
  59789. * 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.
  59790. */
  59791. set: function (value) {
  59792. this._shadowsExposure = value;
  59793. this._dirty = true;
  59794. },
  59795. enumerable: true,
  59796. configurable: true
  59797. });
  59798. /**
  59799. * Binds the color curves to the shader.
  59800. * @param colorCurves The color curve to bind
  59801. * @param effect The effect to bind to
  59802. */
  59803. ColorCurves.Bind = function (colorCurves, effect) {
  59804. if (colorCurves._dirty) {
  59805. colorCurves._dirty = false;
  59806. // Fill in global info.
  59807. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  59808. // Compute highlights info.
  59809. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  59810. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  59811. // Compute midtones info.
  59812. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  59813. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  59814. // Compute shadows info.
  59815. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  59816. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  59817. // Compute deltas (neutral is midtones).
  59818. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  59819. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  59820. }
  59821. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  59822. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  59823. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  59824. };
  59825. /**
  59826. * Prepare the list of uniforms associated with the ColorCurves effects.
  59827. * @param uniformsList The list of uniforms used in the effect
  59828. */
  59829. ColorCurves.PrepareUniforms = function (uniformsList) {
  59830. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  59831. };
  59832. /**
  59833. * Returns color grading data based on a hue, density, saturation and exposure value.
  59834. * @param filterHue The hue of the color filter.
  59835. * @param filterDensity The density of the color filter.
  59836. * @param saturation The saturation.
  59837. * @param exposure The exposure.
  59838. * @param result The result data container.
  59839. */
  59840. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  59841. if (hue == null) {
  59842. return;
  59843. }
  59844. hue = ColorCurves.clamp(hue, 0, 360);
  59845. density = ColorCurves.clamp(density, -100, 100);
  59846. saturation = ColorCurves.clamp(saturation, -100, 100);
  59847. exposure = ColorCurves.clamp(exposure, -100, 100);
  59848. // Remap the slider/config filter density with non-linear mapping and also scale by half
  59849. // so that the maximum filter density is only 50% control. This provides fine control
  59850. // for small values and reasonable range.
  59851. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  59852. density *= 0.5;
  59853. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  59854. if (density < 0) {
  59855. density *= -1;
  59856. hue = (hue + 180) % 360;
  59857. }
  59858. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  59859. result.scaleToRef(2, result);
  59860. result.a = 1 + 0.01 * saturation;
  59861. };
  59862. /**
  59863. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  59864. * @param value The input slider value in range [-100,100].
  59865. * @returns Adjusted value.
  59866. */
  59867. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  59868. value /= 100;
  59869. var x = Math.abs(value);
  59870. x = Math.pow(x, 2);
  59871. if (value < 0) {
  59872. x *= -1;
  59873. }
  59874. x *= 100;
  59875. return x;
  59876. };
  59877. /**
  59878. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  59879. * @param hue The hue (H) input.
  59880. * @param saturation The saturation (S) input.
  59881. * @param brightness The brightness (B) input.
  59882. * @result An RGBA color represented as Vector4.
  59883. */
  59884. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  59885. var h = ColorCurves.clamp(hue, 0, 360);
  59886. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  59887. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  59888. if (s === 0) {
  59889. result.r = v;
  59890. result.g = v;
  59891. result.b = v;
  59892. }
  59893. else {
  59894. // sector 0 to 5
  59895. h /= 60;
  59896. var i = Math.floor(h);
  59897. // fractional part of h
  59898. var f = h - i;
  59899. var p = v * (1 - s);
  59900. var q = v * (1 - s * f);
  59901. var t = v * (1 - s * (1 - f));
  59902. switch (i) {
  59903. case 0:
  59904. result.r = v;
  59905. result.g = t;
  59906. result.b = p;
  59907. break;
  59908. case 1:
  59909. result.r = q;
  59910. result.g = v;
  59911. result.b = p;
  59912. break;
  59913. case 2:
  59914. result.r = p;
  59915. result.g = v;
  59916. result.b = t;
  59917. break;
  59918. case 3:
  59919. result.r = p;
  59920. result.g = q;
  59921. result.b = v;
  59922. break;
  59923. case 4:
  59924. result.r = t;
  59925. result.g = p;
  59926. result.b = v;
  59927. break;
  59928. default:
  59929. result.r = v;
  59930. result.g = p;
  59931. result.b = q;
  59932. break;
  59933. }
  59934. }
  59935. result.a = 1;
  59936. };
  59937. /**
  59938. * Returns a value clamped between min and max
  59939. * @param value The value to clamp
  59940. * @param min The minimum of value
  59941. * @param max The maximum of value
  59942. * @returns The clamped value.
  59943. */
  59944. ColorCurves.clamp = function (value, min, max) {
  59945. return Math.min(Math.max(value, min), max);
  59946. };
  59947. /**
  59948. * Clones the current color curve instance.
  59949. * @return The cloned curves
  59950. */
  59951. ColorCurves.prototype.clone = function () {
  59952. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  59953. };
  59954. /**
  59955. * Serializes the current color curve instance to a json representation.
  59956. * @return a JSON representation
  59957. */
  59958. ColorCurves.prototype.serialize = function () {
  59959. return BABYLON.SerializationHelper.Serialize(this);
  59960. };
  59961. /**
  59962. * Parses the color curve from a json representation.
  59963. * @param source the JSON source to parse
  59964. * @return The parsed curves
  59965. */
  59966. ColorCurves.Parse = function (source) {
  59967. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  59968. };
  59969. __decorate([
  59970. BABYLON.serialize()
  59971. ], ColorCurves.prototype, "_globalHue", void 0);
  59972. __decorate([
  59973. BABYLON.serialize()
  59974. ], ColorCurves.prototype, "_globalDensity", void 0);
  59975. __decorate([
  59976. BABYLON.serialize()
  59977. ], ColorCurves.prototype, "_globalSaturation", void 0);
  59978. __decorate([
  59979. BABYLON.serialize()
  59980. ], ColorCurves.prototype, "_globalExposure", void 0);
  59981. __decorate([
  59982. BABYLON.serialize()
  59983. ], ColorCurves.prototype, "_highlightsHue", void 0);
  59984. __decorate([
  59985. BABYLON.serialize()
  59986. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  59987. __decorate([
  59988. BABYLON.serialize()
  59989. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  59990. __decorate([
  59991. BABYLON.serialize()
  59992. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  59993. __decorate([
  59994. BABYLON.serialize()
  59995. ], ColorCurves.prototype, "_midtonesHue", void 0);
  59996. __decorate([
  59997. BABYLON.serialize()
  59998. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  59999. __decorate([
  60000. BABYLON.serialize()
  60001. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  60002. __decorate([
  60003. BABYLON.serialize()
  60004. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  60005. return ColorCurves;
  60006. })();
  60007. BABYLON.ColorCurves = ColorCurves;
  60008. })(BABYLON || (BABYLON = {}));
  60009. var BABYLON;
  60010. (function (BABYLON) {
  60011. /**
  60012. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  60013. * It can help converting any input color in a desired output one. This can then be used to create effects
  60014. * from sepia, black and white to sixties or futuristic rendering...
  60015. *
  60016. * The only supported format is currently 3dl.
  60017. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  60018. */
  60019. var ColorGradingTexture = (function (_super) {
  60020. __extends(ColorGradingTexture, _super);
  60021. /**
  60022. * Instantiates a ColorGradingTexture from the following parameters.
  60023. *
  60024. * @param url The location of the color gradind data (currently only supporting 3dl)
  60025. * @param scene The scene the texture will be used in
  60026. */
  60027. function ColorGradingTexture(url, scene) {
  60028. _super.call(this, scene);
  60029. if (!url) {
  60030. return;
  60031. }
  60032. this._textureMatrix = BABYLON.Matrix.Identity();
  60033. this.name = url;
  60034. this.url = url;
  60035. this.hasAlpha = false;
  60036. this.isCube = false;
  60037. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60038. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60039. this.anisotropicFilteringLevel = 1;
  60040. this._texture = this._getFromCache(url, true);
  60041. if (!this._texture) {
  60042. if (!scene.useDelayedTextureLoading) {
  60043. this.loadTexture();
  60044. }
  60045. else {
  60046. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  60047. }
  60048. }
  60049. }
  60050. /**
  60051. * Returns the texture matrix used in most of the material.
  60052. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  60053. */
  60054. ColorGradingTexture.prototype.getTextureMatrix = function () {
  60055. return this._textureMatrix;
  60056. };
  60057. /**
  60058. * Occurs when the file being loaded is a .3dl LUT file.
  60059. */
  60060. ColorGradingTexture.prototype.load3dlTexture = function () {
  60061. var _this = this;
  60062. var mipLevels = 0;
  60063. var floatArrayView = null;
  60064. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60065. this._texture = texture;
  60066. var callback = function (text) {
  60067. var data;
  60068. var tempData;
  60069. var line;
  60070. var lines = text.split('\n');
  60071. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  60072. var maxColor = 0;
  60073. for (var i = 0; i < lines.length; i++) {
  60074. line = lines[i];
  60075. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  60076. continue;
  60077. if (line.indexOf('#') === 0)
  60078. continue;
  60079. var words = line.split(" ");
  60080. if (size === 0) {
  60081. // Number of space + one
  60082. size = words.length;
  60083. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  60084. tempData = new Float32Array(size * size * size * 4);
  60085. continue;
  60086. }
  60087. if (size != 0) {
  60088. var r = Math.max(parseInt(words[0]), 0);
  60089. var g = Math.max(parseInt(words[1]), 0);
  60090. var b = Math.max(parseInt(words[2]), 0);
  60091. maxColor = Math.max(r, maxColor);
  60092. maxColor = Math.max(g, maxColor);
  60093. maxColor = Math.max(b, maxColor);
  60094. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  60095. tempData[pixelStorageIndex + 0] = r;
  60096. tempData[pixelStorageIndex + 1] = g;
  60097. tempData[pixelStorageIndex + 2] = b;
  60098. tempData[pixelStorageIndex + 3] = 0;
  60099. pixelIndexSlice++;
  60100. if (pixelIndexSlice % size == 0) {
  60101. pixelIndexH++;
  60102. pixelIndexSlice = 0;
  60103. if (pixelIndexH % size == 0) {
  60104. pixelIndexW++;
  60105. pixelIndexH = 0;
  60106. }
  60107. }
  60108. }
  60109. }
  60110. for (var i = 0; i < tempData.length; i++) {
  60111. var value = tempData[i];
  60112. data[i] = (value / maxColor * 255);
  60113. }
  60114. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  60115. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  60116. };
  60117. BABYLON.Tools.LoadFile(this.url, callback);
  60118. return this._texture;
  60119. };
  60120. /**
  60121. * Starts the loading process of the texture.
  60122. */
  60123. ColorGradingTexture.prototype.loadTexture = function () {
  60124. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  60125. this.load3dlTexture();
  60126. }
  60127. };
  60128. /**
  60129. * Clones the color gradind texture.
  60130. */
  60131. ColorGradingTexture.prototype.clone = function () {
  60132. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  60133. // Base texture
  60134. newTexture.level = this.level;
  60135. return newTexture;
  60136. };
  60137. /**
  60138. * Called during delayed load for textures.
  60139. */
  60140. ColorGradingTexture.prototype.delayLoad = function () {
  60141. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  60142. return;
  60143. }
  60144. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  60145. this._texture = this._getFromCache(this.url, true);
  60146. if (!this._texture) {
  60147. this.loadTexture();
  60148. }
  60149. };
  60150. /**
  60151. * Binds the color grading to the shader.
  60152. * @param colorGrading The texture to bind
  60153. * @param effect The effect to bind to
  60154. */
  60155. ColorGradingTexture.Bind = function (colorGrading, effect) {
  60156. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  60157. var x = colorGrading.level; // Texture Level
  60158. var y = colorGrading.getSize().height; // Texture Size example with 8
  60159. var z = y - 1.0; // SizeMinusOne 8 - 1
  60160. var w = 1 / y; // Space of 1 slice 1 / 8
  60161. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  60162. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  60163. 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
  60164. 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
  60165. 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
  60166. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  60167. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  60168. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  60169. };
  60170. /**
  60171. * Prepare the list of uniforms associated with the ColorGrading effects.
  60172. * @param uniformsList The list of uniforms used in the effect
  60173. * @param samplersList The list of samplers used in the effect
  60174. */
  60175. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  60176. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  60177. samplersList.push("cameraColorGrading2DSampler");
  60178. };
  60179. /**
  60180. * Parses a color grading texture serialized by Babylon.
  60181. * @param parsedTexture The texture information being parsedTexture
  60182. * @param scene The scene to load the texture in
  60183. * @param rootUrl The root url of the data assets to load
  60184. * @return A color gradind texture
  60185. */
  60186. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  60187. var texture = null;
  60188. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  60189. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  60190. texture.name = parsedTexture.name;
  60191. texture.level = parsedTexture.level;
  60192. }
  60193. return texture;
  60194. };
  60195. /**
  60196. * Serializes the LUT texture to json format.
  60197. */
  60198. ColorGradingTexture.prototype.serialize = function () {
  60199. if (!this.name) {
  60200. return null;
  60201. }
  60202. var serializationObject = {};
  60203. serializationObject.name = this.name;
  60204. serializationObject.level = this.level;
  60205. serializationObject.customType = "BABYLON.ColorGradingTexture";
  60206. return serializationObject;
  60207. };
  60208. /**
  60209. * Empty line regex stored for GC.
  60210. */
  60211. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  60212. return ColorGradingTexture;
  60213. })(BABYLON.BaseTexture);
  60214. BABYLON.ColorGradingTexture = ColorGradingTexture;
  60215. })(BABYLON || (BABYLON = {}));
  60216. var BABYLON;
  60217. (function (BABYLON) {
  60218. var PBRMaterialDefines = (function (_super) {
  60219. __extends(PBRMaterialDefines, _super);
  60220. function PBRMaterialDefines() {
  60221. _super.call(this);
  60222. this.ALBEDO = false;
  60223. this.AMBIENT = false;
  60224. this.OPACITY = false;
  60225. this.OPACITYRGB = false;
  60226. this.REFLECTION = false;
  60227. this.EMISSIVE = false;
  60228. this.REFLECTIVITY = false;
  60229. this.BUMP = false;
  60230. this.PARALLAX = false;
  60231. this.PARALLAXOCCLUSION = false;
  60232. this.SPECULAROVERALPHA = false;
  60233. this.CLIPPLANE = false;
  60234. this.ALPHATEST = false;
  60235. this.ALPHAFROMALBEDO = false;
  60236. this.POINTSIZE = false;
  60237. this.FOG = false;
  60238. this.SPECULARTERM = false;
  60239. this.OPACITYFRESNEL = false;
  60240. this.EMISSIVEFRESNEL = false;
  60241. this.FRESNEL = false;
  60242. this.NORMAL = false;
  60243. this.UV1 = false;
  60244. this.UV2 = false;
  60245. this.VERTEXCOLOR = false;
  60246. this.VERTEXALPHA = false;
  60247. this.NUM_BONE_INFLUENCERS = 0;
  60248. this.BonesPerMesh = 0;
  60249. this.INSTANCES = false;
  60250. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  60251. this.MICROSURFACEAUTOMATIC = false;
  60252. this.EMISSIVEASILLUMINATION = false;
  60253. this.LINKEMISSIVEWITHALBEDO = false;
  60254. this.LIGHTMAP = false;
  60255. this.USELIGHTMAPASSHADOWMAP = false;
  60256. this.REFLECTIONMAP_3D = false;
  60257. this.REFLECTIONMAP_SPHERICAL = false;
  60258. this.REFLECTIONMAP_PLANAR = false;
  60259. this.REFLECTIONMAP_CUBIC = false;
  60260. this.REFLECTIONMAP_PROJECTION = false;
  60261. this.REFLECTIONMAP_SKYBOX = false;
  60262. this.REFLECTIONMAP_EXPLICIT = false;
  60263. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  60264. this.INVERTCUBICMAP = false;
  60265. this.LOGARITHMICDEPTH = false;
  60266. this.CAMERATONEMAP = false;
  60267. this.CAMERACONTRAST = false;
  60268. this.CAMERACOLORGRADING = false;
  60269. this.CAMERACOLORCURVES = false;
  60270. this.OVERLOADEDVALUES = false;
  60271. this.OVERLOADEDSHADOWVALUES = false;
  60272. this.USESPHERICALFROMREFLECTIONMAP = false;
  60273. this.REFRACTION = false;
  60274. this.REFRACTIONMAP_3D = false;
  60275. this.LINKREFRACTIONTOTRANSPARENCY = false;
  60276. this.REFRACTIONMAPINLINEARSPACE = false;
  60277. this.LODBASEDMICROSFURACE = false;
  60278. this.USEPHYSICALLIGHTFALLOFF = false;
  60279. this.RADIANCEOVERALPHA = false;
  60280. this.USEPMREMREFLECTION = false;
  60281. this.USEPMREMREFRACTION = false;
  60282. this.OPENGLNORMALMAP = false;
  60283. this.INVERTNORMALMAPX = false;
  60284. this.INVERTNORMALMAPY = false;
  60285. this.SHADOWFULLFLOAT = false;
  60286. this.rebuild();
  60287. }
  60288. return PBRMaterialDefines;
  60289. })(BABYLON.MaterialDefines);
  60290. /**
  60291. * The Physically based material of BJS.
  60292. *
  60293. * This offers the main features of a standard PBR material.
  60294. * For more information, please refer to the documentation :
  60295. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  60296. */
  60297. var PBRMaterial = (function (_super) {
  60298. __extends(PBRMaterial, _super);
  60299. /**
  60300. * Instantiates a new PBRMaterial instance.
  60301. *
  60302. * @param name The material name
  60303. * @param scene The scene the material will be use in.
  60304. */
  60305. function PBRMaterial(name, scene) {
  60306. var _this = this;
  60307. _super.call(this, name, scene);
  60308. /**
  60309. * Intensity of the direct lights e.g. the four lights available in your scene.
  60310. * This impacts both the direct diffuse and specular highlights.
  60311. */
  60312. this.directIntensity = 1.0;
  60313. /**
  60314. * Intensity of the emissive part of the material.
  60315. * This helps controlling the emissive effect without modifying the emissive color.
  60316. */
  60317. this.emissiveIntensity = 1.0;
  60318. /**
  60319. * Intensity of the environment e.g. how much the environment will light the object
  60320. * either through harmonics for rough material or through the refelction for shiny ones.
  60321. */
  60322. this.environmentIntensity = 1.0;
  60323. /**
  60324. * This is a special control allowing the reduction of the specular highlights coming from the
  60325. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  60326. */
  60327. this.specularIntensity = 1.0;
  60328. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  60329. /**
  60330. * Debug Control allowing disabling the bump map on this material.
  60331. */
  60332. this.disableBumpMap = false;
  60333. /**
  60334. * Debug Control helping enforcing or dropping the darkness of shadows.
  60335. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  60336. */
  60337. this.overloadedShadowIntensity = 1.0;
  60338. /**
  60339. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  60340. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  60341. */
  60342. this.overloadedShadeIntensity = 1.0;
  60343. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  60344. /**
  60345. * The camera exposure used on this material.
  60346. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  60347. * This corresponds to a photographic exposure.
  60348. */
  60349. this.cameraExposure = 1.0;
  60350. /**
  60351. * The camera contrast used on this material.
  60352. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  60353. */
  60354. this.cameraContrast = 1.0;
  60355. /**
  60356. * Color Grading 2D Lookup Texture.
  60357. * This allows special effects like sepia, black and white to sixties rendering style.
  60358. */
  60359. this.cameraColorGradingTexture = null;
  60360. /**
  60361. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  60362. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  60363. * 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;
  60364. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  60365. */
  60366. this.cameraColorCurves = null;
  60367. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  60368. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  60369. /**
  60370. * Debug Control allowing to overload the ambient color.
  60371. * This as to be use with the overloadedAmbientIntensity parameter.
  60372. */
  60373. this.overloadedAmbient = BABYLON.Color3.White();
  60374. /**
  60375. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  60376. */
  60377. this.overloadedAmbientIntensity = 0.0;
  60378. /**
  60379. * Debug Control allowing to overload the albedo color.
  60380. * This as to be use with the overloadedAlbedoIntensity parameter.
  60381. */
  60382. this.overloadedAlbedo = BABYLON.Color3.White();
  60383. /**
  60384. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  60385. */
  60386. this.overloadedAlbedoIntensity = 0.0;
  60387. /**
  60388. * Debug Control allowing to overload the reflectivity color.
  60389. * This as to be use with the overloadedReflectivityIntensity parameter.
  60390. */
  60391. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  60392. /**
  60393. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  60394. */
  60395. this.overloadedReflectivityIntensity = 0.0;
  60396. /**
  60397. * Debug Control allowing to overload the emissive color.
  60398. * This as to be use with the overloadedEmissiveIntensity parameter.
  60399. */
  60400. this.overloadedEmissive = BABYLON.Color3.White();
  60401. /**
  60402. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  60403. */
  60404. this.overloadedEmissiveIntensity = 0.0;
  60405. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  60406. /**
  60407. * Debug Control allowing to overload the reflection color.
  60408. * This as to be use with the overloadedReflectionIntensity parameter.
  60409. */
  60410. this.overloadedReflection = BABYLON.Color3.White();
  60411. /**
  60412. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  60413. */
  60414. this.overloadedReflectionIntensity = 0.0;
  60415. /**
  60416. * Debug Control allowing to overload the microsurface.
  60417. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  60418. */
  60419. this.overloadedMicroSurface = 0.0;
  60420. /**
  60421. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  60422. */
  60423. this.overloadedMicroSurfaceIntensity = 0.0;
  60424. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  60425. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  60426. /**
  60427. * AKA Diffuse Color in other nomenclature.
  60428. */
  60429. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  60430. /**
  60431. * AKA Specular Color in other nomenclature.
  60432. */
  60433. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  60434. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  60435. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  60436. /**
  60437. * AKA Glossiness in other nomenclature.
  60438. */
  60439. this.microSurface = 0.9;
  60440. /**
  60441. * source material index of refraction (IOR)' / 'destination material IOR.
  60442. */
  60443. this.indexOfRefraction = 0.66;
  60444. /**
  60445. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  60446. */
  60447. this.invertRefractionY = false;
  60448. /**
  60449. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  60450. * Materials half opaque for instance using refraction could benefit from this control.
  60451. */
  60452. this.linkRefractionWithTransparency = false;
  60453. /**
  60454. * The emissive and albedo are linked to never be more than one (Energy conservation).
  60455. */
  60456. this.linkEmissiveWithAlbedo = false;
  60457. this.useLightmapAsShadowmap = false;
  60458. /**
  60459. * In this mode, the emissive informtaion will always be added to the lighting once.
  60460. * A light for instance can be thought as emissive.
  60461. */
  60462. this.useEmissiveAsIllumination = false;
  60463. /**
  60464. * Secifies that the alpha is coming form the albedo channel alpha channel.
  60465. */
  60466. this.useAlphaFromAlbedoTexture = false;
  60467. /**
  60468. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  60469. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  60470. */
  60471. this.useSpecularOverAlpha = true;
  60472. /**
  60473. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  60474. */
  60475. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  60476. /**
  60477. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  60478. * The material will try to infer what glossiness each pixel should be.
  60479. */
  60480. this.useAutoMicroSurfaceFromReflectivityMap = false;
  60481. /**
  60482. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  60483. * the creation of the material.
  60484. */
  60485. this.useScalarInLinearSpace = false;
  60486. /**
  60487. * BJS is using an harcoded light falloff based on a manually sets up range.
  60488. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  60489. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  60490. */
  60491. this.usePhysicalLightFalloff = true;
  60492. /**
  60493. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  60494. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  60495. */
  60496. this.useRadianceOverAlpha = true;
  60497. /**
  60498. * Allows using the bump map in parallax mode.
  60499. */
  60500. this.useParallax = false;
  60501. /**
  60502. * Allows using the bump map in parallax occlusion mode.
  60503. */
  60504. this.useParallaxOcclusion = false;
  60505. /**
  60506. * Controls the scale bias of the parallax mode.
  60507. */
  60508. this.parallaxScaleBias = 0.05;
  60509. /**
  60510. * If sets to true, disables all the lights affecting the material.
  60511. */
  60512. this.disableLighting = false;
  60513. /**
  60514. * Number of Simultaneous lights allowed on the material.
  60515. */
  60516. this.maxSimultaneousLights = 4;
  60517. /**
  60518. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  60519. */
  60520. this.invertNormalMapX = false;
  60521. /**
  60522. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  60523. */
  60524. this.invertNormalMapY = false;
  60525. this._renderTargets = new BABYLON.SmartArray(16);
  60526. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  60527. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  60528. this._tempColor = new BABYLON.Color3();
  60529. this._defines = new PBRMaterialDefines();
  60530. this._cachedDefines = new PBRMaterialDefines();
  60531. this._myScene = null;
  60532. this._myShadowGenerator = null;
  60533. this._cachedDefines.BonesPerMesh = -1;
  60534. this.getRenderTargetTextures = function () {
  60535. _this._renderTargets.reset();
  60536. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  60537. _this._renderTargets.push(_this.reflectionTexture);
  60538. }
  60539. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  60540. _this._renderTargets.push(_this.refractionTexture);
  60541. }
  60542. return _this._renderTargets;
  60543. };
  60544. }
  60545. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  60546. get: function () {
  60547. return this._useLogarithmicDepth;
  60548. },
  60549. set: function (value) {
  60550. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  60551. },
  60552. enumerable: true,
  60553. configurable: true
  60554. });
  60555. PBRMaterial.prototype.needAlphaBlending = function () {
  60556. if (this.linkRefractionWithTransparency) {
  60557. return false;
  60558. }
  60559. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  60560. };
  60561. PBRMaterial.prototype.needAlphaTesting = function () {
  60562. if (this.linkRefractionWithTransparency) {
  60563. return false;
  60564. }
  60565. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  60566. };
  60567. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  60568. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  60569. };
  60570. PBRMaterial.prototype.getAlphaTestTexture = function () {
  60571. return this.albedoTexture;
  60572. };
  60573. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  60574. if (!mesh) {
  60575. return true;
  60576. }
  60577. if (this._defines.INSTANCES !== useInstances) {
  60578. return false;
  60579. }
  60580. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  60581. return true;
  60582. }
  60583. return false;
  60584. };
  60585. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  60586. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  60587. };
  60588. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  60589. if (!useScalarInLinear) {
  60590. color.toLinearSpaceToRef(ref);
  60591. }
  60592. else {
  60593. ref.r = color.r;
  60594. ref.g = color.g;
  60595. ref.b = color.b;
  60596. }
  60597. };
  60598. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  60599. var lightIndex = 0;
  60600. var depthValuesAlreadySet = false;
  60601. for (var index = 0; index < scene.lights.length; index++) {
  60602. var light = scene.lights[index];
  60603. if (!light.isEnabled()) {
  60604. continue;
  60605. }
  60606. if (!light.canAffectMesh(mesh)) {
  60607. continue;
  60608. }
  60609. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  60610. // GAMMA CORRECTION.
  60611. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  60612. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  60613. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  60614. if (defines["SPECULARTERM"]) {
  60615. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  60616. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  60617. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  60618. }
  60619. // Shadows
  60620. if (scene.shadowsEnabled) {
  60621. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  60622. }
  60623. lightIndex++;
  60624. if (lightIndex === maxSimultaneousLights)
  60625. break;
  60626. }
  60627. };
  60628. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  60629. if (this.checkReadyOnlyOnce) {
  60630. if (this._wasPreviouslyReady) {
  60631. return true;
  60632. }
  60633. }
  60634. var scene = this.getScene();
  60635. if (!this.checkReadyOnEveryCall) {
  60636. if (this._renderId === scene.getRenderId()) {
  60637. if (this._checkCache(scene, mesh, useInstances)) {
  60638. return true;
  60639. }
  60640. }
  60641. }
  60642. var engine = scene.getEngine();
  60643. var needNormals = false;
  60644. var needUVs = false;
  60645. this._defines.reset();
  60646. if (scene.texturesEnabled) {
  60647. // Textures
  60648. if (scene.texturesEnabled) {
  60649. if (scene.getEngine().getCaps().textureLOD) {
  60650. this._defines.LODBASEDMICROSFURACE = true;
  60651. }
  60652. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  60653. if (!this.albedoTexture.isReady()) {
  60654. return false;
  60655. }
  60656. else {
  60657. needUVs = true;
  60658. this._defines.ALBEDO = true;
  60659. }
  60660. }
  60661. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  60662. if (!this.ambientTexture.isReady()) {
  60663. return false;
  60664. }
  60665. else {
  60666. needUVs = true;
  60667. this._defines.AMBIENT = true;
  60668. }
  60669. }
  60670. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  60671. if (!this.opacityTexture.isReady()) {
  60672. return false;
  60673. }
  60674. else {
  60675. needUVs = true;
  60676. this._defines.OPACITY = true;
  60677. if (this.opacityTexture.getAlphaFromRGB) {
  60678. this._defines.OPACITYRGB = true;
  60679. }
  60680. }
  60681. }
  60682. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  60683. if (!this.reflectionTexture.isReady()) {
  60684. return false;
  60685. }
  60686. else {
  60687. needNormals = true;
  60688. this._defines.REFLECTION = true;
  60689. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  60690. this._defines.INVERTCUBICMAP = true;
  60691. }
  60692. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  60693. switch (this.reflectionTexture.coordinatesMode) {
  60694. case BABYLON.Texture.CUBIC_MODE:
  60695. case BABYLON.Texture.INVCUBIC_MODE:
  60696. this._defines.REFLECTIONMAP_CUBIC = true;
  60697. break;
  60698. case BABYLON.Texture.EXPLICIT_MODE:
  60699. this._defines.REFLECTIONMAP_EXPLICIT = true;
  60700. break;
  60701. case BABYLON.Texture.PLANAR_MODE:
  60702. this._defines.REFLECTIONMAP_PLANAR = true;
  60703. break;
  60704. case BABYLON.Texture.PROJECTION_MODE:
  60705. this._defines.REFLECTIONMAP_PROJECTION = true;
  60706. break;
  60707. case BABYLON.Texture.SKYBOX_MODE:
  60708. this._defines.REFLECTIONMAP_SKYBOX = true;
  60709. break;
  60710. case BABYLON.Texture.SPHERICAL_MODE:
  60711. this._defines.REFLECTIONMAP_SPHERICAL = true;
  60712. break;
  60713. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  60714. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  60715. break;
  60716. }
  60717. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  60718. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  60719. needNormals = true;
  60720. if (this.reflectionTexture.isPMREM) {
  60721. this._defines.USEPMREMREFLECTION = true;
  60722. }
  60723. }
  60724. }
  60725. }
  60726. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  60727. if (!this.lightmapTexture.isReady()) {
  60728. return false;
  60729. }
  60730. else {
  60731. needUVs = true;
  60732. this._defines.LIGHTMAP = true;
  60733. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  60734. }
  60735. }
  60736. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  60737. if (!this.emissiveTexture.isReady()) {
  60738. return false;
  60739. }
  60740. else {
  60741. needUVs = true;
  60742. this._defines.EMISSIVE = true;
  60743. }
  60744. }
  60745. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  60746. if (!this.reflectivityTexture.isReady()) {
  60747. return false;
  60748. }
  60749. else {
  60750. needUVs = true;
  60751. this._defines.REFLECTIVITY = true;
  60752. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  60753. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  60754. }
  60755. }
  60756. }
  60757. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  60758. if (!this.bumpTexture.isReady()) {
  60759. return false;
  60760. }
  60761. else {
  60762. needUVs = true;
  60763. this._defines.BUMP = true;
  60764. if (this.useParallax) {
  60765. this._defines.PARALLAX = true;
  60766. if (this.useParallaxOcclusion) {
  60767. this._defines.PARALLAXOCCLUSION = true;
  60768. }
  60769. }
  60770. if (this.invertNormalMapX) {
  60771. this._defines.INVERTNORMALMAPX = true;
  60772. }
  60773. if (this.invertNormalMapY) {
  60774. this._defines.INVERTNORMALMAPY = true;
  60775. }
  60776. }
  60777. }
  60778. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  60779. if (!this.refractionTexture.isReady()) {
  60780. return false;
  60781. }
  60782. else {
  60783. needUVs = true;
  60784. this._defines.REFRACTION = true;
  60785. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  60786. if (this.linkRefractionWithTransparency) {
  60787. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  60788. }
  60789. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  60790. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  60791. if (this.refractionTexture.isPMREM) {
  60792. this._defines.USEPMREMREFRACTION = true;
  60793. }
  60794. }
  60795. }
  60796. }
  60797. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  60798. if (!this.cameraColorGradingTexture.isReady()) {
  60799. return false;
  60800. }
  60801. else {
  60802. this._defines.CAMERACOLORGRADING = true;
  60803. }
  60804. }
  60805. }
  60806. // Effect
  60807. if (scene.clipPlane) {
  60808. this._defines.CLIPPLANE = true;
  60809. }
  60810. if (engine.getAlphaTesting()) {
  60811. this._defines.ALPHATEST = true;
  60812. }
  60813. if (this._shouldUseAlphaFromAlbedoTexture()) {
  60814. this._defines.ALPHAFROMALBEDO = true;
  60815. }
  60816. if (this.useEmissiveAsIllumination) {
  60817. this._defines.EMISSIVEASILLUMINATION = true;
  60818. }
  60819. if (this.linkEmissiveWithAlbedo) {
  60820. this._defines.LINKEMISSIVEWITHALBEDO = true;
  60821. }
  60822. if (this.useLogarithmicDepth) {
  60823. this._defines.LOGARITHMICDEPTH = true;
  60824. }
  60825. if (this.cameraContrast != 1) {
  60826. this._defines.CAMERACONTRAST = true;
  60827. }
  60828. if (this.cameraExposure != 1) {
  60829. this._defines.CAMERATONEMAP = true;
  60830. }
  60831. if (this.cameraColorCurves) {
  60832. this._defines.CAMERACOLORCURVES = true;
  60833. }
  60834. if (this.overloadedShadeIntensity != 1 ||
  60835. this.overloadedShadowIntensity != 1) {
  60836. this._defines.OVERLOADEDSHADOWVALUES = true;
  60837. }
  60838. if (this.overloadedMicroSurfaceIntensity > 0 ||
  60839. this.overloadedEmissiveIntensity > 0 ||
  60840. this.overloadedReflectivityIntensity > 0 ||
  60841. this.overloadedAlbedoIntensity > 0 ||
  60842. this.overloadedAmbientIntensity > 0 ||
  60843. this.overloadedReflectionIntensity > 0) {
  60844. this._defines.OVERLOADEDVALUES = true;
  60845. }
  60846. // Point size
  60847. if (this.pointsCloud || scene.forcePointsCloud) {
  60848. this._defines.POINTSIZE = true;
  60849. }
  60850. // Fog
  60851. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  60852. this._defines.FOG = true;
  60853. }
  60854. if (scene.lightsEnabled && !this.disableLighting) {
  60855. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  60856. }
  60857. if (BABYLON.StandardMaterial.FresnelEnabled) {
  60858. // Fresnel
  60859. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  60860. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  60861. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  60862. this._defines.OPACITYFRESNEL = true;
  60863. }
  60864. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  60865. this._defines.EMISSIVEFRESNEL = true;
  60866. }
  60867. needNormals = true;
  60868. this._defines.FRESNEL = true;
  60869. }
  60870. }
  60871. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  60872. this._defines.SPECULAROVERALPHA = true;
  60873. }
  60874. if (this.usePhysicalLightFalloff) {
  60875. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  60876. }
  60877. if (this.useRadianceOverAlpha) {
  60878. this._defines.RADIANCEOVERALPHA = true;
  60879. }
  60880. // Attribs
  60881. if (mesh) {
  60882. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  60883. this._defines.NORMAL = true;
  60884. }
  60885. if (needUVs) {
  60886. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60887. this._defines.UV1 = true;
  60888. }
  60889. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60890. this._defines.UV2 = true;
  60891. }
  60892. }
  60893. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  60894. this._defines.VERTEXCOLOR = true;
  60895. if (mesh.hasVertexAlpha) {
  60896. this._defines.VERTEXALPHA = true;
  60897. }
  60898. }
  60899. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60900. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  60901. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  60902. }
  60903. // Instances
  60904. if (useInstances) {
  60905. this._defines.INSTANCES = true;
  60906. }
  60907. }
  60908. // Get correct effect
  60909. if (!this._defines.isEqual(this._cachedDefines)) {
  60910. this._defines.cloneTo(this._cachedDefines);
  60911. scene.resetCachedMaterial();
  60912. // Fallbacks
  60913. var fallbacks = new BABYLON.EffectFallbacks();
  60914. if (this._defines.REFLECTION) {
  60915. fallbacks.addFallback(0, "REFLECTION");
  60916. }
  60917. if (this._defines.REFRACTION) {
  60918. fallbacks.addFallback(0, "REFRACTION");
  60919. }
  60920. if (this._defines.REFLECTIVITY) {
  60921. fallbacks.addFallback(0, "REFLECTIVITY");
  60922. }
  60923. if (this._defines.BUMP) {
  60924. fallbacks.addFallback(0, "BUMP");
  60925. }
  60926. if (this._defines.PARALLAX) {
  60927. fallbacks.addFallback(1, "PARALLAX");
  60928. }
  60929. if (this._defines.PARALLAXOCCLUSION) {
  60930. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  60931. }
  60932. if (this._defines.SPECULAROVERALPHA) {
  60933. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  60934. }
  60935. if (this._defines.FOG) {
  60936. fallbacks.addFallback(1, "FOG");
  60937. }
  60938. if (this._defines.POINTSIZE) {
  60939. fallbacks.addFallback(0, "POINTSIZE");
  60940. }
  60941. if (this._defines.LOGARITHMICDEPTH) {
  60942. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  60943. }
  60944. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  60945. if (this._defines.SPECULARTERM) {
  60946. fallbacks.addFallback(0, "SPECULARTERM");
  60947. }
  60948. if (this._defines.OPACITYFRESNEL) {
  60949. fallbacks.addFallback(1, "OPACITYFRESNEL");
  60950. }
  60951. if (this._defines.EMISSIVEFRESNEL) {
  60952. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  60953. }
  60954. if (this._defines.FRESNEL) {
  60955. fallbacks.addFallback(3, "FRESNEL");
  60956. }
  60957. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  60958. fallbacks.addCPUSkinningFallback(0, mesh);
  60959. }
  60960. //Attributes
  60961. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60962. if (this._defines.NORMAL) {
  60963. attribs.push(BABYLON.VertexBuffer.NormalKind);
  60964. }
  60965. if (this._defines.UV1) {
  60966. attribs.push(BABYLON.VertexBuffer.UVKind);
  60967. }
  60968. if (this._defines.UV2) {
  60969. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60970. }
  60971. if (this._defines.VERTEXCOLOR) {
  60972. attribs.push(BABYLON.VertexBuffer.ColorKind);
  60973. }
  60974. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  60975. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  60976. // Legacy browser patch
  60977. var shaderName = "pbr";
  60978. if (!scene.getEngine().getCaps().standardDerivatives) {
  60979. shaderName = "legacypbr";
  60980. }
  60981. var join = this._defines.toString();
  60982. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  60983. "vFogInfos", "vFogColor", "pointSize",
  60984. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  60985. "mBones",
  60986. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  60987. "depthValues",
  60988. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  60989. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  60990. "logarithmicDepthConstant",
  60991. "vSphericalX", "vSphericalY", "vSphericalZ",
  60992. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  60993. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  60994. "vMicrosurfaceTextureLods",
  60995. "vCameraInfos"
  60996. ];
  60997. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  60998. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  60999. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  61000. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  61001. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  61002. }
  61003. if (!this._effect.isReady()) {
  61004. return false;
  61005. }
  61006. this._renderId = scene.getRenderId();
  61007. this._wasPreviouslyReady = true;
  61008. if (mesh) {
  61009. if (!mesh._materialDefines) {
  61010. mesh._materialDefines = new PBRMaterialDefines();
  61011. }
  61012. this._defines.cloneTo(mesh._materialDefines);
  61013. }
  61014. return true;
  61015. };
  61016. PBRMaterial.prototype.unbind = function () {
  61017. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  61018. this._effect.setTexture("reflection2DSampler", null);
  61019. }
  61020. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  61021. this._effect.setTexture("refraction2DSampler", null);
  61022. }
  61023. _super.prototype.unbind.call(this);
  61024. };
  61025. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  61026. this._effect.setMatrix("world", world);
  61027. };
  61028. PBRMaterial.prototype.bind = function (world, mesh) {
  61029. this._myScene = this.getScene();
  61030. // Matrices
  61031. this.bindOnlyWorldMatrix(world);
  61032. // Bones
  61033. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  61034. if (this._myScene.getCachedMaterial() !== this) {
  61035. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  61036. if (BABYLON.StandardMaterial.FresnelEnabled) {
  61037. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  61038. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  61039. }
  61040. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  61041. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  61042. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  61043. }
  61044. }
  61045. // Textures
  61046. if (this._myScene.texturesEnabled) {
  61047. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  61048. this._effect.setTexture("albedoSampler", this.albedoTexture);
  61049. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  61050. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  61051. }
  61052. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  61053. this._effect.setTexture("ambientSampler", this.ambientTexture);
  61054. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  61055. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  61056. }
  61057. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  61058. this._effect.setTexture("opacitySampler", this.opacityTexture);
  61059. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  61060. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  61061. }
  61062. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  61063. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  61064. if (this.reflectionTexture.isCube) {
  61065. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  61066. }
  61067. else {
  61068. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  61069. }
  61070. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  61071. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  61072. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  61073. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  61074. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  61075. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  61076. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  61077. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  61078. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  61079. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  61080. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  61081. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  61082. }
  61083. }
  61084. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  61085. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  61086. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  61087. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  61088. }
  61089. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  61090. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  61091. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  61092. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  61093. }
  61094. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  61095. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  61096. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  61097. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  61098. }
  61099. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  61100. this._effect.setTexture("bumpSampler", this.bumpTexture);
  61101. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  61102. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  61103. }
  61104. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  61105. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  61106. var depth = 1.0;
  61107. if (this.refractionTexture.isCube) {
  61108. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  61109. }
  61110. else {
  61111. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  61112. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  61113. if (this.refractionTexture.depth) {
  61114. depth = this.refractionTexture.depth;
  61115. }
  61116. }
  61117. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  61118. }
  61119. if ((this.reflectionTexture || this.refractionTexture)) {
  61120. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  61121. }
  61122. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  61123. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  61124. }
  61125. }
  61126. // Clip plane
  61127. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  61128. // Point size
  61129. if (this.pointsCloud) {
  61130. this._effect.setFloat("pointSize", this.pointSize);
  61131. }
  61132. // Colors
  61133. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  61134. // GAMMA CORRECTION.
  61135. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  61136. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  61137. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  61138. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  61139. // GAMMA CORRECTION.
  61140. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  61141. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  61142. // GAMMA CORRECTION.
  61143. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  61144. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  61145. }
  61146. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  61147. // GAMMA CORRECTION.
  61148. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  61149. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  61150. // Lights
  61151. if (this._myScene.lightsEnabled && !this.disableLighting) {
  61152. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  61153. }
  61154. // View
  61155. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  61156. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  61157. }
  61158. // Fog
  61159. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  61160. this._lightingInfos.x = this.directIntensity;
  61161. this._lightingInfos.y = this.emissiveIntensity;
  61162. this._lightingInfos.z = this.environmentIntensity;
  61163. this._lightingInfos.w = this.specularIntensity;
  61164. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  61165. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  61166. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  61167. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  61168. this._cameraInfos.x = this.cameraExposure;
  61169. this._cameraInfos.y = this.cameraContrast;
  61170. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  61171. if (this.cameraColorCurves) {
  61172. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  61173. }
  61174. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  61175. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  61176. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  61177. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  61178. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  61179. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  61180. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  61181. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  61182. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  61183. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  61184. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  61185. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  61186. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  61187. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  61188. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  61189. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  61190. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  61191. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  61192. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  61193. // Log. depth
  61194. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  61195. }
  61196. _super.prototype.bind.call(this, world, mesh);
  61197. this._myScene = null;
  61198. };
  61199. PBRMaterial.prototype.getAnimatables = function () {
  61200. var results = [];
  61201. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  61202. results.push(this.albedoTexture);
  61203. }
  61204. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  61205. results.push(this.ambientTexture);
  61206. }
  61207. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  61208. results.push(this.opacityTexture);
  61209. }
  61210. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  61211. results.push(this.reflectionTexture);
  61212. }
  61213. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  61214. results.push(this.emissiveTexture);
  61215. }
  61216. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  61217. results.push(this.reflectivityTexture);
  61218. }
  61219. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  61220. results.push(this.bumpTexture);
  61221. }
  61222. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  61223. results.push(this.lightmapTexture);
  61224. }
  61225. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  61226. results.push(this.refractionTexture);
  61227. }
  61228. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  61229. results.push(this.cameraColorGradingTexture);
  61230. }
  61231. return results;
  61232. };
  61233. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  61234. if (forceDisposeTextures) {
  61235. if (this.albedoTexture) {
  61236. this.albedoTexture.dispose();
  61237. }
  61238. if (this.ambientTexture) {
  61239. this.ambientTexture.dispose();
  61240. }
  61241. if (this.opacityTexture) {
  61242. this.opacityTexture.dispose();
  61243. }
  61244. if (this.reflectionTexture) {
  61245. this.reflectionTexture.dispose();
  61246. }
  61247. if (this.emissiveTexture) {
  61248. this.emissiveTexture.dispose();
  61249. }
  61250. if (this.reflectivityTexture) {
  61251. this.reflectivityTexture.dispose();
  61252. }
  61253. if (this.bumpTexture) {
  61254. this.bumpTexture.dispose();
  61255. }
  61256. if (this.lightmapTexture) {
  61257. this.lightmapTexture.dispose();
  61258. }
  61259. if (this.refractionTexture) {
  61260. this.refractionTexture.dispose();
  61261. }
  61262. if (this.cameraColorGradingTexture) {
  61263. this.cameraColorGradingTexture.dispose();
  61264. }
  61265. }
  61266. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  61267. };
  61268. PBRMaterial.prototype.clone = function (name) {
  61269. var _this = this;
  61270. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  61271. };
  61272. PBRMaterial.prototype.serialize = function () {
  61273. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61274. serializationObject.customType = "BABYLON.PBRMaterial";
  61275. return serializationObject;
  61276. };
  61277. // Statics
  61278. PBRMaterial.Parse = function (source, scene, rootUrl) {
  61279. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  61280. };
  61281. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  61282. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  61283. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  61284. PBRMaterial._scaledReflection = new BABYLON.Color3();
  61285. __decorate([
  61286. BABYLON.serialize()
  61287. ], PBRMaterial.prototype, "directIntensity", void 0);
  61288. __decorate([
  61289. BABYLON.serialize()
  61290. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  61291. __decorate([
  61292. BABYLON.serialize()
  61293. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  61294. __decorate([
  61295. BABYLON.serialize()
  61296. ], PBRMaterial.prototype, "specularIntensity", void 0);
  61297. __decorate([
  61298. BABYLON.serialize()
  61299. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  61300. __decorate([
  61301. BABYLON.serialize()
  61302. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  61303. __decorate([
  61304. BABYLON.serialize()
  61305. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  61306. __decorate([
  61307. BABYLON.serialize()
  61308. ], PBRMaterial.prototype, "cameraExposure", void 0);
  61309. __decorate([
  61310. BABYLON.serialize()
  61311. ], PBRMaterial.prototype, "cameraContrast", void 0);
  61312. __decorate([
  61313. BABYLON.serializeAsTexture()
  61314. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  61315. __decorate([
  61316. BABYLON.serializeAsColorCurves()
  61317. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  61318. __decorate([
  61319. BABYLON.serializeAsColor3()
  61320. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  61321. __decorate([
  61322. BABYLON.serialize()
  61323. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  61324. __decorate([
  61325. BABYLON.serializeAsColor3()
  61326. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  61327. __decorate([
  61328. BABYLON.serialize()
  61329. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  61330. __decorate([
  61331. BABYLON.serializeAsColor3()
  61332. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  61333. __decorate([
  61334. BABYLON.serialize()
  61335. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  61336. __decorate([
  61337. BABYLON.serializeAsColor3()
  61338. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  61339. __decorate([
  61340. BABYLON.serialize()
  61341. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  61342. __decorate([
  61343. BABYLON.serializeAsColor3()
  61344. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  61345. __decorate([
  61346. BABYLON.serialize()
  61347. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  61348. __decorate([
  61349. BABYLON.serialize()
  61350. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  61351. __decorate([
  61352. BABYLON.serialize()
  61353. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  61354. __decorate([
  61355. BABYLON.serializeAsTexture()
  61356. ], PBRMaterial.prototype, "albedoTexture", void 0);
  61357. __decorate([
  61358. BABYLON.serializeAsTexture()
  61359. ], PBRMaterial.prototype, "ambientTexture", void 0);
  61360. __decorate([
  61361. BABYLON.serializeAsTexture()
  61362. ], PBRMaterial.prototype, "opacityTexture", void 0);
  61363. __decorate([
  61364. BABYLON.serializeAsTexture()
  61365. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  61366. __decorate([
  61367. BABYLON.serializeAsTexture()
  61368. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  61369. __decorate([
  61370. BABYLON.serializeAsTexture()
  61371. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  61372. __decorate([
  61373. BABYLON.serializeAsTexture()
  61374. ], PBRMaterial.prototype, "bumpTexture", void 0);
  61375. __decorate([
  61376. BABYLON.serializeAsTexture()
  61377. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  61378. __decorate([
  61379. BABYLON.serializeAsTexture()
  61380. ], PBRMaterial.prototype, "refractionTexture", void 0);
  61381. __decorate([
  61382. BABYLON.serializeAsColor3("ambient")
  61383. ], PBRMaterial.prototype, "ambientColor", void 0);
  61384. __decorate([
  61385. BABYLON.serializeAsColor3("albedo")
  61386. ], PBRMaterial.prototype, "albedoColor", void 0);
  61387. __decorate([
  61388. BABYLON.serializeAsColor3("reflectivity")
  61389. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  61390. __decorate([
  61391. BABYLON.serializeAsColor3("reflection")
  61392. ], PBRMaterial.prototype, "reflectionColor", void 0);
  61393. __decorate([
  61394. BABYLON.serializeAsColor3("emissive")
  61395. ], PBRMaterial.prototype, "emissiveColor", void 0);
  61396. __decorate([
  61397. BABYLON.serialize()
  61398. ], PBRMaterial.prototype, "microSurface", void 0);
  61399. __decorate([
  61400. BABYLON.serialize()
  61401. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  61402. __decorate([
  61403. BABYLON.serialize()
  61404. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  61405. __decorate([
  61406. BABYLON.serializeAsFresnelParameters()
  61407. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  61408. __decorate([
  61409. BABYLON.serializeAsFresnelParameters()
  61410. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  61411. __decorate([
  61412. BABYLON.serialize()
  61413. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  61414. __decorate([
  61415. BABYLON.serialize()
  61416. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  61417. __decorate([
  61418. BABYLON.serialize()
  61419. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  61420. __decorate([
  61421. BABYLON.serialize()
  61422. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  61423. __decorate([
  61424. BABYLON.serialize()
  61425. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  61426. __decorate([
  61427. BABYLON.serialize()
  61428. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  61429. __decorate([
  61430. BABYLON.serialize()
  61431. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  61432. __decorate([
  61433. BABYLON.serialize()
  61434. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  61435. __decorate([
  61436. BABYLON.serialize()
  61437. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  61438. __decorate([
  61439. BABYLON.serialize()
  61440. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  61441. __decorate([
  61442. BABYLON.serialize()
  61443. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  61444. __decorate([
  61445. BABYLON.serialize()
  61446. ], PBRMaterial.prototype, "useParallax", void 0);
  61447. __decorate([
  61448. BABYLON.serialize()
  61449. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  61450. __decorate([
  61451. BABYLON.serialize()
  61452. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  61453. __decorate([
  61454. BABYLON.serialize()
  61455. ], PBRMaterial.prototype, "disableLighting", void 0);
  61456. __decorate([
  61457. BABYLON.serialize()
  61458. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  61459. __decorate([
  61460. BABYLON.serialize()
  61461. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  61462. __decorate([
  61463. BABYLON.serialize()
  61464. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  61465. __decorate([
  61466. BABYLON.serialize()
  61467. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  61468. return PBRMaterial;
  61469. })(BABYLON.Material);
  61470. BABYLON.PBRMaterial = PBRMaterial;
  61471. })(BABYLON || (BABYLON = {}));
  61472. 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}"};
  61473. 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"};
  61474. 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={}));";
  61475. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  61476. module.exports = BABYLON;
  61477. };